query
stringlengths
10
3.85k
ru_query
stringlengths
9
3.76k
document
stringlengths
17
430k
metadata
dict
negatives
listlengths
97
100
negative_scores
listlengths
97
100
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
UpdateProtectBranch saves branch protection options. If ID is 0, it creates a new record. Otherwise, updates existing record.
UpdateProtectBranch сохраняет параметры защиты ветки. Если ID равно 0, создаётся новый запись. В противном случае, обновляется существующая запись.
func UpdateProtectBranch(protectBranch *ProtectBranch) (err error) { sess := x.NewSession() defer sess.Close() if err = sess.Begin(); err != nil { return err } if protectBranch.ID == 0 { if _, err = sess.Insert(protectBranch); err != nil { return fmt.Errorf("Insert: %v", err) } } if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { return fmt.Errorf("Update: %v", err) } return sess.Commit() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func EditBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation PATCH /repos/{owner}/{repo}/branch_protections/{name} repository repoEditBranchProtection\n\t// ---\n\t// summary: Edit a branch protections for a repository. Only fields that are set will be changed\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// - name: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/EditBranchProtectionOption\"\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\t// \"422\":\n\t// \"$ref\": \"#/responses/validationError\"\n\tform := web.GetForm(ctx).(*api.EditBranchProtectionOption)\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tprotectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif protectBranch == nil || protectBranch.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tif form.EnablePush != nil {\n\t\tif !*form.EnablePush {\n\t\t\tprotectBranch.CanPush = false\n\t\t\tprotectBranch.EnableWhitelist = false\n\t\t\tprotectBranch.WhitelistDeployKeys = false\n\t\t} else {\n\t\t\tprotectBranch.CanPush = true\n\t\t\tif form.EnablePushWhitelist != nil {\n\t\t\t\tif !*form.EnablePushWhitelist {\n\t\t\t\t\tprotectBranch.EnableWhitelist = false\n\t\t\t\t\tprotectBranch.WhitelistDeployKeys = false\n\t\t\t\t} else {\n\t\t\t\t\tprotectBranch.EnableWhitelist = true\n\t\t\t\t\tif form.PushWhitelistDeployKeys != nil {\n\t\t\t\t\t\tprotectBranch.WhitelistDeployKeys = *form.PushWhitelistDeployKeys\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif form.EnableMergeWhitelist != nil {\n\t\tprotectBranch.EnableMergeWhitelist = *form.EnableMergeWhitelist\n\t}\n\n\tif form.EnableStatusCheck != nil {\n\t\tprotectBranch.EnableStatusCheck = *form.EnableStatusCheck\n\t}\n\n\tif form.StatusCheckContexts != nil {\n\t\tprotectBranch.StatusCheckContexts = form.StatusCheckContexts\n\t}\n\n\tif form.RequiredApprovals != nil && *form.RequiredApprovals >= 0 {\n\t\tprotectBranch.RequiredApprovals = *form.RequiredApprovals\n\t}\n\n\tif form.EnableApprovalsWhitelist != nil {\n\t\tprotectBranch.EnableApprovalsWhitelist = *form.EnableApprovalsWhitelist\n\t}\n\n\tif form.BlockOnRejectedReviews != nil {\n\t\tprotectBranch.BlockOnRejectedReviews = *form.BlockOnRejectedReviews\n\t}\n\n\tif form.BlockOnOfficialReviewRequests != nil {\n\t\tprotectBranch.BlockOnOfficialReviewRequests = *form.BlockOnOfficialReviewRequests\n\t}\n\n\tif form.DismissStaleApprovals != nil {\n\t\tprotectBranch.DismissStaleApprovals = *form.DismissStaleApprovals\n\t}\n\n\tif form.RequireSignedCommits != nil {\n\t\tprotectBranch.RequireSignedCommits = *form.RequireSignedCommits\n\t}\n\n\tif form.ProtectedFilePatterns != nil {\n\t\tprotectBranch.ProtectedFilePatterns = *form.ProtectedFilePatterns\n\t}\n\n\tif form.UnprotectedFilePatterns != nil {\n\t\tprotectBranch.UnprotectedFilePatterns = *form.UnprotectedFilePatterns\n\t}\n\n\tif form.BlockOnOutdatedBranch != nil {\n\t\tprotectBranch.BlockOnOutdatedBranch = *form.BlockOnOutdatedBranch\n\t}\n\n\tvar whitelistUsers []int64\n\tif form.PushWhitelistUsernames != nil {\n\t\twhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\twhitelistUsers = protectBranch.WhitelistUserIDs\n\t}\n\tvar mergeWhitelistUsers []int64\n\tif form.MergeWhitelistUsernames != nil {\n\t\tmergeWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tmergeWhitelistUsers = protectBranch.MergeWhitelistUserIDs\n\t}\n\tvar approvalsWhitelistUsers []int64\n\tif form.ApprovalsWhitelistUsernames != nil {\n\t\tapprovalsWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tapprovalsWhitelistUsers = protectBranch.ApprovalsWhitelistUserIDs\n\t}\n\n\tvar whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64\n\tif repo.Owner.IsOrganization() {\n\t\tif form.PushWhitelistTeams != nil {\n\t\t\twhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\twhitelistTeams = protectBranch.WhitelistTeamIDs\n\t\t}\n\t\tif form.MergeWhitelistTeams != nil {\n\t\t\tmergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tmergeWhitelistTeams = protectBranch.MergeWhitelistTeamIDs\n\t\t}\n\t\tif form.ApprovalsWhitelistTeams != nil {\n\t\t\tapprovalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tapprovalsWhitelistTeams = protectBranch.ApprovalsWhitelistTeamIDs\n\t\t}\n\t}\n\n\terr = git_model.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, git_model.WhitelistOptions{\n\t\tUserIDs: whitelistUsers,\n\t\tTeamIDs: whitelistTeams,\n\t\tMergeUserIDs: mergeWhitelistUsers,\n\t\tMergeTeamIDs: mergeWhitelistTeams,\n\t\tApprovalsUserIDs: approvalsWhitelistUsers,\n\t\tApprovalsTeamIDs: approvalsWhitelistTeams,\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"UpdateProtectBranch\", err)\n\t\treturn\n\t}\n\n\tisPlainRule := !git_model.IsRuleNameSpecial(bpName)\n\tvar isBranchExist bool\n\tif isPlainRule {\n\t\tisBranchExist = git.IsBranchExist(ctx.Req.Context(), ctx.Repo.Repository.RepoPath(), bpName)\n\t}\n\n\tif isBranchExist {\n\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, bpName); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPrsForBaseBranch\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !isPlainRule {\n\t\t\tif ctx.Repo.GitRepo == nil {\n\t\t\t\tctx.Repo.GitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.RepoPath())\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"OpenRepository\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer func() {\n\t\t\t\t\tctx.Repo.GitRepo.Close()\n\t\t\t\t\tctx.Repo.GitRepo = nil\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\t// FIXME: since we only need to recheck files protected rules, we could improve this\n\t\t\tmatchedBranches, err := git_model.FindAllMatchedBranches(ctx, ctx.Repo.Repository.ID, protectBranch.RuleName)\n\t\t\tif err != nil {\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"FindAllMatchedBranches\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, branchName := range matchedBranches {\n\t\t\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, branchName); err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPrsForBaseBranch\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reload from db to ensure get all whitelists\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchBy\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != ctx.Repo.Repository.ID {\n\t\tctx.Error(http.StatusInternalServerError, \"New branch protection not found\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, convert.ToBranchProtection(bp))\n}", "func (c *client) UpdateBranchProtection(org, repo, branch string, config BranchProtectionRequest) error {\n\tdurationLogger := c.log(\"UpdateBranchProtection\", org, repo, branch, config)\n\tdefer durationLogger()\n\n\t_, err := c.request(&request{\n\t\taccept: \"application/vnd.github.luke-cage-preview+json\", // for required_approving_review_count\n\t\tmethod: http.MethodPut,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/branches/%s/protection\", org, repo, branch),\n\t\torg: org,\n\t\trequestBody: config,\n\t\texitCodes: []int{200},\n\t}, nil)\n\treturn err\n}", "func (p GithubRepoHost) UpdateBranchProtection(repoID string, rule BranchProtectionRule) error {\n\tif isDebug() {\n\t\tfmt.Printf(\"Updating branch protection on %s\\n\", repoID)\n\t}\n\n\trules := fetchBranchProtectionRules()\n\tinput := githubv4.UpdateBranchProtectionRuleInput{\n\t\tBranchProtectionRuleID: rule.ID,\n\t\tPattern: githubv4.NewString(githubv4.String(rules.Pattern)),\n\t\tDismissesStaleReviews: githubv4.NewBoolean(githubv4.Boolean(rules.DismissesStaleReviews)),\n\t\tIsAdminEnforced: githubv4.NewBoolean(githubv4.Boolean(rules.IsAdminEnforced)),\n\t\tRequiresApprovingReviews: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresApprovingReviews)),\n\t\tRequiredApprovingReviewCount: githubv4.NewInt(githubv4.Int(rules.RequiredApprovingReviewCount)),\n\t\tRequiresStatusChecks: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresStatusChecks)),\n\t\tRequiredStatusCheckContexts: &[]githubv4.String{\n\t\t\t*githubv4.NewString(\"build\"),\n\t\t},\n\t}\n\n\tvar m UpdateBranchProtectionRuleMutation\n\tclient := buildClient()\n\terr := client.Mutate(context.Background(), &m, input, nil)\n\treturn err\n}", "func UpdateBranchProtection() error {\n\tvar wg sync.WaitGroup\n\trequests, err := getBranchProtectionRequests()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twg.Add(len(requests))\n\towner, repo := getOwnerRepo()\n\n\tfor _, bp := range requests {\n\t\tgo func(bp BranchProtection) {\n\t\t\tdefer wg.Done()\n\t\t\t_, _, err := cli.Repositories.UpdateBranchProtection(ctx, owner, repo, bp.Branch, bp.Protection)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\t_, err = fmt.Fprintln(writer, fmt.Sprintf(\"branch %v has been protected\", bp.Branch))\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}(bp)\n\t}\n\n\twg.Wait()\n\n\treturn nil\n}", "func (mr *MockRepositoryClientMockRecorder) UpdateBranchProtection(org, repo, branch, config interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateBranchProtection\", reflect.TypeOf((*MockRepositoryClient)(nil).UpdateBranchProtection), org, repo, branch, config)\n}", "func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whitelistUserIDs, whitelistTeamIDs string) (err error) {\n\tif err = repo.GetOwner(); err != nil {\n\t\treturn fmt.Errorf(\"GetOwner: %v\", err)\n\t} else if !repo.Owner.IsOrganization() {\n\t\treturn fmt.Errorf(\"expect repository owner to be an organization\")\n\t}\n\n\thasUsersChanged := false\n\tvalidUserIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistUserIDs, \",\"))\n\tif protectBranch.WhitelistUserIDs != whitelistUserIDs {\n\t\thasUsersChanged = true\n\t\tuserIDs := tool.StringsToInt64s(strings.Split(whitelistUserIDs, \",\"))\n\t\tvalidUserIDs = make([]int64, 0, len(userIDs))\n\t\tfor _, userID := range userIDs {\n\t\t\tif !Perms.Authorize(context.TODO(), userID, repo.ID, AccessModeWrite,\n\t\t\t\tAccessModeOptions{\n\t\t\t\t\tOwnerID: repo.OwnerID,\n\t\t\t\t\tPrivate: repo.IsPrivate,\n\t\t\t\t},\n\t\t\t) {\n\t\t\t\tcontinue // Drop invalid user ID\n\t\t\t}\n\n\t\t\tvalidUserIDs = append(validUserIDs, userID)\n\t\t}\n\n\t\tprotectBranch.WhitelistUserIDs = strings.Join(tool.Int64sToStrings(validUserIDs), \",\")\n\t}\n\n\thasTeamsChanged := false\n\tvalidTeamIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistTeamIDs, \",\"))\n\tif protectBranch.WhitelistTeamIDs != whitelistTeamIDs {\n\t\thasTeamsChanged = true\n\t\tteamIDs := tool.StringsToInt64s(strings.Split(whitelistTeamIDs, \",\"))\n\t\tteams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v\", repo.OwnerID, repo.ID, err)\n\t\t}\n\t\tvalidTeamIDs = make([]int64, 0, len(teams))\n\t\tfor i := range teams {\n\t\t\tif teams[i].HasWriteAccess() && com.IsSliceContainsInt64(teamIDs, teams[i].ID) {\n\t\t\t\tvalidTeamIDs = append(validTeamIDs, teams[i].ID)\n\t\t\t}\n\t\t}\n\n\t\tprotectBranch.WhitelistTeamIDs = strings.Join(tool.Int64sToStrings(validTeamIDs), \",\")\n\t}\n\n\t// Make sure protectBranch.ID is not 0 for whitelists\n\tif protectBranch.ID == 0 {\n\t\tif _, err = x.Insert(protectBranch); err != nil {\n\t\t\treturn fmt.Errorf(\"Insert: %v\", err)\n\t\t}\n\t}\n\n\t// Merge users and members of teams\n\tvar whitelists []*ProtectBranchWhitelist\n\tif hasUsersChanged || hasTeamsChanged {\n\t\tmergedUserIDs := make(map[int64]bool)\n\t\tfor _, userID := range validUserIDs {\n\t\t\t// Empty whitelist users can cause an ID with 0\n\t\t\tif userID != 0 {\n\t\t\t\tmergedUserIDs[userID] = true\n\t\t\t}\n\t\t}\n\n\t\tfor _, teamID := range validTeamIDs {\n\t\t\tmembers, err := GetTeamMembers(teamID)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"GetTeamMembers [team_id: %d]: %v\", teamID, err)\n\t\t\t}\n\n\t\t\tfor i := range members {\n\t\t\t\tmergedUserIDs[members[i].ID] = true\n\t\t\t}\n\t\t}\n\n\t\twhitelists = make([]*ProtectBranchWhitelist, 0, len(mergedUserIDs))\n\t\tfor userID := range mergedUserIDs {\n\t\t\twhitelists = append(whitelists, &ProtectBranchWhitelist{\n\t\t\t\tProtectBranchID: protectBranch.ID,\n\t\t\t\tRepoID: repo.ID,\n\t\t\t\tName: protectBranch.Name,\n\t\t\t\tUserID: userID,\n\t\t\t})\n\t\t}\n\t}\n\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\tif err = sess.Begin(); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {\n\t\treturn fmt.Errorf(\"Update: %v\", err)\n\t}\n\n\t// Refresh whitelists\n\tif hasUsersChanged || hasTeamsChanged {\n\t\tif _, err = sess.Delete(&ProtectBranchWhitelist{ProtectBranchID: protectBranch.ID}); err != nil {\n\t\t\treturn fmt.Errorf(\"delete old protect branch whitelists: %v\", err)\n\t\t} else if _, err = sess.Insert(whitelists); err != nil {\n\t\t\treturn fmt.Errorf(\"insert new protect branch whitelists: %v\", err)\n\t\t}\n\t}\n\n\treturn sess.Commit()\n}", "func (mr *MockClientMockRecorder) UpdateBranchProtection(org, repo, branch, config interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateBranchProtection\", reflect.TypeOf((*MockClient)(nil).UpdateBranchProtection), org, repo, branch, config)\n}", "func (m *MockClient) UpdateBranchProtection(org, repo, branch string, config github.BranchProtectionRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateBranchProtection\", org, repo, branch, config)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (p GithubRepoHost) AddBranchProtection(repoID string) (BranchProtectionRule, error) {\n\tif isDebug() {\n\t\tfmt.Printf(\"Adding branch protection on %s\\n\", repoID)\n\t}\n\n\trules := fetchBranchProtectionRules()\n\tinput := githubv4.CreateBranchProtectionRuleInput{\n\t\tRepositoryID: repoID,\n\t\tPattern: *githubv4.NewString(githubv4.String(rules.Pattern)),\n\t\tDismissesStaleReviews: githubv4.NewBoolean(githubv4.Boolean(rules.DismissesStaleReviews)),\n\t\tIsAdminEnforced: githubv4.NewBoolean(githubv4.Boolean(rules.IsAdminEnforced)),\n\t\tRequiresApprovingReviews: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresApprovingReviews)),\n\t\tRequiredApprovingReviewCount: githubv4.NewInt(githubv4.Int(rules.RequiredApprovingReviewCount)),\n\t\tRequiresStatusChecks: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresStatusChecks)),\n\t}\n\n\tchecks := make([]githubv4.String, len(rules.RequiredStatusCheckContexts))\n\tfor i, name := range rules.RequiredStatusCheckContexts {\n\t\tchecks[i] = *githubv4.NewString(githubv4.String(name))\n\t}\n\tinput.RequiredStatusCheckContexts = &checks\n\n\tvar m CreateRuleMutation\n\tclient := buildClient()\n\terr := client.Mutate(context.Background(), &m, input, nil)\n\treturn m.CreateBranchProtectionRule.BranchProtectionRule, err\n}", "func (m *MockRepositoryClient) UpdateBranchProtection(org, repo, branch string, config github.BranchProtectionRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateBranchProtection\", org, repo, branch, config)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func CreateBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation POST /repos/{owner}/{repo}/branch_protections repository repoCreateBranchProtection\n\t// ---\n\t// summary: Create a branch protections for a repository\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: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/CreateBranchProtectionOption\"\n\t// responses:\n\t// \"201\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"403\":\n\t// \"$ref\": \"#/responses/forbidden\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\t// \"422\":\n\t// \"$ref\": \"#/responses/validationError\"\n\n\tform := web.GetForm(ctx).(*api.CreateBranchProtectionOption)\n\trepo := ctx.Repo.Repository\n\n\truleName := form.RuleName\n\tif ruleName == \"\" {\n\t\truleName = form.BranchName //nolint\n\t}\n\tif len(ruleName) == 0 {\n\t\tctx.Error(http.StatusBadRequest, \"both rule_name and branch_name are empty\", \"both rule_name and branch_name are empty\")\n\t\treturn\n\t}\n\n\tisPlainRule := !git_model.IsRuleNameSpecial(ruleName)\n\tvar isBranchExist bool\n\tif isPlainRule {\n\t\tisBranchExist = git.IsBranchExist(ctx.Req.Context(), ctx.Repo.Repository.RepoPath(), ruleName)\n\t}\n\n\tprotectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, ruleName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectBranchOfRepoByName\", err)\n\t\treturn\n\t} else if protectBranch != nil {\n\t\tctx.Error(http.StatusForbidden, \"Create branch protection\", \"Branch protection already exist\")\n\t\treturn\n\t}\n\n\tvar requiredApprovals int64\n\tif form.RequiredApprovals > 0 {\n\t\trequiredApprovals = form.RequiredApprovals\n\t}\n\n\twhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tmergeWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tapprovalsWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tvar whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64\n\tif repo.Owner.IsOrganization() {\n\t\twhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t\tmergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t\tapprovalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tprotectBranch = &git_model.ProtectedBranch{\n\t\tRepoID: ctx.Repo.Repository.ID,\n\t\tRuleName: ruleName,\n\t\tCanPush: form.EnablePush,\n\t\tEnableWhitelist: form.EnablePush && form.EnablePushWhitelist,\n\t\tEnableMergeWhitelist: form.EnableMergeWhitelist,\n\t\tWhitelistDeployKeys: form.EnablePush && form.EnablePushWhitelist && form.PushWhitelistDeployKeys,\n\t\tEnableStatusCheck: form.EnableStatusCheck,\n\t\tStatusCheckContexts: form.StatusCheckContexts,\n\t\tEnableApprovalsWhitelist: form.EnableApprovalsWhitelist,\n\t\tRequiredApprovals: requiredApprovals,\n\t\tBlockOnRejectedReviews: form.BlockOnRejectedReviews,\n\t\tBlockOnOfficialReviewRequests: form.BlockOnOfficialReviewRequests,\n\t\tDismissStaleApprovals: form.DismissStaleApprovals,\n\t\tRequireSignedCommits: form.RequireSignedCommits,\n\t\tProtectedFilePatterns: form.ProtectedFilePatterns,\n\t\tUnprotectedFilePatterns: form.UnprotectedFilePatterns,\n\t\tBlockOnOutdatedBranch: form.BlockOnOutdatedBranch,\n\t}\n\n\terr = git_model.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, git_model.WhitelistOptions{\n\t\tUserIDs: whitelistUsers,\n\t\tTeamIDs: whitelistTeams,\n\t\tMergeUserIDs: mergeWhitelistUsers,\n\t\tMergeTeamIDs: mergeWhitelistTeams,\n\t\tApprovalsUserIDs: approvalsWhitelistUsers,\n\t\tApprovalsTeamIDs: approvalsWhitelistTeams,\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"UpdateProtectBranch\", err)\n\t\treturn\n\t}\n\n\tif isBranchExist {\n\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, ruleName); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPRsForBaseBranch\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !isPlainRule {\n\t\t\tif ctx.Repo.GitRepo == nil {\n\t\t\t\tctx.Repo.GitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.RepoPath())\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"OpenRepository\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer func() {\n\t\t\t\t\tctx.Repo.GitRepo.Close()\n\t\t\t\t\tctx.Repo.GitRepo = nil\n\t\t\t\t}()\n\t\t\t}\n\t\t\t// FIXME: since we only need to recheck files protected rules, we could improve this\n\t\t\tmatchedBranches, err := git_model.FindAllMatchedBranches(ctx, ctx.Repo.Repository.ID, ruleName)\n\t\t\tif err != nil {\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"FindAllMatchedBranches\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, branchName := range matchedBranches {\n\t\t\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, branchName); err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPRsForBaseBranch\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reload from db to get all whitelists\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, ctx.Repo.Repository.ID, ruleName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != ctx.Repo.Repository.ID {\n\t\tctx.Error(http.StatusInternalServerError, \"New branch protection not found\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusCreated, convert.ToBranchProtection(bp))\n}", "func DeleteBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation DELETE /repos/{owner}/{repo}/branch_protections/{name} repository repoDeleteBranchProtection\n\t// ---\n\t// summary: Delete a specific branch protection for the repository\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// responses:\n\t// \"204\":\n\t// \"$ref\": \"#/responses/empty\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tif err := git_model.DeleteProtectedBranch(ctx, ctx.Repo.Repository.ID, bp.ID); err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"DeleteProtectedBranch\", err)\n\t\treturn\n\t}\n\n\tctx.Status(http.StatusNoContent)\n}", "func (c *client) RemoveBranchProtection(org, repo, branch string) error {\n\tdurationLogger := c.log(\"RemoveBranchProtection\", org, repo, branch)\n\tdefer durationLogger()\n\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodDelete,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/branches/%s/protection\", org, repo, branch),\n\t\torg: org,\n\t\texitCodes: []int{204},\n\t}, nil)\n\treturn err\n}", "func (m *MarkerIndexBranchIDMapping) SetBranchID(index markers.Index, branchID ledgerstate.BranchID) {\n\tm.mappingMutex.Lock()\n\tdefer m.mappingMutex.Unlock()\n\n\tm.mapping.Set(index, branchID)\n}", "func (a *Client) UpdateBranch(params *UpdateBranchParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateBranchOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewUpdateBranchParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"updateBranch\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/vcs/branch/{branchID}\",\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: &UpdateBranchReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*UpdateBranchOK)\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 updateBranch: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (r *SettingRepository) EditBranchByID(branch *models.Branch) error {\n\terr := r.C.Update(bson.M{\"_id\": branch.ID},\n\t\tbson.M{\"$set\": bson.M{\n\t\t\t\"name\": branch.Name,\n\t\t\t\"updatedat\": time.Now(),\n\t\t\t\"status\": branch.Status,\n\t\t}})\n\treturn err\n}", "func (m *MarkerBranchIDMappingManager) SetBranchID(marker *markers.Marker, branchID ledgerstate.BranchID) {\n\tm.tangle.Storage.MarkerIndexBranchIDMapping(marker.SequenceID(), NewMarkerIndexBranchIDMapping).Consume(func(markerIndexBranchIDMapping *MarkerIndexBranchIDMapping) {\n\t\tmarkerIndexBranchIDMapping.SetBranchID(marker.Index(), branchID)\n\t})\n}", "func GetProtectBranchesByRepoID(repoID int64) ([]*ProtectBranch, error) {\n\tprotectBranches := make([]*ProtectBranch, 0, 2)\n\treturn protectBranches, x.Where(\"repo_id = ? and protected = ?\", repoID, true).Asc(\"name\").Find(&protectBranches)\n}", "func (m *MarkerIndexBranchIDMapping) Update(other objectstorage.StorableObject) {\n\tpanic(\"updates disabled\")\n}", "func NewBranchProtection(ctx *pulumi.Context,\n\tname string, args *BranchProtectionArgs, opts ...pulumi.ResourceOption) (*BranchProtection, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Branch == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Branch'\")\n\t}\n\tif args.Project == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Project'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource BranchProtection\n\terr := ctx.RegisterResource(\"gitlab:index/branchProtection:BranchProtection\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *UpdateTemplateSyncConfigInput) SetBranch(v string) *UpdateTemplateSyncConfigInput {\n\ts.Branch = &v\n\treturn s\n}", "func handleRepo(ctx context.Context, client *github.Client, repo *github.Repository) error {\n\topt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tbranches, resp, err := client.Repositories.ListBranches(ctx, *repo.Owner.Login, *repo.Name, opt)\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, branch := range branches {\n\t\tif branch.GetName() == \"master\" && in(orgs, *repo.Owner.Login) {\n\t\t\t// we must get the individual branch for the branch protection to work\n\t\t\tb, _, err := client.Repositories.GetBranch(ctx, *repo.Owner.Login, *repo.Name, branch.GetName())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// return early if it is already protected\n\t\t\tif b.GetProtected() {\n\t\t\t\tfmt.Printf(\"[OK] %s:%s is already protected\\n\", *repo.FullName, b.GetName())\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfmt.Printf(\"[UPDATE] %s:%s will be changed to protected\\n\", *repo.FullName, b.GetName())\n\t\t\tif dryrun {\n\t\t\t\t// return early\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// set the branch to be protected\n\t\t\tif _, _, err := client.Repositories.UpdateBranchProtection(ctx, *repo.Owner.Login, *repo.Name, b.GetName(), &github.ProtectionRequest{\n\t\t\t\tRequiredStatusChecks: &github.RequiredStatusChecks{\n\t\t\t\t\tStrict: false,\n\t\t\t\t\tContexts: []string{},\n\t\t\t\t},\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func UpdateCompanyBranchHyCompanybranchBadRequest(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, error) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\treturn nil, e\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\treturn nil, _e\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 400 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 400\", rw.Code)\n\t}\n\tvar mt error\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(error)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of error\", resp, resp)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func UpdateCompanyBranchHyCompanybranchOKID(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.CompanyID) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.CompanyID\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.CompanyID)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.CompanyID\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func (s *UpdateServiceSyncConfigInput) SetBranch(v string) *UpdateServiceSyncConfigInput {\n\ts.Branch = &v\n\treturn s\n}", "func (s *CreateTemplateSyncConfigInput) SetBranch(v string) *CreateTemplateSyncConfigInput {\n\ts.Branch = &v\n\treturn s\n}", "func (v *VersionHistory) SetBranchToken(\n\tinputToken []byte,\n) error {\n\n\ttoken := make([]byte, len(inputToken))\n\tcopy(token, inputToken)\n\tv.BranchToken = token\n\treturn nil\n}", "func UpdateCgroupDeviceWriteBps(pid, innerPath, value string) error {\n\tif pid == \"0\" {\n\t\treturn nil\n\t}\n\n\tcgroupPath, err := FindCgroupPath(pid, \"blkio\", innerPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpath := filepath.Join(cgroupPath, \"blkio.throttle.write_bps_device\")\n\tif err := ioutil.WriteFile(path, []byte(value), 0600); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (service *Service) UpdateProtectionMode(d9SecurityGroupID, protectionMode string) (*CloudSecurityGroupResponse, *http.Response, error) {\n\tif protectionMode != \"FullManage\" && protectionMode != \"ReadOnly\" {\n\t\treturn nil, nil, fmt.Errorf(\"protection mode can be FullManage or ReadOnly\")\n\t}\n\n\tv := new(CloudSecurityGroupResponse)\n\trelativeURL := fmt.Sprintf(\"%s/%s/%s\", awsSgResourcePath, d9SecurityGroupID, awsSgResourceProtectionMode)\n\tbody := UpdateProtectionModeQueryParameters{\n\t\tProtectionMode: protectionMode,\n\t}\n\n\tresp, err := service.Client.NewRequestDo(\"POST\", relativeURL, nil, body, v)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn v, resp, nil\n}", "func (mr *MockRepositoryClientMockRecorder) RemoveBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RemoveBranchProtection\", reflect.TypeOf((*MockRepositoryClient)(nil).RemoveBranchProtection), org, repo, branch)\n}", "func (s *CreateServiceSyncConfigInput) SetBranch(v string) *CreateServiceSyncConfigInput {\n\ts.Branch = &v\n\treturn s\n}", "func (b *BranchDAG) SetBranchConfirmed(branchID BranchID) (err error) {\n\tif b.InclusionState(branchID) == Confirmed {\n\t\treturn\n\t}\n\n\tif _, branchErr := b.SetBranchMonotonicallyLiked(branchID, true); branchErr != nil {\n\t\terr = errors.Errorf(\"failed to set Branch with %s to be monotonically liked: %w\", branchID, branchErr)\n\t\treturn\n\t}\n\n\tif _, branchErr := b.SetBranchFinalized(branchID, true); branchErr != nil {\n\t\terr = errors.Errorf(\"failed to set Branch with %s to be finalized: %w\", branchID, branchErr)\n\t\treturn\n\t}\n\n\treturn\n}", "func (patchwork *Patchwork) Branch(branch string) {\n\tpatchwork.branch = branch\n}", "func (mr *MockSendUpdateQueryMockRecorder) UpdateBranch(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateBranch\", reflect.TypeOf((*MockSendUpdateQuery)(nil).UpdateBranch), arg0, arg1, arg2)\n}", "func (s *TemplateSyncConfig) SetBranch(v string) *TemplateSyncConfig {\n\ts.Branch = &v\n\treturn s\n}", "func (r *SettingRepository) AddBranchByOrgID(orgID string) (branch models.Branch, err error) {\n\tobjID := bson.NewObjectId()\n\tbranch.ID = objID\n\tbranch.OrgID = bson.ObjectIdHex(orgID)\n\tbranch.Status = \"Active\"\n\tbranch.CreatedAt = time.Now()\n\tbranch.UpdatedAt = time.Now()\n\n\terr = r.C.Insert(&branch)\n\treturn\n}", "func (mr *MockClientMockRecorder) RemoveBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RemoveBranchProtection\", reflect.TypeOf((*MockClient)(nil).RemoveBranchProtection), org, repo, branch)\n}", "func UpdateCompanyBranchHyCompanybranchNotFound(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) {}\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 404 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 404\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (m *MockSendUpdateQuery) UpdateBranch(arg0 context.Context, arg1 interfaces.NewBranch, arg2 bool) error {\n\tret := m.ctrl.Call(m, \"UpdateBranch\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func UpdateLimitAccount(currentLimit float64) {\n\n\terr := utils.CheckTempFile(PathFileC)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tjsonFile, err := os.Open(PathFileC)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer jsonFile.Close()\n\n\taccountJSON, err := ioutil.ReadAll(jsonFile)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tvar account models.Account\n\n\terr = json.Unmarshal(accountJSON, &account)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\taccount.Accounts.AvailableLimit = currentLimit\n\n\taccountJSON, err = json.Marshal(account)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\terr = ioutil.WriteFile(PathFileC, accountJSON, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (c APIClient) SetBranch(repoName string, commit string, branch string) error {\n\treturn c.CreateBranch(repoName, branch, commit, nil)\n}", "func ListBranchProtections(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/branch_protections repository repoListBranchProtection\n\t// ---\n\t// summary: List branch protections for a repository\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// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/BranchProtectionList\"\n\n\trepo := ctx.Repo.Repository\n\tbps, err := git_model.FindRepoProtectedBranchRules(ctx, repo.ID)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranches\", err)\n\t\treturn\n\t}\n\tapiBps := make([]*api.BranchProtection, len(bps))\n\tfor i := range bps {\n\t\tapiBps[i] = convert.ToBranchProtection(bps[i])\n\t}\n\n\tctx.JSON(http.StatusOK, apiBps)\n}", "func (c *client) GetBranchProtection(org, repo, branch string) (*BranchProtection, error) {\n\tdurationLogger := c.log(\"GetBranchProtection\", org, repo, branch)\n\tdefer durationLogger()\n\n\tcode, body, err := c.requestRaw(&request{\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/branches/%s/protection\", org, repo, branch),\n\t\torg: org,\n\t\t// GitHub returns 404 for this call if either:\n\t\t// - The branch is not protected\n\t\t// - The access token used does not have sufficient privileges\n\t\t// We therefore need to introspect the response body.\n\t\texitCodes: []int{200, 404},\n\t})\n\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase code == 200:\n\t\tvar bp BranchProtection\n\t\tif err := json.Unmarshal(body, &bp); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &bp, nil\n\tcase code == 404:\n\t\t// continue\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected status code: %d\", code)\n\t}\n\n\tvar ge githubError\n\tif err := json.Unmarshal(body, &ge); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the error was because the branch is not protected, we return a\n\t// nil pointer to indicate this.\n\tif ge.Message == \"Branch not protected\" {\n\t\treturn nil, nil\n\t}\n\n\t// Otherwise we got some other 404 error.\n\treturn nil, fmt.Errorf(\"getting branch protection 404: %s\", ge.Message)\n}", "func (s *GetRepositorySyncStatusInput) SetBranch(v string) *GetRepositorySyncStatusInput {\n\ts.Branch = &v\n\treturn s\n}", "func UpdateCompanyBranchHyCompanybranchOK(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.Company) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.Company\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.Company)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.Company\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func (client *Client) UpdateLoadBalancerProtectionWithOptions(request *UpdateLoadBalancerProtectionRequest, runtime *util.RuntimeOptions) (_result *UpdateLoadBalancerProtectionResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tbody := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.ClientToken)) {\n\t\tbody[\"ClientToken\"] = request.ClientToken\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.DeletionProtectionEnabled)) {\n\t\tbody[\"DeletionProtectionEnabled\"] = request.DeletionProtectionEnabled\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.DeletionProtectionReason)) {\n\t\tbody[\"DeletionProtectionReason\"] = request.DeletionProtectionReason\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.DryRun)) {\n\t\tbody[\"DryRun\"] = request.DryRun\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.LoadBalancerId)) {\n\t\tbody[\"LoadBalancerId\"] = request.LoadBalancerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ModificationProtectionReason)) {\n\t\tbody[\"ModificationProtectionReason\"] = request.ModificationProtectionReason\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ModificationProtectionStatus)) {\n\t\tbody[\"ModificationProtectionStatus\"] = request.ModificationProtectionStatus\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.RegionId)) {\n\t\tbody[\"RegionId\"] = request.RegionId\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tBody: openapiutil.ParseToMap(body),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"UpdateLoadBalancerProtection\"),\n\t\tVersion: tea.String(\"2022-04-30\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &UpdateLoadBalancerProtectionResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (s *ServiceSyncConfig) SetBranch(v string) *ServiceSyncConfig {\n\ts.Branch = &v\n\treturn s\n}", "func GetBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/branch_protections/{name} repository repoGetBranchProtection\n\t// ---\n\t// summary: Get a specific branch protection for the repository\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, convert.ToBranchProtection(bp))\n}", "func (r *WorkbookWorksheetProtectionRequest) Update(ctx context.Context, reqObj *WorkbookWorksheetProtection) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func SetDefaultBranch(ctx context.Context, ownerName, repoName, branch string) ResponseExtra {\n\treqURL := setting.LocalURL + fmt.Sprintf(\"api/internal/hook/set-default-branch/%s/%s/%s\",\n\t\turl.PathEscape(ownerName),\n\t\turl.PathEscape(repoName),\n\t\turl.PathEscape(branch),\n\t)\n\treq := newInternalRequest(ctx, reqURL, \"POST\")\n\t_, extra := requestJSONResp(req, &responseText{})\n\treturn extra\n}", "func (l *BranchLocker) Writer(ctx context.Context, repositoryID graveler.RepositoryID, branchID graveler.BranchID, lockedFn graveler.BranchLockerFunc) (interface{}, error) {\n\twriterLockKey, _ := calculateBranchLockerKeys(repositoryID, branchID)\n\treturn l.db.Transact(func(tx db.Tx) (interface{}, error) {\n\t\t// try lock committer key\n\t\tvar locked bool\n\t\terr := tx.GetPrimitive(&locked, `SELECT pg_try_advisory_xact_lock_shared($1)`, writerLockKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w (%d): %s\", graveler.ErrLockNotAcquired, writerLockKey, err)\n\t\t}\n\t\tif !locked {\n\t\t\treturn nil, fmt.Errorf(\"%w (%d)\", graveler.ErrLockNotAcquired, writerLockKey)\n\t\t}\n\t\treturn lockedFn()\n\t}, db.WithContext(ctx), db.WithIsolationLevel(pgx.ReadCommitted))\n}", "func (client *Client) UpdateLoadBalancerProtection(request *UpdateLoadBalancerProtectionRequest) (_result *UpdateLoadBalancerProtectionResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &UpdateLoadBalancerProtectionResponse{}\n\t_body, _err := client.UpdateLoadBalancerProtectionWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (b *Booker) UpdateMessagesBranch(transactionID ledgerstate.TransactionID) {\n\tb.tangle.Utils.WalkMessageAndMetadata(func(message *Message, messageMetadata *MessageMetadata, walker *walker.Walker) {\n\t\tif messageMetadata.IsBooked() {\n\t\t\tinheritedBranch, inheritErr := b.tangle.LedgerState.InheritBranch(b.branchIDsOfParents(message).Add(b.branchIDOfPayload(message)))\n\t\t\tif inheritErr != nil {\n\t\t\t\tpanic(xerrors.Errorf(\"failed to inherit Branch when booking Message with %s: %w\", message.ID(), inheritErr))\n\t\t\t}\n\t\t\tif messageMetadata.SetBranchID(inheritedBranch) {\n\t\t\t\tfor _, approvingMessageID := range b.tangle.Utils.ApprovingMessageIDs(message.ID(), StrongApprover) {\n\t\t\t\t\twalker.Push(approvingMessageID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}, b.tangle.Storage.AttachmentMessageIDs(transactionID), true)\n}", "func (pu *PendingloanbindingUpdate) SetMainBranch(s string) *PendingloanbindingUpdate {\n\tpu.mutation.SetMainBranch(s)\n\treturn pu\n}", "func DestroyBranch(db *sqlx.DB, id int) (int64, error) {\n\n\t_, err := db.Exec(\"DELETE FROM branches WHERE id=$1\", id)\n\n\tif err != nil {\n\t\treturn 400, err\n\t}\n\n\treturn 200, nil\n}", "func (m *ProtectGroup) SetPrivacy(value *GroupPrivacy)() {\n err := m.GetBackingStore().Set(\"privacy\", value)\n if err != nil {\n panic(err)\n }\n}", "func (l *BranchLocker) Writer(ctx context.Context, repositoryID graveler.RepositoryID, branchID graveler.BranchID, lockedFn graveler.BranchLockerFunc) (interface{}, error) {\n\twriterLockKey := calculateBranchLockerKey(repositoryID, branchID)\n\treturn l.db.Transact(ctx, func(tx db.Tx) (interface{}, error) {\n\t\t// try to get a shared lock on the writer key\n\t\t_, err := tx.Exec(`SELECT pg_advisory_xact_lock_shared($1);`, writerLockKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w (%d): %s\", graveler.ErrLockNotAcquired, writerLockKey, err)\n\t\t}\n\t\treturn lockedFn()\n\t}, db.WithIsolationLevel(pgx.ReadCommitted))\n}", "func (s *PaymentStorage) UpdateBeneficiary(ctx context.Context, id aggregate.ID, beneficiary transaction.BankAccount) error {\n\tlogger := log.FromContext(ctx)\n\n\tjsBeneficiary, err := json.Marshal(beneficiary)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tquery := `UPDATE %[1]s \n\t\t\t SET attributes = attributes::jsonb || '{\"beneficiary_party\": %[2]s}'::jsonb\n\t\t\t WHERE id = $1`\n\tquery = fmt.Sprintf(query, s.table, string(jsBeneficiary))\n\n\tif logger != nil {\n\t\tlogger.Debugf(\"exec in transaction sql %s, values %+v\", query, []interface{}{\n\t\t\tid,\n\t\t})\n\t}\n\n\treturn execInTransaction(s.db, func(tx *sqlx.Tx) error {\n\t\t_, err := tx.ExecContext(ctx, query, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (puo *PendingloanbindingUpdateOne) SetMainBranch(s string) *PendingloanbindingUpdateOne {\n\tpuo.mutation.SetMainBranch(s)\n\treturn puo\n}", "func (buo *BankUpdateOne) AddBranchIDs(ids ...int) *BankUpdateOne {\n\tbuo.mutation.AddBranchIDs(ids...)\n\treturn buo\n}", "func (c *Client) UpdateBarcodeRule(br *BarcodeRule) error {\n\treturn c.UpdateBarcodeRules([]int64{br.Id.Get()}, br)\n}", "func (s *RepositorySyncDefinition) SetBranch(v string) *RepositorySyncDefinition {\n\ts.Branch = &v\n\treturn s\n}", "func (o BranchProtectionOutput) BranchProtectionId() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *BranchProtection) pulumi.IntOutput { return v.BranchProtectionId }).(pulumi.IntOutput)\n}", "func (mr *MockRepositoryClientMockRecorder) GetBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBranchProtection\", reflect.TypeOf((*MockRepositoryClient)(nil).GetBranchProtection), org, repo, branch)\n}", "func (t *Commit) SetBranch(v string) {\n\tt.Branch = &v\n}", "func (o BranchProtectionOutput) Branch() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BranchProtection) pulumi.StringOutput { return v.Branch }).(pulumi.StringOutput)\n}", "func (token *Token) Update(db *sqlx.DB) {\n\t\n\tif strings.TrimSpace(token.AccessToken) == \"\" || strings.TrimSpace(token.RefreshToken) == \"\" || token.RefreshTokenExpiry == 0 || token.AccessTokenExpiry == 0 || strings.TrimSpace(token.DeviceID) == \"\" || strings.TrimSpace(token.MacAddress) == \"\" || strings.TrimSpace(token.APIKey) == \"\" || token.Status == 0{\n\t\tfmt.Println(\"Missing Fields from tokens\")\n\t\treturn\n\t}\n\t\n\tif strings.TrimSpace(token.ID) == \"\" {\n\t\tfmt.Println(\"Empty ID\")\n\t\treturn\n\t}\n\n\tsql := \"UPDATE tokens SET access_token=?,access_token_time=?,access_token_expiry=?,user_id=?,status=?,api_key=?,refresh_token=?,refresh_token_time=?,refresh_token_expiry=?,device_id=?,mac_address=? WHERE id='\" + token.ID + \"'\"\n\n\t_, err := db.Exec(sql,\n\t\ttoken.AccessToken,\n\t\ttoken.AccessTokenTime,\n\t\ttoken.AccessTokenExpiry,\n\t\ttoken.UserID,\n\t\ttoken.Status,\n\t\ttoken.APIKey,\n\t\ttoken.RefreshToken,\n\t\ttoken.RefreshTokenTime,\n\t\ttoken.RefreshTokenExpiry,\n\t\ttoken.DeviceID,\n\t\ttoken.MacAddress,\n\t)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func StoreBranch(db *sqlx.DB, branch *Branch) (int64, error) {\n\n\tif branch.ID != 0 {\n\t\tinsertBranch := `UPDATE branches SET code = $1, name = $2 WHERE id = $3`\n\t\t_, err := db.Exec(insertBranch, branch.Code, branch.Name, branch.ID)\n\n\t\tif err != nil {\n\t\t\treturn 404, err\n\t\t}\n\n\t} else {\n\t\tinsertBranch := `INSERT INTO branches (code, name) VALUES ($1, $2) RETURNING id`\n\t\t_, err := db.Exec(insertBranch, branch.Code, branch.Name)\n\n\t\tif err != nil {\n\t\t\treturn 404, err\n\t\t}\n\t}\n\n\treturn 200, nil\n}", "func Branch(branch string) GitOptions {\n\treturn func(o *options) error {\n\t\to.branch = branch\n\t\treturn nil\n\t}\n}", "func (r *DeviceCompliancePolicyAssignmentRequest) Update(ctx context.Context, reqObj *DeviceCompliancePolicyAssignment) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (mr *MockClientMockRecorder) GetBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBranchProtection\", reflect.TypeOf((*MockClient)(nil).GetBranchProtection), org, repo, branch)\n}", "func (s *RepositoryBranchInput_) SetBranch(v string) *RepositoryBranchInput_ {\n\ts.Branch = &v\n\treturn s\n}", "func (auup *AuthUserUserPermission) Update(ctx context.Context, db DB) error {\n\tswitch {\n\tcase !auup._exists: // doesn't exist\n\t\treturn logerror(&ErrUpdateFailed{ErrDoesNotExist})\n\tcase auup._deleted: // deleted\n\t\treturn logerror(&ErrUpdateFailed{ErrMarkedForDeletion})\n\t}\n\t// update with primary key\n\tconst sqlstr = `UPDATE django.auth_user_user_permissions SET ` +\n\t\t`user_id = :1, permission_id = :2 ` +\n\t\t`WHERE id = :3`\n\t// run\n\tlogf(sqlstr, auup.UserID, auup.PermissionID, auup.ID)\n\tif _, err := db.ExecContext(ctx, sqlstr, auup.UserID, auup.PermissionID, auup.ID); err != nil {\n\t\treturn logerror(err)\n\t}\n\treturn nil\n}", "func d4addBranch(branch *d4branchT, node *d4nodeT, newNode **d4nodeT) bool {\n\tif node.count < d4maxNodes { // Split won't be necessary\n\t\tnode.branch[node.count] = *branch\n\t\tnode.count++\n\t\treturn false\n\t} else {\n\t\td4splitNode(node, branch, newNode)\n\t\treturn true\n\t}\n}", "func (m *MockClient) RemoveBranchProtection(org, repo, branch string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RemoveBranchProtection\", org, repo, branch)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepositoryClient) RemoveBranchProtection(org, repo, branch string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RemoveBranchProtection\", org, repo, branch)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (r *DeviceCompliancePolicyGroupAssignmentRequest) Update(ctx context.Context, reqObj *DeviceCompliancePolicyGroupAssignment) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (r *SettingRepository) DeleteBranchById(id string) error {\n\terr := r.C.Remove(bson.M{\"_id\": bson.ObjectIdHex(id)})\n\treturn err\n}", "func d16addBranch(branch *d16branchT, node *d16nodeT, newNode **d16nodeT) bool {\n\tif node.count < d16maxNodes { // Split won't be necessary\n\t\tnode.branch[node.count] = *branch\n\t\tnode.count++\n\t\treturn false\n\t} else {\n\t\td16splitNode(node, branch, newNode)\n\t\treturn true\n\t}\n}", "func (db *MySQLDB) UpdateTenant(ctx context.Context, tenant *Tenant) error {\n\tfLog := mysqlLog.WithField(\"func\", \"UpdateTenant\").WithField(\"RequestID\", ctx.Value(constants.RequestID))\n\n\texist, err := db.IsTenantRecIDExist(ctx, tenant.RecID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exist {\n\t\treturn ErrNotFound\n\t}\n\n\torigin, err := db.GetTenantByRecID(ctx, tenant.RecID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdomainChanged := origin.Domain != tenant.Domain\n\n\tq := \"UPDATE HANSIP_TENANT SET TENANT_NAME=?, TENANT_DOMAIN=?, DESCRIPTION=? WHERE REC_ID=?\"\n\t_, err = db.instance.ExecContext(ctx, q,\n\t\ttenant.Name, tenant.Domain, tenant.Description, tenant.RecID)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\treturn &ErrDBExecuteError{\n\t\t\tWrapped: err,\n\t\t\tMessage: \"Error UpdateTenant\",\n\t\t\tSQL: q,\n\t\t}\n\t}\n\n\tif domainChanged {\n\t\tq = \"UPDATE HANSIP_ROLE SET ROLE_DOMAIN=? WHERE ROLE_DOMAIN=?\"\n\t\t_, err = db.instance.ExecContext(ctx, q,\n\t\t\ttenant.Domain, origin.Domain)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\t\treturn &ErrDBExecuteError{\n\t\t\t\tWrapped: err,\n\t\t\t\tMessage: \"Error UpdateTenant\",\n\t\t\t\tSQL: q,\n\t\t\t}\n\t\t}\n\n\t\tq = \"UPDATE HANSIP_GROUP SET GROUP_DOMAIN=? WHERE GROUP_DOMAIN=?\"\n\t\t_, err = db.instance.ExecContext(ctx, q,\n\t\t\ttenant.Domain, origin.Domain)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\t\treturn &ErrDBExecuteError{\n\t\t\t\tWrapped: err,\n\t\t\t\tMessage: \"Error UpdateTenant\",\n\t\t\t\tSQL: q,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (bu *BankUpdate) AddBranchIDs(ids ...int) *BankUpdate {\n\tbu.mutation.AddBranchIDs(ids...)\n\treturn bu\n}", "func (accountStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {\n}", "func UpdateCompanyBranchHyCompanybranchOKIdname(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.CompanyIdname) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.CompanyIdname\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.CompanyIdname)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.CompanyIdname\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func addBranchRestrictions(ft *factsTable, b *Block, br branch) {\n\tc := b.Controls[0]\n\tswitch br {\n\tcase negative:\n\t\taddRestrictions(b, ft, boolean, nil, c, eq)\n\tcase positive:\n\t\taddRestrictions(b, ft, boolean, nil, c, lt|gt)\n\tdefault:\n\t\tpanic(\"unknown branch\")\n\t}\n\tif tr, has := domainRelationTable[c.Op]; has {\n\t\t// When we branched from parent we learned a new set of\n\t\t// restrictions. Update the factsTable accordingly.\n\t\td := tr.d\n\t\tif d == signed && ft.isNonNegative(c.Args[0]) && ft.isNonNegative(c.Args[1]) {\n\t\t\td |= unsigned\n\t\t}\n\t\tswitch c.Op {\n\t\tcase OpIsInBounds, OpIsSliceInBounds:\n\t\t\t// 0 <= a0 < a1 (or 0 <= a0 <= a1)\n\t\t\t//\n\t\t\t// On the positive branch, we learn:\n\t\t\t// signed: 0 <= a0 < a1 (or 0 <= a0 <= a1)\n\t\t\t// unsigned: a0 < a1 (or a0 <= a1)\n\t\t\t//\n\t\t\t// On the negative branch, we learn (0 > a0 ||\n\t\t\t// a0 >= a1). In the unsigned domain, this is\n\t\t\t// simply a0 >= a1 (which is the reverse of the\n\t\t\t// positive branch, so nothing surprising).\n\t\t\t// But in the signed domain, we can't express the ||\n\t\t\t// condition, so check if a0 is non-negative instead,\n\t\t\t// to be able to learn something.\n\t\t\tswitch br {\n\t\t\tcase negative:\n\t\t\t\td = unsigned\n\t\t\t\tif ft.isNonNegative(c.Args[0]) {\n\t\t\t\t\td |= signed\n\t\t\t\t}\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r^(lt|gt|eq))\n\t\t\tcase positive:\n\t\t\t\taddRestrictions(b, ft, signed, ft.zero, c.Args[0], lt|eq)\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r)\n\t\t\t}\n\t\tdefault:\n\t\t\tswitch br {\n\t\t\tcase negative:\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r^(lt|gt|eq))\n\t\t\tcase positive:\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r)\n\t\t\t}\n\t\t}\n\n\t}\n}", "func (u *Updater) tryUpdate(ctx context.Context, repositoryID, dirtyToken int) (err error) {\n\tok, unlock, err := u.locker.Lock(ctx, repositoryID, false)\n\tif err != nil || !ok {\n\t\treturn errors.Wrap(err, \"locker.Lock\")\n\t}\n\tdefer func() {\n\t\terr = unlock(err)\n\t}()\n\n\treturn u.update(ctx, repositoryID, dirtyToken)\n}", "func (b *BranchDAG) setBranchLiked(cachedBranch *CachedBranch, liked bool) (modified bool, err error) {\n\t// release the CachedBranch when we are done\n\tdefer cachedBranch.Release()\n\n\t// unwrap ConflictBranch\n\tconflictBranch, err := cachedBranch.UnwrapConflictBranch()\n\tif err != nil {\n\t\terr = errors.Errorf(\"failed to load ConflictBranch with %s: %w\", cachedBranch.ID(), cerrors.ErrFatal)\n\t\treturn\n\t}\n\n\t// execute case dependent logic\n\tswitch liked {\n\tcase true:\n\t\t// iterate through all Conflicts of the current Branch and set their ConflictMembers to be not liked\n\t\tfor conflictID := range conflictBranch.Conflicts() {\n\t\t\t// iterate through all ConflictMembers and set them to not liked\n\t\t\tcachedConflictMembers := b.ConflictMembers(conflictID)\n\t\t\tfor _, cachedConflictMember := range cachedConflictMembers {\n\t\t\t\t// unwrap the ConflictMember\n\t\t\t\tconflictMember := cachedConflictMember.Unwrap()\n\t\t\t\tif conflictMember == nil {\n\t\t\t\t\tcachedConflictMembers.Release()\n\t\t\t\t\terr = errors.Errorf(\"failed to load ConflictMember of %s: %w\", conflictID, cerrors.ErrFatal)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// skip the current Branch\n\t\t\t\tif conflictMember.BranchID() == conflictBranch.ID() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// update the other ConflictMembers to be not liked\n\t\t\t\tif _, err = b.setBranchLiked(b.Branch(conflictMember.BranchID()), false); err != nil {\n\t\t\t\t\tcachedConflictMembers.Release()\n\t\t\t\t\terr = errors.Errorf(\"failed to propagate liked changes to other ConflictMembers: %w\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tcachedConflictMembers.Release()\n\t\t}\n\n\t\t// abort if the branch was liked already\n\t\tif modified = conflictBranch.SetLiked(true); !modified {\n\t\t\treturn\n\t\t}\n\n\t\t// trigger event\n\t\tb.Events.BranchLiked.Trigger(NewBranchDAGEvent(cachedBranch))\n\n\t\t// update the liked status of the future cone (it only effects the AggregatedBranches)\n\t\tif err = b.updateLikedOfAggregatedChildBranches(conflictBranch.ID(), true); err != nil {\n\t\t\terr = errors.Errorf(\"failed to update liked status of future cone of Branch with %s: %w\", conflictBranch.ID(), err)\n\t\t\treturn\n\t\t}\n\n\t\t// update the liked status of the future cone (if necessary)\n\t\tif _, err = b.updateMonotonicallyLikedStatus(conflictBranch.ID(), true); err != nil {\n\t\t\terr = errors.Errorf(\"failed to update liked status of future cone of Branch with %s: %w\", conflictBranch.ID(), err)\n\t\t\treturn\n\t\t}\n\tcase false:\n\t\t// set the branch to be not liked\n\t\tif modified = conflictBranch.SetLiked(false); modified {\n\t\t\t// trigger event\n\t\t\tb.Events.BranchDisliked.Trigger(NewBranchDAGEvent(cachedBranch))\n\n\t\t\t// update the liked status of the future cone (it only affect the AggregatedBranches)\n\t\t\tif propagationErr := b.updateLikedOfAggregatedChildBranches(conflictBranch.ID(), false); propagationErr != nil {\n\t\t\t\terr = errors.Errorf(\"failed to propagate liked changes to AggregatedBranches: %w\", propagationErr)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// update the liked status of the future cone (if necessary)\n\t\t\tif _, propagationErr := b.updateMonotonicallyLikedStatus(conflictBranch.ID(), false); propagationErr != nil {\n\t\t\t\terr = errors.Errorf(\"failed to update liked status of future cone of Branch with %s: %w\", conflictBranch.ID(), propagationErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func updateLoan(l *models.Loan, db *gorm.DB) error {\n\tomitList := []string{\"id\", \"initial_value\", \"interest\", \"quota\", \"cod_client\", \"cod_collection\", \"cod_user\", \"deleted_at\"}\n\terr := db.Model(l).Omit(omitList...).Save(l).Error\n\treturn err\n}", "func (r *DeviceCompliancePolicyRequest) Update(ctx context.Context, reqObj *DeviceCompliancePolicy) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (p *Patch) SetFinalized(ctx context.Context, versionId string) error {\n\tif _, err := evergreen.GetEnvironment().DB().Collection(Collection).UpdateOne(ctx,\n\t\tbson.M{IdKey: p.Id},\n\t\tbson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\tActivatedKey: true,\n\t\t\t\tVersionKey: versionId,\n\t\t\t},\n\t\t\t\"$unset\": bson.M{\n\t\t\t\tProjectStorageMethodKey: 1,\n\t\t\t\tPatchedParserProjectKey: 1,\n\t\t\t\tPatchedProjectConfigKey: 1,\n\t\t\t},\n\t\t},\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tp.Version = versionId\n\tp.Activated = true\n\tp.ProjectStorageMethod = \"\"\n\tp.PatchedParserProject = \"\"\n\tp.PatchedProjectConfig = \"\"\n\n\treturn nil\n}", "func (handler *InitHandler) handleBranches(c Community, r Repository) error {\n\t// if the branches are defined in the repositories, it means that\n\t// all the branches defined in the community will not inherited by repositories\n\tmapBranches := make(map[string]string)\n\n\tif len(r.ProtectedBranches) > 0 {\n\t\t// using repository branches\n\t\tglog.Infof(\"using repository branches: %s\", *r.Name)\n\t\tfor _, b := range r.ProtectedBranches {\n\t\t\tmapBranches[b] = b\n\t\t}\n\t} else {\n\t\t// using community branches\n\t\tglog.Infof(\"using community branches: %s\", *r.Name)\n\t\tfor _, b := range c.ProtectedBranches {\n\t\t\tmapBranches[b] = b\n\t\t}\n\t}\n\n\t// get branches from DB\n\tvar bs []database.Branches\n\terr := database.DBConnection.Model(&database.Branches{}).\n\t\tWhere(\"owner = ? and repo = ?\", c.Name, r.Name).Find(&bs).Error\n\tif err != nil {\n\t\tglog.Errorf(\"unable to get branches: %v\", err)\n\t\treturn err\n\t}\n\tmapBranchesInDB := make(map[string]string)\n\tfor _, b := range bs {\n\t\tmapBranchesInDB[b.Name] = strconv.Itoa(int(b.ID))\n\t}\n\n\t// un-protected branches\n\terr = handler.removeBranchProtections(c, r, mapBranches, mapBranchesInDB)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to un-protected branches: %v\", err)\n\t}\n\n\t// protected branches\n\terr = handler.addBranchProtections(c, r, mapBranches, mapBranchesInDB)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to protected branches: %v\", err)\n\t}\n\n\treturn nil\n}", "func (s *RepositoryBranch) SetBranch(v string) *RepositoryBranch {\n\ts.Branch = &v\n\treturn s\n}", "func (c *AccountController) Update(ctx echo.Context) error {\n\tmodel := account.Account{}\n\terr := ctx.Bind(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusUnprocessableEntity, err.Error())\n\t}\n\n\terr = c.AccountUsecase.Update(&model)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn ctx.NoContent(http.StatusNoContent)\n}", "func (s *BucketService) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) {\n\tb, err := s.s.FindBucketByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := authorizeWriteBucket(ctx, b.OrgID, id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.s.UpdateBucket(ctx, id, upd)\n}", "func StoreBranches(dbOwner, dbFolder, dbName string, branches map[string]BranchEntry) error {\n\tdbQuery := `\n\t\tUPDATE sqlite_databases\n\t\tSET branch_heads = $4, branches = $5\n\t\tWHERE user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t\t)\n\t\t\tAND folder = $2\n\t\t\tAND db_name = $3`\n\tcommandTag, err := pdb.Exec(dbQuery, dbOwner, dbFolder, dbName, branches, len(branches))\n\tif err != nil {\n\t\tlog.Printf(\"Updating branch heads for database '%s%s%s' to '%v' failed: %v\\n\", dbOwner, dbFolder,\n\t\t\tdbName, branches, err)\n\t\treturn err\n\t}\n\tif numRows := commandTag.RowsAffected(); numRows != 1 {\n\t\tlog.Printf(\n\t\t\t\"Wrong number of rows (%v) affected when updating branch heads for database '%s%s%s' to '%v'\\n\",\n\t\t\tnumRows, dbOwner, dbFolder, dbName, branches)\n\t}\n\treturn nil\n}", "func (op *PermissionProfilesUpdateOp) Do(ctx context.Context) (*model.PermissionProfile, error) {\n\tvar res *model.PermissionProfile\n\treturn res, ((*esign.Op)(op)).Do(ctx, &res)\n}", "func (p *perm) CommitChange() {\n\tp.enforcer.SavePolicy()\n}", "func (s *Repository) Save(ctx context.Context, account Account) error {\n\tcmd, err := s.pool.Exec(\n\t\tctx,\n\t\t`insert into \"account\"\n\t\t\t (\"ID\", \"createdAt\", \"description\", \"balance\", \"currency\", \"lastUpdatedAt\")\n\t\t\t values ($1, current_timestamp(0), $1, $2, $3, current_timestamp(0))\n\t\t\t on conflict (\"ID\") do update\n\t\t\t set \"balance\" = \"excluded\".\"balance\", \"lastUpdatedAt\" = current_timestamp(0)`,\n\t\taccount.ID, account.Balance, account.Currency)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cmd.RowsAffected() == 0 {\n\t\treturn fmt.Errorf(\"failed to upsert account: %v\", account.ID)\n\t}\n\n\treturn nil\n}", "func (m *AospDeviceOwnerDeviceConfiguration) SetBluetoothBlocked(value *bool)() {\n err := m.GetBackingStore().Set(\"bluetoothBlocked\", value)\n if err != nil {\n panic(err)\n }\n}", "func (b *BranchDAG) SetBranchFinalized(branchID BranchID, finalized bool) (modified bool, err error) {\n\treturn b.setBranchFinalized(b.Branch(branchID), finalized)\n}", "func (c *client) UpdatePullRequestBranch(org, repo string, number int, expectedHeadSha *string) error {\n\tdurationLogger := c.log(\"UpdatePullRequestBranch\", org, repo)\n\tdefer durationLogger()\n\n\tdata := struct {\n\t\t// The expected SHA of the pull request's HEAD ref. This is the most recent commit on the pull request's branch.\n\t\t// If the expected SHA does not match the pull request's HEAD, you will receive a 422 Unprocessable Entity status.\n\t\t// You can use the \"List commits\" endpoint to find the most recent commit SHA. Default: SHA of the pull request's current HEAD ref.\n\t\tExpectedHeadSha *string `json:\"expected_head_sha,omitempty\"`\n\t}{\n\t\tExpectedHeadSha: expectedHeadSha,\n\t}\n\n\tcode, err := c.request(&request{\n\t\tmethod: http.MethodPut,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/pulls/%d/update-branch\", org, repo, number),\n\t\taccept: \"application/vnd.github.lydian-preview+json\",\n\t\torg: org,\n\t\trequestBody: &data,\n\t\texitCodes: []int{202, 422},\n\t}, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif code == http.StatusUnprocessableEntity {\n\t\tmsg := \"mismatch expected head sha\"\n\t\tif expectedHeadSha != nil {\n\t\t\tmsg = fmt.Sprintf(\"%s: %s\", msg, *expectedHeadSha)\n\t\t}\n\t\treturn errors.New(msg)\n\t}\n\n\treturn nil\n}" ]
[ "0.6981953", "0.68028724", "0.67981833", "0.6534552", "0.57428634", "0.5720844", "0.56828713", "0.5580903", "0.5515201", "0.5496755", "0.5369292", "0.4983595", "0.49808177", "0.49740207", "0.48678598", "0.48411614", "0.4827034", "0.47039238", "0.46725774", "0.46675575", "0.45363298", "0.452032", "0.4490009", "0.44693503", "0.44619825", "0.444473", "0.4428761", "0.4407938", "0.439502", "0.4361327", "0.4332399", "0.4331433", "0.4327554", "0.431971", "0.43091232", "0.43030196", "0.42953864", "0.42914665", "0.42655522", "0.42574888", "0.42496362", "0.42420632", "0.4235807", "0.42160013", "0.42058375", "0.41991234", "0.41917464", "0.41805708", "0.41705105", "0.41702718", "0.41666535", "0.41490313", "0.4147066", "0.41183293", "0.41154566", "0.41095382", "0.40996015", "0.40972114", "0.4095966", "0.40862817", "0.4082857", "0.40714502", "0.4068068", "0.40668717", "0.40649763", "0.40609756", "0.40513307", "0.4045832", "0.40246597", "0.40198126", "0.40095133", "0.40023246", "0.40001625", "0.3997555", "0.39961457", "0.39936432", "0.39930895", "0.3974371", "0.39688903", "0.39637557", "0.39563718", "0.3925133", "0.39218086", "0.39174074", "0.39167422", "0.39074302", "0.39059624", "0.39001584", "0.38998255", "0.3899464", "0.38686794", "0.3860071", "0.38588694", "0.3855684", "0.38511938", "0.38504738", "0.38504052", "0.38436934", "0.3836403", "0.38331226" ]
0.7305021
0
UpdateOrgProtectBranch saves branch protection options of organizational repository. If ID is 0, it creates a new record. Otherwise, updates existing record. This function also performs check if whitelist user and team's IDs have been changed to avoid unnecessary whitelist delete and regenerate.
UpdateOrgProtectBranch сохраняет параметры защиты ветки организационного репозитория. Если ID равно 0, создаётся новый запись. В противном случае, обновляется существующая запись. Эта функция также проверяет, изменились ли идентификаторы пользователей и команд в белом списке, чтобы избежать ненужного удаления и пересоздания белого списка.
func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whitelistUserIDs, whitelistTeamIDs string) (err error) { if err = repo.GetOwner(); err != nil { return fmt.Errorf("GetOwner: %v", err) } else if !repo.Owner.IsOrganization() { return fmt.Errorf("expect repository owner to be an organization") } hasUsersChanged := false validUserIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistUserIDs, ",")) if protectBranch.WhitelistUserIDs != whitelistUserIDs { hasUsersChanged = true userIDs := tool.StringsToInt64s(strings.Split(whitelistUserIDs, ",")) validUserIDs = make([]int64, 0, len(userIDs)) for _, userID := range userIDs { if !Perms.Authorize(context.TODO(), userID, repo.ID, AccessModeWrite, AccessModeOptions{ OwnerID: repo.OwnerID, Private: repo.IsPrivate, }, ) { continue // Drop invalid user ID } validUserIDs = append(validUserIDs, userID) } protectBranch.WhitelistUserIDs = strings.Join(tool.Int64sToStrings(validUserIDs), ",") } hasTeamsChanged := false validTeamIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistTeamIDs, ",")) if protectBranch.WhitelistTeamIDs != whitelistTeamIDs { hasTeamsChanged = true teamIDs := tool.StringsToInt64s(strings.Split(whitelistTeamIDs, ",")) teams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite) if err != nil { return fmt.Errorf("GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err) } validTeamIDs = make([]int64, 0, len(teams)) for i := range teams { if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(teamIDs, teams[i].ID) { validTeamIDs = append(validTeamIDs, teams[i].ID) } } protectBranch.WhitelistTeamIDs = strings.Join(tool.Int64sToStrings(validTeamIDs), ",") } // Make sure protectBranch.ID is not 0 for whitelists if protectBranch.ID == 0 { if _, err = x.Insert(protectBranch); err != nil { return fmt.Errorf("Insert: %v", err) } } // Merge users and members of teams var whitelists []*ProtectBranchWhitelist if hasUsersChanged || hasTeamsChanged { mergedUserIDs := make(map[int64]bool) for _, userID := range validUserIDs { // Empty whitelist users can cause an ID with 0 if userID != 0 { mergedUserIDs[userID] = true } } for _, teamID := range validTeamIDs { members, err := GetTeamMembers(teamID) if err != nil { return fmt.Errorf("GetTeamMembers [team_id: %d]: %v", teamID, err) } for i := range members { mergedUserIDs[members[i].ID] = true } } whitelists = make([]*ProtectBranchWhitelist, 0, len(mergedUserIDs)) for userID := range mergedUserIDs { whitelists = append(whitelists, &ProtectBranchWhitelist{ ProtectBranchID: protectBranch.ID, RepoID: repo.ID, Name: protectBranch.Name, UserID: userID, }) } } sess := x.NewSession() defer sess.Close() if err = sess.Begin(); err != nil { return err } if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { return fmt.Errorf("Update: %v", err) } // Refresh whitelists if hasUsersChanged || hasTeamsChanged { if _, err = sess.Delete(&ProtectBranchWhitelist{ProtectBranchID: protectBranch.ID}); err != nil { return fmt.Errorf("delete old protect branch whitelists: %v", err) } else if _, err = sess.Insert(whitelists); err != nil { return fmt.Errorf("insert new protect branch whitelists: %v", err) } } return sess.Commit() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func EditBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation PATCH /repos/{owner}/{repo}/branch_protections/{name} repository repoEditBranchProtection\n\t// ---\n\t// summary: Edit a branch protections for a repository. Only fields that are set will be changed\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// - name: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/EditBranchProtectionOption\"\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\t// \"422\":\n\t// \"$ref\": \"#/responses/validationError\"\n\tform := web.GetForm(ctx).(*api.EditBranchProtectionOption)\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tprotectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif protectBranch == nil || protectBranch.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tif form.EnablePush != nil {\n\t\tif !*form.EnablePush {\n\t\t\tprotectBranch.CanPush = false\n\t\t\tprotectBranch.EnableWhitelist = false\n\t\t\tprotectBranch.WhitelistDeployKeys = false\n\t\t} else {\n\t\t\tprotectBranch.CanPush = true\n\t\t\tif form.EnablePushWhitelist != nil {\n\t\t\t\tif !*form.EnablePushWhitelist {\n\t\t\t\t\tprotectBranch.EnableWhitelist = false\n\t\t\t\t\tprotectBranch.WhitelistDeployKeys = false\n\t\t\t\t} else {\n\t\t\t\t\tprotectBranch.EnableWhitelist = true\n\t\t\t\t\tif form.PushWhitelistDeployKeys != nil {\n\t\t\t\t\t\tprotectBranch.WhitelistDeployKeys = *form.PushWhitelistDeployKeys\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif form.EnableMergeWhitelist != nil {\n\t\tprotectBranch.EnableMergeWhitelist = *form.EnableMergeWhitelist\n\t}\n\n\tif form.EnableStatusCheck != nil {\n\t\tprotectBranch.EnableStatusCheck = *form.EnableStatusCheck\n\t}\n\n\tif form.StatusCheckContexts != nil {\n\t\tprotectBranch.StatusCheckContexts = form.StatusCheckContexts\n\t}\n\n\tif form.RequiredApprovals != nil && *form.RequiredApprovals >= 0 {\n\t\tprotectBranch.RequiredApprovals = *form.RequiredApprovals\n\t}\n\n\tif form.EnableApprovalsWhitelist != nil {\n\t\tprotectBranch.EnableApprovalsWhitelist = *form.EnableApprovalsWhitelist\n\t}\n\n\tif form.BlockOnRejectedReviews != nil {\n\t\tprotectBranch.BlockOnRejectedReviews = *form.BlockOnRejectedReviews\n\t}\n\n\tif form.BlockOnOfficialReviewRequests != nil {\n\t\tprotectBranch.BlockOnOfficialReviewRequests = *form.BlockOnOfficialReviewRequests\n\t}\n\n\tif form.DismissStaleApprovals != nil {\n\t\tprotectBranch.DismissStaleApprovals = *form.DismissStaleApprovals\n\t}\n\n\tif form.RequireSignedCommits != nil {\n\t\tprotectBranch.RequireSignedCommits = *form.RequireSignedCommits\n\t}\n\n\tif form.ProtectedFilePatterns != nil {\n\t\tprotectBranch.ProtectedFilePatterns = *form.ProtectedFilePatterns\n\t}\n\n\tif form.UnprotectedFilePatterns != nil {\n\t\tprotectBranch.UnprotectedFilePatterns = *form.UnprotectedFilePatterns\n\t}\n\n\tif form.BlockOnOutdatedBranch != nil {\n\t\tprotectBranch.BlockOnOutdatedBranch = *form.BlockOnOutdatedBranch\n\t}\n\n\tvar whitelistUsers []int64\n\tif form.PushWhitelistUsernames != nil {\n\t\twhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\twhitelistUsers = protectBranch.WhitelistUserIDs\n\t}\n\tvar mergeWhitelistUsers []int64\n\tif form.MergeWhitelistUsernames != nil {\n\t\tmergeWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tmergeWhitelistUsers = protectBranch.MergeWhitelistUserIDs\n\t}\n\tvar approvalsWhitelistUsers []int64\n\tif form.ApprovalsWhitelistUsernames != nil {\n\t\tapprovalsWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tapprovalsWhitelistUsers = protectBranch.ApprovalsWhitelistUserIDs\n\t}\n\n\tvar whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64\n\tif repo.Owner.IsOrganization() {\n\t\tif form.PushWhitelistTeams != nil {\n\t\t\twhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\twhitelistTeams = protectBranch.WhitelistTeamIDs\n\t\t}\n\t\tif form.MergeWhitelistTeams != nil {\n\t\t\tmergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tmergeWhitelistTeams = protectBranch.MergeWhitelistTeamIDs\n\t\t}\n\t\tif form.ApprovalsWhitelistTeams != nil {\n\t\t\tapprovalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tapprovalsWhitelistTeams = protectBranch.ApprovalsWhitelistTeamIDs\n\t\t}\n\t}\n\n\terr = git_model.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, git_model.WhitelistOptions{\n\t\tUserIDs: whitelistUsers,\n\t\tTeamIDs: whitelistTeams,\n\t\tMergeUserIDs: mergeWhitelistUsers,\n\t\tMergeTeamIDs: mergeWhitelistTeams,\n\t\tApprovalsUserIDs: approvalsWhitelistUsers,\n\t\tApprovalsTeamIDs: approvalsWhitelistTeams,\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"UpdateProtectBranch\", err)\n\t\treturn\n\t}\n\n\tisPlainRule := !git_model.IsRuleNameSpecial(bpName)\n\tvar isBranchExist bool\n\tif isPlainRule {\n\t\tisBranchExist = git.IsBranchExist(ctx.Req.Context(), ctx.Repo.Repository.RepoPath(), bpName)\n\t}\n\n\tif isBranchExist {\n\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, bpName); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPrsForBaseBranch\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !isPlainRule {\n\t\t\tif ctx.Repo.GitRepo == nil {\n\t\t\t\tctx.Repo.GitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.RepoPath())\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"OpenRepository\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer func() {\n\t\t\t\t\tctx.Repo.GitRepo.Close()\n\t\t\t\t\tctx.Repo.GitRepo = nil\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\t// FIXME: since we only need to recheck files protected rules, we could improve this\n\t\t\tmatchedBranches, err := git_model.FindAllMatchedBranches(ctx, ctx.Repo.Repository.ID, protectBranch.RuleName)\n\t\t\tif err != nil {\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"FindAllMatchedBranches\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, branchName := range matchedBranches {\n\t\t\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, branchName); err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPrsForBaseBranch\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reload from db to ensure get all whitelists\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchBy\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != ctx.Repo.Repository.ID {\n\t\tctx.Error(http.StatusInternalServerError, \"New branch protection not found\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, convert.ToBranchProtection(bp))\n}", "func UpdateProtectBranch(protectBranch *ProtectBranch) (err error) {\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\tif err = sess.Begin(); err != nil {\n\t\treturn err\n\t}\n\n\tif protectBranch.ID == 0 {\n\t\tif _, err = sess.Insert(protectBranch); err != nil {\n\t\t\treturn fmt.Errorf(\"Insert: %v\", err)\n\t\t}\n\t}\n\n\tif _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {\n\t\treturn fmt.Errorf(\"Update: %v\", err)\n\t}\n\n\treturn sess.Commit()\n}", "func (c *client) UpdateBranchProtection(org, repo, branch string, config BranchProtectionRequest) error {\n\tdurationLogger := c.log(\"UpdateBranchProtection\", org, repo, branch, config)\n\tdefer durationLogger()\n\n\t_, err := c.request(&request{\n\t\taccept: \"application/vnd.github.luke-cage-preview+json\", // for required_approving_review_count\n\t\tmethod: http.MethodPut,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/branches/%s/protection\", org, repo, branch),\n\t\torg: org,\n\t\trequestBody: config,\n\t\texitCodes: []int{200},\n\t}, nil)\n\treturn err\n}", "func (p GithubRepoHost) UpdateBranchProtection(repoID string, rule BranchProtectionRule) error {\n\tif isDebug() {\n\t\tfmt.Printf(\"Updating branch protection on %s\\n\", repoID)\n\t}\n\n\trules := fetchBranchProtectionRules()\n\tinput := githubv4.UpdateBranchProtectionRuleInput{\n\t\tBranchProtectionRuleID: rule.ID,\n\t\tPattern: githubv4.NewString(githubv4.String(rules.Pattern)),\n\t\tDismissesStaleReviews: githubv4.NewBoolean(githubv4.Boolean(rules.DismissesStaleReviews)),\n\t\tIsAdminEnforced: githubv4.NewBoolean(githubv4.Boolean(rules.IsAdminEnforced)),\n\t\tRequiresApprovingReviews: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresApprovingReviews)),\n\t\tRequiredApprovingReviewCount: githubv4.NewInt(githubv4.Int(rules.RequiredApprovingReviewCount)),\n\t\tRequiresStatusChecks: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresStatusChecks)),\n\t\tRequiredStatusCheckContexts: &[]githubv4.String{\n\t\t\t*githubv4.NewString(\"build\"),\n\t\t},\n\t}\n\n\tvar m UpdateBranchProtectionRuleMutation\n\tclient := buildClient()\n\terr := client.Mutate(context.Background(), &m, input, nil)\n\treturn err\n}", "func UpdateBranchProtection() error {\n\tvar wg sync.WaitGroup\n\trequests, err := getBranchProtectionRequests()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twg.Add(len(requests))\n\towner, repo := getOwnerRepo()\n\n\tfor _, bp := range requests {\n\t\tgo func(bp BranchProtection) {\n\t\t\tdefer wg.Done()\n\t\t\t_, _, err := cli.Repositories.UpdateBranchProtection(ctx, owner, repo, bp.Branch, bp.Protection)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\t_, err = fmt.Fprintln(writer, fmt.Sprintf(\"branch %v has been protected\", bp.Branch))\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}(bp)\n\t}\n\n\twg.Wait()\n\n\treturn nil\n}", "func (mr *MockRepositoryClientMockRecorder) UpdateBranchProtection(org, repo, branch, config interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateBranchProtection\", reflect.TypeOf((*MockRepositoryClient)(nil).UpdateBranchProtection), org, repo, branch, config)\n}", "func (mr *MockClientMockRecorder) UpdateBranchProtection(org, repo, branch, config interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateBranchProtection\", reflect.TypeOf((*MockClient)(nil).UpdateBranchProtection), org, repo, branch, config)\n}", "func (m *MockClient) UpdateBranchProtection(org, repo, branch string, config github.BranchProtectionRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateBranchProtection\", org, repo, branch, config)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepositoryClient) UpdateBranchProtection(org, repo, branch string, config github.BranchProtectionRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateBranchProtection\", org, repo, branch, config)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (p GithubRepoHost) AddBranchProtection(repoID string) (BranchProtectionRule, error) {\n\tif isDebug() {\n\t\tfmt.Printf(\"Adding branch protection on %s\\n\", repoID)\n\t}\n\n\trules := fetchBranchProtectionRules()\n\tinput := githubv4.CreateBranchProtectionRuleInput{\n\t\tRepositoryID: repoID,\n\t\tPattern: *githubv4.NewString(githubv4.String(rules.Pattern)),\n\t\tDismissesStaleReviews: githubv4.NewBoolean(githubv4.Boolean(rules.DismissesStaleReviews)),\n\t\tIsAdminEnforced: githubv4.NewBoolean(githubv4.Boolean(rules.IsAdminEnforced)),\n\t\tRequiresApprovingReviews: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresApprovingReviews)),\n\t\tRequiredApprovingReviewCount: githubv4.NewInt(githubv4.Int(rules.RequiredApprovingReviewCount)),\n\t\tRequiresStatusChecks: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresStatusChecks)),\n\t}\n\n\tchecks := make([]githubv4.String, len(rules.RequiredStatusCheckContexts))\n\tfor i, name := range rules.RequiredStatusCheckContexts {\n\t\tchecks[i] = *githubv4.NewString(githubv4.String(name))\n\t}\n\tinput.RequiredStatusCheckContexts = &checks\n\n\tvar m CreateRuleMutation\n\tclient := buildClient()\n\terr := client.Mutate(context.Background(), &m, input, nil)\n\treturn m.CreateBranchProtectionRule.BranchProtectionRule, err\n}", "func CreateBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation POST /repos/{owner}/{repo}/branch_protections repository repoCreateBranchProtection\n\t// ---\n\t// summary: Create a branch protections for a repository\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: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/CreateBranchProtectionOption\"\n\t// responses:\n\t// \"201\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"403\":\n\t// \"$ref\": \"#/responses/forbidden\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\t// \"422\":\n\t// \"$ref\": \"#/responses/validationError\"\n\n\tform := web.GetForm(ctx).(*api.CreateBranchProtectionOption)\n\trepo := ctx.Repo.Repository\n\n\truleName := form.RuleName\n\tif ruleName == \"\" {\n\t\truleName = form.BranchName //nolint\n\t}\n\tif len(ruleName) == 0 {\n\t\tctx.Error(http.StatusBadRequest, \"both rule_name and branch_name are empty\", \"both rule_name and branch_name are empty\")\n\t\treturn\n\t}\n\n\tisPlainRule := !git_model.IsRuleNameSpecial(ruleName)\n\tvar isBranchExist bool\n\tif isPlainRule {\n\t\tisBranchExist = git.IsBranchExist(ctx.Req.Context(), ctx.Repo.Repository.RepoPath(), ruleName)\n\t}\n\n\tprotectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, ruleName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectBranchOfRepoByName\", err)\n\t\treturn\n\t} else if protectBranch != nil {\n\t\tctx.Error(http.StatusForbidden, \"Create branch protection\", \"Branch protection already exist\")\n\t\treturn\n\t}\n\n\tvar requiredApprovals int64\n\tif form.RequiredApprovals > 0 {\n\t\trequiredApprovals = form.RequiredApprovals\n\t}\n\n\twhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tmergeWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tapprovalsWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tvar whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64\n\tif repo.Owner.IsOrganization() {\n\t\twhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t\tmergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t\tapprovalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tprotectBranch = &git_model.ProtectedBranch{\n\t\tRepoID: ctx.Repo.Repository.ID,\n\t\tRuleName: ruleName,\n\t\tCanPush: form.EnablePush,\n\t\tEnableWhitelist: form.EnablePush && form.EnablePushWhitelist,\n\t\tEnableMergeWhitelist: form.EnableMergeWhitelist,\n\t\tWhitelistDeployKeys: form.EnablePush && form.EnablePushWhitelist && form.PushWhitelistDeployKeys,\n\t\tEnableStatusCheck: form.EnableStatusCheck,\n\t\tStatusCheckContexts: form.StatusCheckContexts,\n\t\tEnableApprovalsWhitelist: form.EnableApprovalsWhitelist,\n\t\tRequiredApprovals: requiredApprovals,\n\t\tBlockOnRejectedReviews: form.BlockOnRejectedReviews,\n\t\tBlockOnOfficialReviewRequests: form.BlockOnOfficialReviewRequests,\n\t\tDismissStaleApprovals: form.DismissStaleApprovals,\n\t\tRequireSignedCommits: form.RequireSignedCommits,\n\t\tProtectedFilePatterns: form.ProtectedFilePatterns,\n\t\tUnprotectedFilePatterns: form.UnprotectedFilePatterns,\n\t\tBlockOnOutdatedBranch: form.BlockOnOutdatedBranch,\n\t}\n\n\terr = git_model.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, git_model.WhitelistOptions{\n\t\tUserIDs: whitelistUsers,\n\t\tTeamIDs: whitelistTeams,\n\t\tMergeUserIDs: mergeWhitelistUsers,\n\t\tMergeTeamIDs: mergeWhitelistTeams,\n\t\tApprovalsUserIDs: approvalsWhitelistUsers,\n\t\tApprovalsTeamIDs: approvalsWhitelistTeams,\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"UpdateProtectBranch\", err)\n\t\treturn\n\t}\n\n\tif isBranchExist {\n\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, ruleName); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPRsForBaseBranch\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !isPlainRule {\n\t\t\tif ctx.Repo.GitRepo == nil {\n\t\t\t\tctx.Repo.GitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.RepoPath())\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"OpenRepository\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer func() {\n\t\t\t\t\tctx.Repo.GitRepo.Close()\n\t\t\t\t\tctx.Repo.GitRepo = nil\n\t\t\t\t}()\n\t\t\t}\n\t\t\t// FIXME: since we only need to recheck files protected rules, we could improve this\n\t\t\tmatchedBranches, err := git_model.FindAllMatchedBranches(ctx, ctx.Repo.Repository.ID, ruleName)\n\t\t\tif err != nil {\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"FindAllMatchedBranches\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, branchName := range matchedBranches {\n\t\t\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, branchName); err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPRsForBaseBranch\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reload from db to get all whitelists\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, ctx.Repo.Repository.ID, ruleName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != ctx.Repo.Repository.ID {\n\t\tctx.Error(http.StatusInternalServerError, \"New branch protection not found\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusCreated, convert.ToBranchProtection(bp))\n}", "func (c *client) RemoveBranchProtection(org, repo, branch string) error {\n\tdurationLogger := c.log(\"RemoveBranchProtection\", org, repo, branch)\n\tdefer durationLogger()\n\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodDelete,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/branches/%s/protection\", org, repo, branch),\n\t\torg: org,\n\t\texitCodes: []int{204},\n\t}, nil)\n\treturn err\n}", "func (r *SettingRepository) AddBranchByOrgID(orgID string) (branch models.Branch, err error) {\n\tobjID := bson.NewObjectId()\n\tbranch.ID = objID\n\tbranch.OrgID = bson.ObjectIdHex(orgID)\n\tbranch.Status = \"Active\"\n\tbranch.CreatedAt = time.Now()\n\tbranch.UpdatedAt = time.Now()\n\n\terr = r.C.Insert(&branch)\n\treturn\n}", "func (mr *MockRepositoryClientMockRecorder) RemoveBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RemoveBranchProtection\", reflect.TypeOf((*MockRepositoryClient)(nil).RemoveBranchProtection), org, repo, branch)\n}", "func (mr *MockClientMockRecorder) RemoveBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RemoveBranchProtection\", reflect.TypeOf((*MockClient)(nil).RemoveBranchProtection), org, repo, branch)\n}", "func UpdateCompanyBranchHyCompanybranchBadRequest(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, error) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\treturn nil, e\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\treturn nil, _e\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 400 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 400\", rw.Code)\n\t}\n\tvar mt error\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(error)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of error\", resp, resp)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func handleRepo(ctx context.Context, client *github.Client, repo *github.Repository) error {\n\topt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tbranches, resp, err := client.Repositories.ListBranches(ctx, *repo.Owner.Login, *repo.Name, opt)\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, branch := range branches {\n\t\tif branch.GetName() == \"master\" && in(orgs, *repo.Owner.Login) {\n\t\t\t// we must get the individual branch for the branch protection to work\n\t\t\tb, _, err := client.Repositories.GetBranch(ctx, *repo.Owner.Login, *repo.Name, branch.GetName())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// return early if it is already protected\n\t\t\tif b.GetProtected() {\n\t\t\t\tfmt.Printf(\"[OK] %s:%s is already protected\\n\", *repo.FullName, b.GetName())\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfmt.Printf(\"[UPDATE] %s:%s will be changed to protected\\n\", *repo.FullName, b.GetName())\n\t\t\tif dryrun {\n\t\t\t\t// return early\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// set the branch to be protected\n\t\t\tif _, _, err := client.Repositories.UpdateBranchProtection(ctx, *repo.Owner.Login, *repo.Name, b.GetName(), &github.ProtectionRequest{\n\t\t\t\tRequiredStatusChecks: &github.RequiredStatusChecks{\n\t\t\t\t\tStrict: false,\n\t\t\t\t\tContexts: []string{},\n\t\t\t\t},\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func UpdateCompanyBranchHyCompanybranchNotFound(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) {}\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 404 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 404\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func DeleteBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation DELETE /repos/{owner}/{repo}/branch_protections/{name} repository repoDeleteBranchProtection\n\t// ---\n\t// summary: Delete a specific branch protection for the repository\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// responses:\n\t// \"204\":\n\t// \"$ref\": \"#/responses/empty\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tif err := git_model.DeleteProtectedBranch(ctx, ctx.Repo.Repository.ID, bp.ID); err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"DeleteProtectedBranch\", err)\n\t\treturn\n\t}\n\n\tctx.Status(http.StatusNoContent)\n}", "func (a *Client) UpdateBranch(params *UpdateBranchParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateBranchOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewUpdateBranchParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"updateBranch\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/vcs/branch/{branchID}\",\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: &UpdateBranchReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*UpdateBranchOK)\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 updateBranch: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func UpdateCompanyBranchHyCompanybranchOKID(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.CompanyID) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.CompanyID\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.CompanyID)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.CompanyID\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func UpdateCompanyBranchHyCompanybranchOK(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.Company) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.Company\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.Company)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.Company\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func GetProtectBranchesByRepoID(repoID int64) ([]*ProtectBranch, error) {\n\tprotectBranches := make([]*ProtectBranch, 0, 2)\n\treturn protectBranches, x.Where(\"repo_id = ? and protected = ?\", repoID, true).Asc(\"name\").Find(&protectBranches)\n}", "func (s *SmartContract) UpdateOrgLogin(ctx contractapi.TransactionContextInterface, userName string, password string) error {\n\tuserLogin := UserLogin{\n\t\tPassword: password,\n\t}\n\n\tinfoAsBytes, _ := json.Marshal(userLogin)\n\n\treturn ctx.GetStub().PutState(\"login-org-\" + userName, infoAsBytes)\n}", "func (mr *MockSendUpdateQueryMockRecorder) UpdateBranch(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateBranch\", reflect.TypeOf((*MockSendUpdateQuery)(nil).UpdateBranch), arg0, arg1, arg2)\n}", "func (service *Service) UpdateProtectionMode(d9SecurityGroupID, protectionMode string) (*CloudSecurityGroupResponse, *http.Response, error) {\n\tif protectionMode != \"FullManage\" && protectionMode != \"ReadOnly\" {\n\t\treturn nil, nil, fmt.Errorf(\"protection mode can be FullManage or ReadOnly\")\n\t}\n\n\tv := new(CloudSecurityGroupResponse)\n\trelativeURL := fmt.Sprintf(\"%s/%s/%s\", awsSgResourcePath, d9SecurityGroupID, awsSgResourceProtectionMode)\n\tbody := UpdateProtectionModeQueryParameters{\n\t\tProtectionMode: protectionMode,\n\t}\n\n\tresp, err := service.Client.NewRequestDo(\"POST\", relativeURL, nil, body, v)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn v, resp, nil\n}", "func (mr *MockPullRequestClientMockRecorder) UpdatePullRequestBranch(org, repo, number, expectedHeadSha interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePullRequestBranch\", reflect.TypeOf((*MockPullRequestClient)(nil).UpdatePullRequestBranch), org, repo, number, expectedHeadSha)\n}", "func NewBranchProtection(ctx *pulumi.Context,\n\tname string, args *BranchProtectionArgs, opts ...pulumi.ResourceOption) (*BranchProtection, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Branch == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Branch'\")\n\t}\n\tif args.Project == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Project'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource BranchProtection\n\terr := ctx.RegisterResource(\"gitlab:index/branchProtection:BranchProtection\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *MarkerIndexBranchIDMapping) Update(other objectstorage.StorableObject) {\n\tpanic(\"updates disabled\")\n}", "func (mr *MockRepositoryInterfaceMockRecorder) GitHubUpdateClaGroupID(ctx, repositoryID, claGroupID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GitHubUpdateClaGroupID\", reflect.TypeOf((*MockRepositoryInterface)(nil).GitHubUpdateClaGroupID), ctx, repositoryID, claGroupID)\n}", "func UpdateAccount(w http.ResponseWriter, r *http.Request) {\n\tlogin := mux.Vars(r)[\"login\"]\n\toauth, ok := OAuthToken(r)\n\tif !ok {\n\t\tpanic(\"Request was authorized but no OAuth token is available!\") // this should never happen\n\t}\n\n\taccount, ok := data.GetAccountByLogin(login)\n\tif !ok {\n\t\tPrintErrorJSON(w, r, \"The requested account does not exist\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif oauth.Token.AccountUUID.String != account.UUID || !oauth.Match.Contains(\"account-write\") && !oauth.Match.Contains(\"account-admin\") {\n\t\tPrintErrorJSON(w, r, \"Access to requested account forbidden\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tmarshal := &data.AccountMarshaler{WithMail: true, WithAffiliation: true, Account: account}\n\n\tdec := json.NewDecoder(r.Body)\n\terr := dec.Decode(marshal)\n\tif err != nil {\n\t\tPrintErrorJSON(w, r, \"Error while processing account\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = account.Update()\n\tif err != nil {\n\t\tPrintErrorJSON(w, r, \"Error while processing account\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.Header().Add(\"Cache-Control\", \"no-cache\")\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tenc := json.NewEncoder(w)\n\terr = enc.Encode(marshal)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (_PermInterface *PermInterfaceTransactor) ApproveOrg(opts *bind.TransactOpts, _orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"approveOrg\", _orgId, _enodeId, _ip, _port, _raftport, _account)\n}", "func (repo PostgresPartnershipRequestBlacklistRepository) UpdatePartnershipRequestBlacklist(blacklist businesslogic.PartnershipRequestBlacklistEntry) error {\n\tif repo.Database == nil {\n\t\treturn errors.New(dalutil.DataSourceNotSpecifiedError(repo))\n\t}\n\tstmt := repo.SqlBuilder.Update(\"\").Table(DasPartnershipRequestBlacklistTable)\n\tif blacklist.ID > 0 {\n\t\tstmt = stmt.Set(DAS_PARTNERSHIP_REQUEST_BLACKLIST_COL_WHITELISTED_IND, blacklist.Whitelisted)\n\n\t\tvar err error\n\t\tif tx, txErr := repo.Database.Begin(); txErr != nil {\n\t\t\treturn txErr\n\t\t} else {\n\t\t\t_, err = stmt.RunWith(repo.Database).Exec()\n\t\t\ttx.Commit()\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"blacklist is not specified\")\n\t}\n}", "func (s *Server) updateOrgDeliveryFees(w http.ResponseWriter, r *http.Request) (interface{}, error) {\n\torg, allowed, err := s.orgModAllowed(w, r, false)\n\tif !allowed {\n\t\treturn nil, err\n\t}\n\n\treturn s.updateDeliveryFees(w, r, org.ID)\n}", "func (s *GitlabSCM) UpdateOrgMembership(ctx context.Context, opt *OrgMembershipOptions) error {\n\t// TODO no implementation provided yet\n\treturn ErrNotSupported{\n\t\tSCM: \"gitlab\",\n\t\tMethod: \"UpdateOrgMembership\",\n\t}\n}", "func (mr *MockClientMockRecorder) UpdatePullRequestBranch(org, repo, number, expectedHeadSha interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePullRequestBranch\", reflect.TypeOf((*MockClient)(nil).UpdatePullRequestBranch), org, repo, number, expectedHeadSha)\n}", "func (b *BranchDAG) SetBranchConfirmed(branchID BranchID) (err error) {\n\tif b.InclusionState(branchID) == Confirmed {\n\t\treturn\n\t}\n\n\tif _, branchErr := b.SetBranchMonotonicallyLiked(branchID, true); branchErr != nil {\n\t\terr = errors.Errorf(\"failed to set Branch with %s to be monotonically liked: %w\", branchID, branchErr)\n\t\treturn\n\t}\n\n\tif _, branchErr := b.SetBranchFinalized(branchID, true); branchErr != nil {\n\t\terr = errors.Errorf(\"failed to set Branch with %s to be finalized: %w\", branchID, branchErr)\n\t\treturn\n\t}\n\n\treturn\n}", "func NewUpdateOrganizationBillingAddressMethodNotAllowed() *UpdateOrganizationBillingAddressMethodNotAllowed {\n\treturn &UpdateOrganizationBillingAddressMethodNotAllowed{}\n}", "func (c *client) EditOrgHook(org string, id int, req HookRequest) error {\n\tc.log(\"EditOrgHook\", org, id)\n\treturn c.editHook(org, nil, id, req)\n}", "func (s service) UpdateFundingAgreement(ctx context.Context, docID, fundingID []byte, data *Data) (documents.Model, jobs.JobID, error) {\n\tmodel, err := s.docSrv.GetCurrentVersion(ctx, docID)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, jobs.NilJobID(), documents.ErrDocumentNotFound\n\t}\n\n\tdata.AgreementID = hexutil.Encode(fundingID)\n\tidx, err := extensions.FindAttributeSetIDX(model, data.AgreementID, AttrFundingLabel, agreementIDLabel, fundingFieldKey)\n\tif err != nil {\n\t\treturn nil, jobs.NilJobID(), err\n\t}\n\n\tvar collabs []identity.DID\n\tfor _, id := range []string{data.BorrowerID, data.FunderID} {\n\t\tdid, err := identity.NewDIDFromString(id)\n\t\tif err != nil {\n\t\t\treturn nil, jobs.NilJobID(), err\n\t\t}\n\n\t\tcollabs = append(collabs, did)\n\t}\n\n\t// overwriting is not enough because it is not required that\n\t// the funding payload contains all funding attributes\n\tmodel, err = extensions.DeleteAttributesSet(model, Data{}, idx, fundingFieldKey)\n\tif err != nil {\n\t\treturn nil, jobs.NilJobID(), err\n\t}\n\n\tattributes, err := extensions.FillAttributeList(*data, idx, fundingFieldKey)\n\tif err != nil {\n\t\treturn nil, jobs.NilJobID(), err\n\t}\n\n\terr = model.AddAttributes(\n\t\tdocuments.CollaboratorsAccess{\n\t\t\tReadWriteCollaborators: collabs,\n\t\t},\n\t\ttrue,\n\t\tattributes...,\n\t)\n\tif err != nil {\n\t\treturn nil, jobs.NilJobID(), err\n\t}\n\n\tmodel, jobID, _, err := s.docSrv.Update(ctx, model)\n\tif err != nil {\n\t\treturn nil, jobs.NilJobID(), err\n\t}\n\n\treturn model, jobID, nil\n}", "func (vcd *TestVCD) Test_UpdateOrg(check *C) {\n\tif vcd.skipAdminTests {\n\t\tcheck.Skip(fmt.Sprintf(TestRequiresSysAdminPrivileges, check.TestName()))\n\t}\n\torg, _ := GetAdminOrgByName(vcd.client, TestUpdateOrg)\n\tif org != (AdminOrg{}) {\n\t\terr := org.Delete(true, true)\n\t\tcheck.Assert(err, IsNil)\n\t}\n\ttask, err := CreateOrg(vcd.client, TestUpdateOrg, TestUpdateOrg, TestUpdateOrg, &types.OrgSettings{\n\t\tOrgLdapSettings: &types.OrgLdapSettingsType{OrgLdapMode: \"NONE\"},\n\t}, true)\n\tcheck.Assert(err, IsNil)\n\terr = task.WaitTaskCompletion()\n\tcheck.Assert(err, IsNil)\n\tAddToCleanupList(TestUpdateOrg, \"org\", \"\", \"TestUpdateOrg\")\n\t// fetch newly created org\n\torg, err = GetAdminOrgByName(vcd.client, TestUpdateOrg)\n\tcheck.Assert(err, IsNil)\n\tcheck.Assert(org.AdminOrg.Name, Equals, TestUpdateOrg)\n\tcheck.Assert(org.AdminOrg.Description, Equals, TestUpdateOrg)\n\torg.AdminOrg.OrgSettings.OrgGeneralSettings.DeployedVMQuota = 100\n\ttask, err = org.Update()\n\tcheck.Assert(err, IsNil)\n\t// Wait until update is complete\n\terr = task.WaitTaskCompletion()\n\tcheck.Assert(err, IsNil)\n\t// Refresh\n\terr = org.Refresh()\n\tcheck.Assert(err, IsNil)\n\tcheck.Assert(org.AdminOrg.OrgSettings.OrgGeneralSettings.DeployedVMQuota, Equals, 100)\n\t// Delete, with force and recursive true\n\terr = org.Delete(true, true)\n\tcheck.Assert(err, IsNil)\n\tdoesOrgExist(check, vcd)\n}", "func UpdateLimitAccount(currentLimit float64) {\n\n\terr := utils.CheckTempFile(PathFileC)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tjsonFile, err := os.Open(PathFileC)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer jsonFile.Close()\n\n\taccountJSON, err := ioutil.ReadAll(jsonFile)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tvar account models.Account\n\n\terr = json.Unmarshal(accountJSON, &account)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\taccount.Accounts.AvailableLimit = currentLimit\n\n\taccountJSON, err = json.Marshal(account)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\terr = ioutil.WriteFile(PathFileC, accountJSON, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (r *SettingRepository) EditBranchByID(branch *models.Branch) error {\n\terr := r.C.Update(bson.M{\"_id\": branch.ID},\n\t\tbson.M{\"$set\": bson.M{\n\t\t\t\"name\": branch.Name,\n\t\t\t\"updatedat\": time.Now(),\n\t\t\t\"status\": branch.Status,\n\t\t}})\n\treturn err\n}", "func (c *client) UpdatePullRequestBranch(org, repo string, number int, expectedHeadSha *string) error {\n\tdurationLogger := c.log(\"UpdatePullRequestBranch\", org, repo)\n\tdefer durationLogger()\n\n\tdata := struct {\n\t\t// The expected SHA of the pull request's HEAD ref. This is the most recent commit on the pull request's branch.\n\t\t// If the expected SHA does not match the pull request's HEAD, you will receive a 422 Unprocessable Entity status.\n\t\t// You can use the \"List commits\" endpoint to find the most recent commit SHA. Default: SHA of the pull request's current HEAD ref.\n\t\tExpectedHeadSha *string `json:\"expected_head_sha,omitempty\"`\n\t}{\n\t\tExpectedHeadSha: expectedHeadSha,\n\t}\n\n\tcode, err := c.request(&request{\n\t\tmethod: http.MethodPut,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/pulls/%d/update-branch\", org, repo, number),\n\t\taccept: \"application/vnd.github.lydian-preview+json\",\n\t\torg: org,\n\t\trequestBody: &data,\n\t\texitCodes: []int{202, 422},\n\t}, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif code == http.StatusUnprocessableEntity {\n\t\tmsg := \"mismatch expected head sha\"\n\t\tif expectedHeadSha != nil {\n\t\t\tmsg = fmt.Sprintf(\"%s: %s\", msg, *expectedHeadSha)\n\t\t}\n\t\treturn errors.New(msg)\n\t}\n\n\treturn nil\n}", "func UpdateCompanyBranchHyCompanybranchOKIdname(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.HyCompanybranchController, id int, payload *app.UpdateCompanyBranchHyCompanybranchPayload) (http.ResponseWriter, *app.CompanyIdname) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil, nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/company/branch/%v\", id),\n\t}\n\treq, _err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif _err != nil {\n\t\tpanic(\"invalid test \" + _err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"ID\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"HyCompanybranchTest\"), rw, req, prms)\n\tupdateCompanyBranchCtx, __err := app.NewUpdateCompanyBranchHyCompanybranchContext(goaCtx, req, service)\n\tif __err != nil {\n\t\t_e, _ok := __err.(goa.ServiceError)\n\t\tif !_ok {\n\t\t\tpanic(\"invalid test data \" + __err.Error()) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected parameter validation error: %+v\", _e)\n\t\treturn nil, nil\n\t}\n\tupdateCompanyBranchCtx.Payload = payload\n\n\t// Perform action\n\t__err = ctrl.UpdateCompanyBranch(updateCompanyBranchCtx)\n\n\t// Validate response\n\tif __err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", __err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt *app.CompanyIdname\n\tif resp != nil {\n\t\tvar __ok bool\n\t\tmt, __ok = resp.(*app.CompanyIdname)\n\t\tif !__ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.CompanyIdname\", resp, resp)\n\t\t}\n\t\t__err = mt.Validate()\n\t\tif __err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", __err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func (_PermInterface *PermInterfaceSession) ApproveOrg(_orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.ApproveOrg(&_PermInterface.TransactOpts, _orgId, _enodeId, _ip, _port, _raftport, _account)\n}", "func (p *perm) CommitChange() {\n\tp.enforcer.SavePolicy()\n}", "func (m *MarkerBranchIDMappingManager) SetBranchID(marker *markers.Marker, branchID ledgerstate.BranchID) {\n\tm.tangle.Storage.MarkerIndexBranchIDMapping(marker.SequenceID(), NewMarkerIndexBranchIDMapping).Consume(func(markerIndexBranchIDMapping *MarkerIndexBranchIDMapping) {\n\t\tmarkerIndexBranchIDMapping.SetBranchID(marker.Index(), branchID)\n\t})\n}", "func (db *DB) UpdateCipher(newData bw.Cipher, owner string, ciphID string) error {\n\tiowner, err := strconv.ParseInt(owner, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ticiphID, err := strconv.ParseInt(ciphID, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfavorite := 0\n\tif newData.Favorite {\n\t\tfavorite = 1\n\t}\n\n\tstmt, err := db.db.Prepare(\"UPDATE ciphers SET type=$1, revisiondate=$2, data=$3, folderid=$4, favorite=$5 WHERE id=$6 AND owner=$7\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbdata, err := newData.Data.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = stmt.Exec(newData.Type, time.Now().Unix(), bdata, newData.FolderId, favorite, iciphID, iowner)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_PermInterface *PermInterfaceTransactorSession) ApproveOrg(_orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.ApproveOrg(&_PermInterface.TransactOpts, _orgId, _enodeId, _ip, _port, _raftport, _account)\n}", "func (_PermInterface *PermInterfaceTransactor) UpdateOrgStatus(opts *bind.TransactOpts, _orgId string, _action *big.Int) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"updateOrgStatus\", _orgId, _action)\n}", "func (m *MockSendUpdateQuery) UpdateBranch(arg0 context.Context, arg1 interfaces.NewBranch, arg2 bool) error {\n\tret := m.ctrl.Call(m, \"UpdateBranch\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (r *DeviceCompliancePolicyGroupAssignmentRequest) Update(ctx context.Context, reqObj *DeviceCompliancePolicyGroupAssignment) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (_PermInterface *PermInterfaceSession) ApproveBlacklistedAccountRecovery(_orgId string, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.ApproveBlacklistedAccountRecovery(&_PermInterface.TransactOpts, _orgId, _account)\n}", "func (mr *MockRepositoryClientMockRecorder) GetBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBranchProtection\", reflect.TypeOf((*MockRepositoryClient)(nil).GetBranchProtection), org, repo, branch)\n}", "func (_PermInterface *PermInterfaceTransactor) ApproveBlacklistedAccountRecovery(opts *bind.TransactOpts, _orgId string, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"approveBlacklistedAccountRecovery\", _orgId, _account)\n}", "func (c *client) UpdateOrgMembership(org, user string, admin bool) (*OrgMembership, error) {\n\tc.log(\"UpdateOrgMembership\", org, user, admin)\n\tom := OrgMembership{}\n\tif admin {\n\t\tom.Role = RoleAdmin\n\t} else {\n\t\tom.Role = RoleMember\n\t}\n\tif c.dry {\n\t\treturn &om, nil\n\t}\n\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodPut,\n\t\tpath: fmt.Sprintf(\"/orgs/%s/memberships/%s\", org, user),\n\t\torg: org,\n\t\trequestBody: &om,\n\t\texitCodes: []int{200},\n\t}, &om)\n\treturn &om, err\n}", "func (c *Client) UpdateBarcodeRule(br *BarcodeRule) error {\n\treturn c.UpdateBarcodeRules([]int64{br.Id.Get()}, br)\n}", "func (operator *AccessOperator) UpdateCommit(cxt context.Context, option *UpdateCommitOption) error {\n\t//business first\n\tbusiness, err := operator.GetBusiness(cxt, operator.Business)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif business == nil {\n\t\tlogger.V(3).Infof(\"UpdateCommit: found no relative Business %s\", operator.Business)\n\t\treturn fmt.Errorf(\"No relative Business %s\", operator.Business)\n\t}\n\n\trequest := &accessserver.UpdateCommitReq{\n\t\tSeq: pkgcommon.Sequence(),\n\t\tBid: business.Bid,\n\t\tCommitid: option.CommitID,\n\t\tTemplateid: option.TemplateID,\n\t\tTemplate: option.Template,\n\t\tConfigs: option.Configs,\n\t\tChanges: option.Changes,\n\t\tOperator: operator.User,\n\t}\n\tgrpcOptions := []grpc.CallOption{\n\t\tgrpc.WaitForReady(true),\n\t}\n\tresponse, err := operator.Client.UpdateCommit(cxt, request, grpcOptions...)\n\tif err != nil {\n\t\tlogger.V(3).Infof(\"UpdateCommit %s failed, %s\", option.CommitID, err.Error())\n\t\treturn err\n\t}\n\tif response.ErrCode != common.ErrCode_E_OK {\n\t\tlogger.V(3).Infof(\"UpdateCommit %s successfully, but response Err, %s\", option.CommitID, response.ErrMsg)\n\t\treturn fmt.Errorf(\"%s\", response.ErrMsg)\n\t}\n\treturn nil\n\n}", "func (o *AuthUserUserPermission) UpdateGP(whitelist ...string) {\n\tif err := o.Update(boil.GetDB(), whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (r *WorkbookWorksheetProtectionRequest) Update(ctx context.Context, reqObj *WorkbookWorksheetProtection) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (db *MySQLDB) UpdateTenant(ctx context.Context, tenant *Tenant) error {\n\tfLog := mysqlLog.WithField(\"func\", \"UpdateTenant\").WithField(\"RequestID\", ctx.Value(constants.RequestID))\n\n\texist, err := db.IsTenantRecIDExist(ctx, tenant.RecID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exist {\n\t\treturn ErrNotFound\n\t}\n\n\torigin, err := db.GetTenantByRecID(ctx, tenant.RecID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdomainChanged := origin.Domain != tenant.Domain\n\n\tq := \"UPDATE HANSIP_TENANT SET TENANT_NAME=?, TENANT_DOMAIN=?, DESCRIPTION=? WHERE REC_ID=?\"\n\t_, err = db.instance.ExecContext(ctx, q,\n\t\ttenant.Name, tenant.Domain, tenant.Description, tenant.RecID)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\treturn &ErrDBExecuteError{\n\t\t\tWrapped: err,\n\t\t\tMessage: \"Error UpdateTenant\",\n\t\t\tSQL: q,\n\t\t}\n\t}\n\n\tif domainChanged {\n\t\tq = \"UPDATE HANSIP_ROLE SET ROLE_DOMAIN=? WHERE ROLE_DOMAIN=?\"\n\t\t_, err = db.instance.ExecContext(ctx, q,\n\t\t\ttenant.Domain, origin.Domain)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\t\treturn &ErrDBExecuteError{\n\t\t\t\tWrapped: err,\n\t\t\t\tMessage: \"Error UpdateTenant\",\n\t\t\t\tSQL: q,\n\t\t\t}\n\t\t}\n\n\t\tq = \"UPDATE HANSIP_GROUP SET GROUP_DOMAIN=? WHERE GROUP_DOMAIN=?\"\n\t\t_, err = db.instance.ExecContext(ctx, q,\n\t\t\ttenant.Domain, origin.Domain)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\t\treturn &ErrDBExecuteError{\n\t\t\t\tWrapped: err,\n\t\t\t\tMessage: \"Error UpdateTenant\",\n\t\t\t\tSQL: q,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func addBranchRestrictions(ft *factsTable, b *Block, br branch) {\n\tc := b.Controls[0]\n\tswitch br {\n\tcase negative:\n\t\taddRestrictions(b, ft, boolean, nil, c, eq)\n\tcase positive:\n\t\taddRestrictions(b, ft, boolean, nil, c, lt|gt)\n\tdefault:\n\t\tpanic(\"unknown branch\")\n\t}\n\tif tr, has := domainRelationTable[c.Op]; has {\n\t\t// When we branched from parent we learned a new set of\n\t\t// restrictions. Update the factsTable accordingly.\n\t\td := tr.d\n\t\tif d == signed && ft.isNonNegative(c.Args[0]) && ft.isNonNegative(c.Args[1]) {\n\t\t\td |= unsigned\n\t\t}\n\t\tswitch c.Op {\n\t\tcase OpIsInBounds, OpIsSliceInBounds:\n\t\t\t// 0 <= a0 < a1 (or 0 <= a0 <= a1)\n\t\t\t//\n\t\t\t// On the positive branch, we learn:\n\t\t\t// signed: 0 <= a0 < a1 (or 0 <= a0 <= a1)\n\t\t\t// unsigned: a0 < a1 (or a0 <= a1)\n\t\t\t//\n\t\t\t// On the negative branch, we learn (0 > a0 ||\n\t\t\t// a0 >= a1). In the unsigned domain, this is\n\t\t\t// simply a0 >= a1 (which is the reverse of the\n\t\t\t// positive branch, so nothing surprising).\n\t\t\t// But in the signed domain, we can't express the ||\n\t\t\t// condition, so check if a0 is non-negative instead,\n\t\t\t// to be able to learn something.\n\t\t\tswitch br {\n\t\t\tcase negative:\n\t\t\t\td = unsigned\n\t\t\t\tif ft.isNonNegative(c.Args[0]) {\n\t\t\t\t\td |= signed\n\t\t\t\t}\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r^(lt|gt|eq))\n\t\t\tcase positive:\n\t\t\t\taddRestrictions(b, ft, signed, ft.zero, c.Args[0], lt|eq)\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r)\n\t\t\t}\n\t\tdefault:\n\t\t\tswitch br {\n\t\t\tcase negative:\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r^(lt|gt|eq))\n\t\t\tcase positive:\n\t\t\t\taddRestrictions(b, ft, d, c.Args[0], c.Args[1], tr.r)\n\t\t\t}\n\t\t}\n\n\t}\n}", "func (mr *MockClientMockRecorder) GetBranchProtection(org, repo, branch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBranchProtection\", reflect.TypeOf((*MockClient)(nil).GetBranchProtection), org, repo, branch)\n}", "func (fbo *folderBranchOps) MigrateToImplicitTeam(\n\tctx context.Context, id tlf.ID) (err error) {\n\t// Only MasterBranch FBOs may be migrated.\n\tfb := data.FolderBranch{Tlf: id, Branch: data.MasterBranch}\n\tif fb != fbo.folderBranch {\n\t\t// TODO: log instead of panic?\n\t\tpanic(WrongOpsError{fbo.folderBranch, fb})\n\t}\n\n\tfbo.log.CDebugf(ctx, \"Starting migration of TLF %s\", id)\n\tdefer func() {\n\t\tfbo.deferLog.CDebugf(\n\t\t\tctx, \"Finished migration of TLF %s, err=%+v\", id, err)\n\t}()\n\n\tif id.Type() != tlf.Private && id.Type() != tlf.Public {\n\t\treturn errors.Errorf(\"Cannot migrate a TLF of type: %s\", id.Type())\n\t}\n\n\tlState := makeFBOLockState()\n\tfbo.mdWriterLock.Lock(lState)\n\tdefer fbo.mdWriterLock.Unlock(lState)\n\n\tmd, err := fbo.getMDForMigrationLocked(ctx, lState)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif md == (ImmutableRootMetadata{}) {\n\t\tfbo.log.CDebugf(ctx, \"Nothing to upgrade\")\n\t\treturn nil\n\t}\n\n\tif md.IsFinal() {\n\t\tfbo.log.CDebugf(ctx, \"No need to upgrade a finalized TLF\")\n\t\treturn nil\n\t}\n\n\tif md.TypeForKeying() == tlf.TeamKeying {\n\t\tfbo.log.CDebugf(ctx, \"Already migrated\")\n\t\treturn nil\n\t}\n\n\tname := string(md.GetTlfHandle().GetCanonicalName())\n\tfbo.log.CDebugf(ctx, \"Looking up implicit team for %s\", name)\n\tnewHandle, err := tlfhandle.ParseHandle(\n\t\tctx, fbo.config.KBPKI(), fbo.config.MDOps(), fbo.config,\n\t\tname, id.Type())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Make sure the new handle contains just a team.\n\tif newHandle.TypeForKeying() != tlf.TeamKeying {\n\t\treturn errors.New(\"No corresponding implicit team yet\")\n\t}\n\n\tsession, err := fbo.config.KBPKI().GetCurrentSession(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisWriter := true // getMDForMigrationLocked already checked this.\n\tnewMD, err := md.MakeSuccessorWithNewHandle(\n\t\tctx, newHandle, fbo.config.MetadataVersion(), fbo.config.Codec(),\n\t\tfbo.config.KeyManager(), fbo.config.KBPKI(), fbo.config.KBPKI(),\n\t\tfbo.config, md.mdID, isWriter)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif newMD.TypeForKeying() != tlf.TeamKeying {\n\t\treturn errors.New(\"Migration failed\")\n\t}\n\n\t// Add an empty operation to satisfy assumptions elsewhere.\n\tnewMD.AddOp(newRekeyOp())\n\n\treturn fbo.finalizeMDRekeyWriteLocked(\n\t\tctx, lState, newMD, session.VerifyingKey)\n}", "func (_PermInterface *PermInterfaceSession) UpdateOrgStatus(_orgId string, _action *big.Int) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.UpdateOrgStatus(&_PermInterface.TransactOpts, _orgId, _action)\n}", "func (c *client) GetBranchProtection(org, repo, branch string) (*BranchProtection, error) {\n\tdurationLogger := c.log(\"GetBranchProtection\", org, repo, branch)\n\tdefer durationLogger()\n\n\tcode, body, err := c.requestRaw(&request{\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/branches/%s/protection\", org, repo, branch),\n\t\torg: org,\n\t\t// GitHub returns 404 for this call if either:\n\t\t// - The branch is not protected\n\t\t// - The access token used does not have sufficient privileges\n\t\t// We therefore need to introspect the response body.\n\t\texitCodes: []int{200, 404},\n\t})\n\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase code == 200:\n\t\tvar bp BranchProtection\n\t\tif err := json.Unmarshal(body, &bp); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &bp, nil\n\tcase code == 404:\n\t\t// continue\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected status code: %d\", code)\n\t}\n\n\tvar ge githubError\n\tif err := json.Unmarshal(body, &ge); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the error was because the branch is not protected, we return a\n\t// nil pointer to indicate this.\n\tif ge.Message == \"Branch not protected\" {\n\t\treturn nil, nil\n\t}\n\n\t// Otherwise we got some other 404 error.\n\treturn nil, fmt.Errorf(\"getting branch protection 404: %s\", ge.Message)\n}", "func (m *MarkerIndexBranchIDMapping) SetBranchID(index markers.Index, branchID ledgerstate.BranchID) {\n\tm.mappingMutex.Lock()\n\tdefer m.mappingMutex.Unlock()\n\n\tm.mapping.Set(index, branchID)\n}", "func IsUserInProtectBranchWhitelist(repoID, userID int64, branch string) bool {\n\thas, err := x.Where(\"repo_id = ?\", repoID).And(\"user_id = ?\", userID).And(\"name = ?\", branch).Get(new(ProtectBranchWhitelist))\n\treturn has && err == nil\n}", "func (m *MockRepositoryClient) RemoveBranchProtection(org, repo, branch string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RemoveBranchProtection\", org, repo, branch)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClient) RemoveBranchProtection(org, repo, branch string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RemoveBranchProtection\", org, repo, branch)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_PermInterface *PermInterfaceTransactorSession) ApproveBlacklistedAccountRecovery(_orgId string, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.ApproveBlacklistedAccountRecovery(&_PermInterface.TransactOpts, _orgId, _account)\n}", "func UpdateAccountEmail(w http.ResponseWriter, r *http.Request) {\n\n\tlogin := mux.Vars(r)[\"login\"]\n\toauth, ok := OAuthToken(r)\n\tif !ok {\n\t\tpanic(\"Missing OAuth token\")\n\t}\n\n\tacc, ok := data.GetAccountByLogin(login)\n\tif !ok {\n\t\tPrintErrorJSON(w, r, \"The requested account does not exist\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif oauth.Token.AccountUUID.String != acc.UUID || !oauth.Match.Contains(\"account-write\") {\n\t\tPrintErrorJSON(w, r, \"Unauthorized account access\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tcred := &struct {\n\t\tPassword string `json:\"password\"`\n\t\tEmail string `json:\"email\"`\n\t}{}\n\n\tdec := json.NewDecoder(r.Body)\n\t_ = dec.Decode(cred)\n\n\tif !acc.VerifyPassword(cred.Password) {\n\t\tvalErr := &util.ValidationError{\n\t\t\tMessage: \"Invalid password\",\n\t\t\tFieldErrors: map[string]string{\"password\": \"Invalid password\"}}\n\t\tPrintErrorJSON(w, r, valErr, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := acc.UpdateEmail(cred.Email)\n\tif err != nil {\n\t\tPrintErrorJSON(w, r, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttmplFields := &struct {\n\t\tFrom string\n\t\tTo string\n\t\tSubject string\n\t\tBody string\n\t}{}\n\ttmplFields.From = conf.GetSmtpCredentials().From\n\ttmplFields.To = cred.Email\n\ttmplFields.Subject = \"GIN account confirmation\"\n\ttmplFields.Body = \"The e-mail address of your GIN account has been successfully changed.\"\n\n\tcontent := util.MakeEmailTemplate(\"emailplain.txt\", tmplFields)\n\temail := &data.Email{}\n\terr = email.Create(util.NewStringSet(cred.Email), content.Bytes())\n\tif err != nil {\n\t\tmsg := \"An error occurred trying to create change e-mail address confirmation.\"\n\t\tPrintErrorJSON(w, r, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func NewUpdateOrganizationBillingAddressForbidden() *UpdateOrganizationBillingAddressForbidden {\n\treturn &UpdateOrganizationBillingAddressForbidden{}\n}", "func (m *MockPullRequestClient) UpdatePullRequestBranch(org, repo string, number int, expectedHeadSha *string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePullRequestBranch\", org, repo, number, expectedHeadSha)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Update(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\n\t// Decode the JSON body\n\tacct := datastore.Account{}\n\terr = json.NewDecoder(r.Body).Decode(&acct)\n\tswitch {\n\t// Check we have some data\n\tcase err == io.EOF:\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tresponse.FormatStandardResponse(false, \"error-account-data\", \"\", \"No account data supplied\", w)\n\t\treturn\n\t\t// Check for parsing errors\n\tcase err != nil:\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tresponse.FormatStandardResponse(false, \"error-decode-json\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tupdateHandler(w, authUser, false, acct)\n}", "func (m *MockClient) UpdatePullRequestBranch(org, repo string, number int, expectedHeadSha *string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePullRequestBranch\", org, repo, number, expectedHeadSha)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (s *BucketService) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) {\n\tb, err := s.s.FindBucketByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := authorizeWriteBucket(ctx, b.OrgID, id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.s.UpdateBucket(ctx, id, upd)\n}", "func (fbo *folderBranchOps) TeamAbandoned(\n\tctx context.Context, tid keybase1.TeamID) {\n\tctx, cancelFunc := fbo.newCtxWithFBOIDWithCtx(ctx)\n\tdefer cancelFunc()\n\tfbo.log.CDebugf(ctx, \"Abandoning team %s\", tid)\n\tfbo.locallyFinalizeTLF(ctx)\n}", "func UpdateAccountPassword(w http.ResponseWriter, r *http.Request) {\n\tlogin := mux.Vars(r)[\"login\"]\n\toauth, ok := OAuthToken(r)\n\tif !ok {\n\t\tpanic(\"Request was authorized but no OAuth token is available!\") // this should never happen\n\t}\n\n\taccount, ok := data.GetAccountByLogin(login)\n\tif !ok {\n\t\tPrintErrorJSON(w, r, \"The requested account does not exist\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif oauth.Token.AccountUUID.String != account.UUID || !oauth.Match.Contains(\"account-write\") {\n\t\tPrintErrorJSON(w, r, \"Access to requested account forbidden\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tpwData := &struct {\n\t\tPasswordOld string `json:\"password_old\"`\n\t\tPasswordNew string `json:\"password_new\"`\n\t\tPasswordNewRepeat string `json:\"password_new_repeat\"`\n\t}{}\n\tdec := json.NewDecoder(r.Body)\n\t_ = dec.Decode(pwData)\n\n\tif !account.VerifyPassword(pwData.PasswordOld) {\n\t\terr := &util.ValidationError{\n\t\t\tMessage: \"Unable to set password\",\n\t\t\tFieldErrors: map[string]string{\"password_old\": \"Wrong password\"}}\n\t\tPrintErrorJSON(w, r, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif len(pwData.PasswordNew) < 6 {\n\t\terr := &util.ValidationError{\n\t\t\tMessage: \"Unable to set password\",\n\t\t\tFieldErrors: map[string]string{\"password_new\": \"Password must be at least 6 characters long\"}}\n\t\tPrintErrorJSON(w, r, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif pwData.PasswordNew != pwData.PasswordNewRepeat {\n\t\terr := &util.ValidationError{\n\t\t\tMessage: \"Unable to set password\",\n\t\t\tFieldErrors: map[string]string{\"password_new_repeat\": \"Repeated password does not match\"}}\n\t\tPrintErrorJSON(w, r, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := account.UpdatePassword(pwData.PasswordNew)\n\tif err != nil {\n\t\tPrintErrorJSON(w, r, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (r *DeviceCompliancePolicyAssignmentRequest) Update(ctx context.Context, reqObj *DeviceCompliancePolicyAssignment) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (mr *MockOrganizationClientMockRecorder) UpdateOrgMembership(org, user, admin interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateOrgMembership\", reflect.TypeOf((*MockOrganizationClient)(nil).UpdateOrgMembership), org, user, admin)\n}", "func (c *AuthenticationComponent) UpdateAccount(ctx context.Context, Id uint32, email string) error {\n\tif err, _ := c.isValidID(Id); err != nil {\n\t\tc.Logger.Error(err.Error())\n\t\treturn err\n\t}\n\n\tif err, _ := c.isValidEmail(email); err != nil {\n\t\tc.Logger.Error(err.Error())\n\t\treturn err\n\t}\n\n\taccountId := strconv.Itoa(int(Id))\n\tif err := c.Client.Update(accountId, email); err != nil {\n\t\tc.Logger.Error(err.Error())\n\t\treturn err\n\t}\n\n\tc.Logger.Info(\"Successfully updated user account\", zap.Int(\"Id\", int(Id)))\n\treturn nil\n}", "func (_PermInterface *PermInterfaceTransactorSession) UpdateOrgStatus(_orgId string, _action *big.Int) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.UpdateOrgStatus(&_PermInterface.TransactOpts, _orgId, _action)\n}", "func (mr *MockClientMockRecorder) UpdateOrgMembership(org, user, admin interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateOrgMembership\", reflect.TypeOf((*MockClient)(nil).UpdateOrgMembership), org, user, admin)\n}", "func UpdateVLANGroupMembership(w http.ResponseWriter, r *http.Request) {\n\thr := HTTPResponse{w}\n\tvlan, ok := getVLANHelper(hr, r)\n\tif !ok {\n\t\treturn\n\t}\n\tvar newGroups []string\n\tif err := json.NewDecoder(r.Body).Decode(&newGroups); err != nil {\n\t\thr.JSONMsg(http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\t// Determine group modifications necessary\n\t// -1 : Removed\n\t// 0 : No change\n\t// 1 : Added\n\tctx := GetContext(r)\n\tgroupModifications := make(map[string]int)\n\tfor _, oldGroup := range vlan.VLANGroups() {\n\t\tgroupModifications[oldGroup] = -1\n\t}\n\tfor _, newGroup := range newGroups {\n\t\tgroupModifications[newGroup]++\n\t}\n\t// Make group modifications\n\tfor groupID, action := range groupModifications {\n\t\tvlanGroup, err := ctx.VLANGroup(groupID)\n\t\tif err != nil {\n\t\t\tif ctx.IsKeyNotFound(err) {\n\t\t\t\thr.JSONMsg(http.StatusBadRequest, \"group not found\")\n\t\t\t} else {\n\t\t\t\thr.JSONMsg(http.StatusInternalServerError, err.Error())\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tswitch action {\n\t\tcase -1:\n\t\t\tif err := vlanGroup.RemoveVLAN(vlan); err != nil {\n\t\t\t\thr.JSONError(http.StatusInternalServerError, err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase 0:\n\t\t\tbreak\n\t\tcase 1:\n\t\t\tif err := vlanGroup.AddVLAN(vlan); err != nil {\n\t\t\t\thr.JSONError(http.StatusInternalServerError, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\thr.JSON(http.StatusOK, vlan.VLANGroups())\n}", "func UpdateAccount(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func (oo *OnuDeviceEntry) ModifySwImageActiveCommit(ctx context.Context, aCommitted uint8) {\n\too.mutexOnuSwImageIndications.Lock()\n\tdefer oo.mutexOnuSwImageIndications.Unlock()\n\tlogger.Debugw(ctx, \"software-image set active entity commit flag\", log.Fields{\n\t\t\"device-id\": oo.deviceID, \"committed\": aCommitted})\n\too.onuSwImageIndications.ActiveEntityEntry.IsCommitted = aCommitted\n\t//commit flag is not part of persistency data (yet) - no need to update that\n}", "func (o *Auth) UpdateGP(whitelist ...string) {\n\tif err := o.Update(boil.GetDB(), whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (a *Client) MergeBranch(params *MergeBranchParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MergeBranchOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewMergeBranchParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"mergeBranch\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/vcs/branch/{branchID}/merge\",\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: &MergeBranchReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*MergeBranchOK)\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 mergeBranch: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func UpdateCgroupPermission(CgroupBase string, device *types.Device, isAddDevice bool) error {\n\tvar path string\n\n\tif isAddDevice {\n\t\tpath = filepath.Join(CgroupBase, \"devices.allow\")\n\t} else {\n\t\tpath = filepath.Join(CgroupBase, \"devices.deny\")\n\t}\n\tvalue := device.CgroupString()\n\tif err := ioutil.WriteFile(path, []byte(value), 0600); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mr *MockClientMockRecorder) UpdateTeamRepo(id, org, repo, permission interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateTeamRepo\", reflect.TypeOf((*MockClient)(nil).UpdateTeamRepo), id, org, repo, permission)\n}", "func (o BranchProtectionOutput) BranchProtectionId() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *BranchProtection) pulumi.IntOutput { return v.BranchProtectionId }).(pulumi.IntOutput)\n}", "func (m *MockClient) UpdateOrgMembership(org, user string, admin bool) (*github.OrgMembership, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateOrgMembership\", org, user, admin)\n\tret0, _ := ret[0].(*github.OrgMembership)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *client) UpdateTeamRepo(id int, org, repo string, permission TeamPermission) error {\n\tc.logger.WithField(\"methodName\", \"UpdateTeamRepo\").\n\t\tWarn(\"method is deprecated, and will result in multiple api calls to achieve result\")\n\tdurationLogger := c.log(\"UpdateTeamRepo\", id, org, repo, permission)\n\tdefer durationLogger()\n\n\tif c.fake || c.dry {\n\t\treturn nil\n\t}\n\n\torganization, err := c.GetOrg(org)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata := struct {\n\t\tPermission string `json:\"permission\"`\n\t}{\n\t\tPermission: string(permission),\n\t}\n\n\t_, err = c.request(&request{\n\t\tmethod: http.MethodPut,\n\t\tpath: fmt.Sprintf(\"/organizations/%d/team/%d/repos/%s/%s\", organization.Id, id, org, repo),\n\t\torg: org,\n\t\trequestBody: &data,\n\t\texitCodes: []int{204},\n\t}, nil)\n\treturn err\n}", "func (m *MockOrganizationClient) UpdateOrgMembership(org, user string, admin bool) (*github.OrgMembership, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateOrgMembership\", org, user, admin)\n\tret0, _ := ret[0].(*github.OrgMembership)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (b Branch) Fix(ctx context.Context, c *github.Client, owner, repo string) error {\n\tlog.Warn().\n\t\tStr(\"org\", owner).\n\t\tStr(\"repo\", repo).\n\t\tStr(\"area\", polName).\n\t\tMsg(\"Action fix is configured, but not implemented.\")\n\treturn nil\n}", "func (o *AuthUser) UpdateGP(whitelist ...string) {\n\tif err := o.Update(boil.GetDB(), whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (b *BranchDAG) updateInclusionState(branchID BranchID, inclusionState InclusionState) (err error) {\n\t// initialize stack for iteration\n\tbranchStack := list.New()\n\tbranchStack.PushBack(branchID)\n\n\t// iterate through stack\nProcessStack:\n\tfor branchStack.Len() >= 1 {\n\t\t// retrieve first element from the stack\n\t\tcurrentStackElement := branchStack.Front()\n\t\tbranchStack.Remove(currentStackElement)\n\n\t\t// load Branch\n\t\tcurrentCachedBranch := b.Branch(currentStackElement.Value.(BranchID))\n\n\t\t// unwrap current CachedBranch\n\t\tcurrentBranch := currentCachedBranch.Unwrap()\n\t\tif currentBranch == nil {\n\t\t\tcurrentCachedBranch.Release()\n\t\t\terr = errors.Errorf(\"failed to load Branch with %s: %w\", currentCachedBranch.ID(), cerrors.ErrFatal)\n\t\t\treturn\n\t\t}\n\n\t\t// execute case dependent logic\n\t\tswitch inclusionState {\n\t\tcase Confirmed:\n\t\t\t// abort if the current Branch is not liked or not finalized\n\t\t\tif !currentBranch.Liked() || !currentBranch.Finalized() {\n\t\t\t\tcurrentCachedBranch.Release()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// abort if any parent Branch is not confirmed\n\t\t\tfor parentBranchID := range currentBranch.Parents() {\n\t\t\t\t// load parent Branch\n\t\t\t\tcachedParentBranch := b.Branch(parentBranchID)\n\n\t\t\t\t// unwrap parent Branch\n\t\t\t\tparentBranch := cachedParentBranch.Unwrap()\n\t\t\t\tif parentBranch == nil {\n\t\t\t\t\tcurrentCachedBranch.Release()\n\t\t\t\t\tcachedParentBranch.Release()\n\t\t\t\t\terr = errors.Errorf(\"failed to load parent Branch with %s: %w\", parentBranchID, cerrors.ErrFatal)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// abort if parent Branch is not confirmed\n\t\t\t\tif parentBranch.InclusionState() != Confirmed {\n\t\t\t\t\tcurrentCachedBranch.Release()\n\t\t\t\t\tcachedParentBranch.Release()\n\t\t\t\t\tcontinue ProcessStack\n\t\t\t\t}\n\n\t\t\t\t// release parent CachedBranch\n\t\t\t\tcachedParentBranch.Release()\n\t\t\t}\n\n\t\t\t// abort if the Branch is already confirmed\n\t\t\tif !currentBranch.SetInclusionState(Confirmed) {\n\t\t\t\tcurrentCachedBranch.Release()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// trigger event\n\t\t\tb.Events.BranchConfirmed.Trigger(NewBranchDAGEvent(currentCachedBranch))\n\t\tcase Rejected:\n\t\t\t// abort if the current Branch is not confirmed already\n\t\t\tif !currentBranch.SetInclusionState(Rejected) {\n\t\t\t\tcurrentCachedBranch.Release()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// trigger event\n\t\t\tb.Events.BranchRejected.Trigger(NewBranchDAGEvent(currentCachedBranch))\n\t\tcase Pending:\n\t\t\t// abort if the current Branch is not confirmed already\n\t\t\tif !currentBranch.SetInclusionState(Pending) {\n\t\t\t\tcurrentCachedBranch.Release()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// trigger event\n\t\t\tb.Events.BranchPending.Trigger(NewBranchDAGEvent(currentCachedBranch))\n\t\t}\n\n\t\t// iterate through ChildBranch references and queue found Branches for propagation\n\t\tcachedChildBranchReferences := b.ChildBranches(currentBranch.ID())\n\t\tfor _, cachedChildBranchReference := range cachedChildBranchReferences {\n\t\t\t// unwrap ChildBranch reference\n\t\t\tchildBranchReference := cachedChildBranchReference.Unwrap()\n\t\t\tif childBranchReference == nil {\n\t\t\t\tcurrentCachedBranch.Release()\n\t\t\t\tcachedChildBranchReferences.Release()\n\t\t\t\terr = errors.Errorf(\"failed to load ChildBranch reference: %w\", cerrors.ErrFatal)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// queue child Branch for propagation\n\t\t\tbranchStack.PushBack(childBranchReference.ChildBranchID())\n\t\t}\n\t\tcachedChildBranchReferences.Release()\n\n\t\t// release current CachedBranch\n\t\tcurrentCachedBranch.Release()\n\t}\n\n\treturn\n}", "func (r *RBAC) UpdateWhiteList(system, uid string, whitelist ...string) error {\n\tr.Cache.RemoveUser(system, uid)\n\treturn r.User.UpdateWhiteList(system, uid, whitelist...)\n}" ]
[ "0.6461851", "0.6423092", "0.6416864", "0.63546205", "0.61288905", "0.5720693", "0.5681801", "0.53321487", "0.5272768", "0.48651224", "0.4766242", "0.47318128", "0.45781916", "0.45240498", "0.45019257", "0.4427853", "0.4406283", "0.4384094", "0.43788534", "0.4349381", "0.43306437", "0.42248893", "0.42192593", "0.41811898", "0.41733363", "0.41718102", "0.417088", "0.41558424", "0.41506955", "0.41321653", "0.41203552", "0.41159227", "0.41019717", "0.40998563", "0.40937644", "0.40817487", "0.4080539", "0.4060079", "0.4054799", "0.4052626", "0.40225667", "0.40176925", "0.40074202", "0.399842", "0.39811942", "0.39528945", "0.3928695", "0.39006966", "0.38763925", "0.38722143", "0.38699263", "0.38648373", "0.38373187", "0.38314694", "0.38301647", "0.38275024", "0.38209575", "0.38156772", "0.38138902", "0.38106024", "0.3799447", "0.37932268", "0.3788386", "0.37852642", "0.3778877", "0.37767273", "0.37735566", "0.37731063", "0.37706372", "0.37658823", "0.37622204", "0.37590364", "0.3752378", "0.3747476", "0.37431014", "0.3736712", "0.3735243", "0.37256756", "0.37224832", "0.37195218", "0.3717617", "0.37172323", "0.37145248", "0.37094778", "0.37057728", "0.3691134", "0.368982", "0.3688388", "0.36744207", "0.36706236", "0.3670572", "0.3665798", "0.36581868", "0.36563718", "0.3652379", "0.36516804", "0.36483437", "0.36480847", "0.36432683", "0.36404896" ]
0.758683
0
GetProtectBranchesByRepoID returns a list of ProtectBranch in given repository.
GetProtectBranchesByRepoID возвращает список ProtectBranch в заданном репозитории.
func GetProtectBranchesByRepoID(repoID int64) ([]*ProtectBranch, error) { protectBranches := make([]*ProtectBranch, 0, 2) return protectBranches, x.Where("repo_id = ? and protected = ?", repoID, true).Asc("name").Find(&protectBranches) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *client) GetBranches(org, repo string, onlyProtected bool) ([]Branch, error) {\n\tdurationLogger := c.log(\"GetBranches\", org, repo, onlyProtected)\n\tdefer durationLogger()\n\n\tvar branches []Branch\n\terr := c.readPaginatedResultsWithValues(\n\t\tfmt.Sprintf(\"/repos/%s/%s/branches\", org, repo),\n\t\turl.Values{\n\t\t\t\"protected\": []string{strconv.FormatBool(onlyProtected)},\n\t\t\t\"per_page\": []string{\"100\"},\n\t\t},\n\t\tacceptNone,\n\t\torg,\n\t\tfunc() interface{} { // newObj\n\t\t\treturn &[]Branch{}\n\t\t},\n\t\tfunc(obj interface{}) {\n\t\t\tbranches = append(branches, *(obj.(*[]Branch))...)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn branches, nil\n}", "func (r *SettingRepository) GetBranchesByOrgID(orgID string) []models.Branch {\n\tvar branches []models.Branch\n\torgid := bson.ObjectIdHex(orgID)\n\titer := r.C.Find(bson.M{\"orgid\": orgid}).Iter()\n\tresult := models.Branch{}\n\tfor iter.Next(&result) {\n\t\tbranches = append(branches, result)\n\t}\n\treturn branches\n}", "func ListBranchProtections(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/branch_protections repository repoListBranchProtection\n\t// ---\n\t// summary: List branch protections for a repository\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// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/BranchProtectionList\"\n\n\trepo := ctx.Repo.Repository\n\tbps, err := git_model.FindRepoProtectedBranchRules(ctx, repo.ID)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranches\", err)\n\t\treturn\n\t}\n\tapiBps := make([]*api.BranchProtection, len(bps))\n\tfor i := range bps {\n\t\tapiBps[i] = convert.ToBranchProtection(bps[i])\n\t}\n\n\tctx.JSON(http.StatusOK, apiBps)\n}", "func (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) {\n\tbranches := make([]*Branch, 0, 10)\n\treturn branches, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/repos/%s/%s/branches\", user, repo), nil, nil, &branches)\n}", "func GetBranches(repo *models.Repository, skip, limit int) ([]*git.Branch, int, error) {\n\treturn git.GetBranchesByPath(repo.RepoPath(), skip, limit)\n}", "func (g *GitLab) Branches(ctx context.Context, user *model.User, repo *model.Repo, p *model.ListOptions) ([]string, error) {\n\ttoken := common.UserToken(ctx, repo, user)\n\tclient, err := newClient(g.url, token, g.SkipVerify)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_repo, err := g.getProject(ctx, client, repo.Owner, repo.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgitlabBranches, _, err := client.Branches.ListBranches(_repo.ID,\n\t\t&gitlab.ListBranchesOptions{ListOptions: gitlab.ListOptions{Page: p.Page, PerPage: p.PerPage}},\n\t\tgitlab.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbranches := make([]string, 0)\n\tfor _, branch := range gitlabBranches {\n\t\tbranches = append(branches, branch.Name)\n\t}\n\treturn branches, nil\n}", "func handleRepo(ctx context.Context, client *github.Client, repo *github.Repository) error {\n\topt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tbranches, resp, err := client.Repositories.ListBranches(ctx, *repo.Owner.Login, *repo.Name, opt)\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, branch := range branches {\n\t\tif branch.GetName() == \"master\" && in(orgs, *repo.Owner.Login) {\n\t\t\t// we must get the individual branch for the branch protection to work\n\t\t\tb, _, err := client.Repositories.GetBranch(ctx, *repo.Owner.Login, *repo.Name, branch.GetName())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// return early if it is already protected\n\t\t\tif b.GetProtected() {\n\t\t\t\tfmt.Printf(\"[OK] %s:%s is already protected\\n\", *repo.FullName, b.GetName())\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfmt.Printf(\"[UPDATE] %s:%s will be changed to protected\\n\", *repo.FullName, b.GetName())\n\t\t\tif dryrun {\n\t\t\t\t// return early\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// set the branch to be protected\n\t\t\tif _, _, err := client.Repositories.UpdateBranchProtection(ctx, *repo.Owner.Login, *repo.Name, b.GetName(), &github.ProtectionRequest{\n\t\t\t\tRequiredStatusChecks: &github.RequiredStatusChecks{\n\t\t\t\t\tStrict: false,\n\t\t\t\t\tContexts: []string{},\n\t\t\t\t},\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetBranches(token, owner, repo string) ([]*github.Branch, error) {\n\tclient, ctx := getOauthClient(token)\n\tres, _, err := client.Repositories.ListBranches(ctx, owner, repo, nil)\n\tif res == nil || err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func GetBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/branch_protections/{name} repository repoGetBranchProtection\n\t// ---\n\t// summary: Get a specific branch protection for the repository\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, convert.ToBranchProtection(bp))\n}", "func (client *Client) Branches(issueID, repositoryType string) (branches []*Branch, err error) {\n\tpath := fmt.Sprintf(\"/rest/dev-status/latest/issue/detail?issueId=%s&applicationType=%s&dataType=branch\", issueID, repositoryType)\n\tres, err := client.getRequest(path, http.StatusOK)\n\tif err != nil {\n\t\treturn []*Branch{}, fmt.Errorf(\"Branches failed request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tvar result DevStatus\n\tbodyBytes, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn []*Branch{}, fmt.Errorf(\"Branches failed to read response body %w\", err)\n\t}\n\n\tif err := json.Unmarshal(bodyBytes, &result); err != nil {\n\t\treturn []*Branch{}, fmt.Errorf(\"Branches failed unmarshal response body: %w\", err)\n\t}\n\n\tif len(result.Errors) > 0 {\n\t\treturn []*Branch{}, fmt.Errorf(\"Branches found unexpected errors: %s\", result.Errors)\n\t}\n\tbranches = make([]*Branch, 0)\n\tfor _, detail := range result.Details {\n\t\tbranches = append(branches, detail.Branches...)\n\t}\n\treturn branches, nil\n}", "func (server *RepositoriesService) ListBranches(ctx context.Context, project string, repo string, opt *ListOpts) (*Branches, *http.Response, error) {\n\tu := fmt.Sprintf(\"rest/api/1.0/projects/%s/repos/%s/branches\", project, repo)\n\treq, err := server.v1Client.NewRequest(http.MethodGet, u, nil, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvar branches Branches\n\tresp, err := server.v1Client.Do(req, &branches)\n\tlog.Infof(\"branch: %+v, error: %+v\", branches, err)\n\treturn &branches, resp, err\n}", "func (m *MockRepositoryClient) GetBranches(org, repo string, onlyProtected bool) ([]github.Branch, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetBranches\", org, repo, onlyProtected)\n\tret0, _ := ret[0].([]github.Branch)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func ListBranches(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/branches repository repoListBranches\n\t// ---\n\t// summary: List a repository's branches\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: 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/BranchList\"\n\n\tvar totalNumOfBranches int64\n\tvar apiBranches []*api.Branch\n\n\tlistOptions := utils.GetListOptions(ctx)\n\n\tif !ctx.Repo.Repository.IsEmpty {\n\t\tif ctx.Repo.GitRepo == nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"Load git repository failed\", nil)\n\t\t\treturn\n\t\t}\n\n\t\tbranchOpts := git_model.FindBranchOptions{\n\t\t\tListOptions: listOptions,\n\t\t\tRepoID: ctx.Repo.Repository.ID,\n\t\t\tIsDeletedBranch: util.OptionalBoolFalse,\n\t\t}\n\t\tvar err error\n\t\ttotalNumOfBranches, err = git_model.CountBranches(ctx, branchOpts)\n\t\tif err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"CountBranches\", err)\n\t\t\treturn\n\t\t}\n\t\tif totalNumOfBranches == 0 { // sync branches immediately because non-empty repository should have at least 1 branch\n\t\t\ttotalNumOfBranches, err = repo_module.SyncRepoBranches(ctx, ctx.Repo.Repository.ID, 0)\n\t\t\tif err != nil {\n\t\t\t\tctx.ServerError(\"SyncRepoBranches\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\trules, err := git_model.FindRepoProtectedBranchRules(ctx, ctx.Repo.Repository.ID)\n\t\tif err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"FindMatchedProtectedBranchRules\", err)\n\t\t\treturn\n\t\t}\n\n\t\tbranches, err := git_model.FindBranches(ctx, branchOpts)\n\t\tif err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetBranches\", err)\n\t\t\treturn\n\t\t}\n\n\t\tapiBranches = make([]*api.Branch, 0, len(branches))\n\t\tfor i := range branches {\n\t\t\tc, err := ctx.Repo.GitRepo.GetBranchCommit(branches[i].Name)\n\t\t\tif err != nil {\n\t\t\t\t// Skip if this branch doesn't exist anymore.\n\t\t\t\tif git.IsErrNotExist(err) {\n\t\t\t\t\ttotalNumOfBranches--\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetCommit\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbranchProtection := rules.GetFirstMatched(branches[i].Name)\n\t\t\tapiBranch, err := convert.ToBranch(ctx, ctx.Repo.Repository, branches[i].Name, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())\n\t\t\tif err != nil {\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"convert.ToBranch\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tapiBranches = append(apiBranches, apiBranch)\n\t\t}\n\t}\n\n\tctx.SetLinkHeader(int(totalNumOfBranches), listOptions.PageSize)\n\tctx.SetTotalCountHeader(totalNumOfBranches)\n\tctx.JSON(http.StatusOK, apiBranches)\n}", "func (m *MockClient) GetBranches(org, repo string, onlyProtected bool) ([]github.Branch, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetBranches\", org, repo, onlyProtected)\n\tret0, _ := ret[0].([]github.Branch)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetBranches(db *sqlx.DB) ([]Branch, error) {\n\n\tobjects := []Branch{}\n\n\terr := db.Select(&objects, \"SELECT * FROM branches\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn objects, nil\n}", "func GetBranches() []string {\n\treturn branches\n}", "func GetProtectBranchOfRepoByName(repoID int64, name string) (*ProtectBranch, error) {\n\tprotectBranch := &ProtectBranch{\n\t\tRepoID: repoID,\n\t\tName: name,\n\t}\n\thas, err := x.Get(protectBranch)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, ErrBranchNotExist{args: map[string]any{\"name\": name}}\n\t}\n\treturn protectBranch, nil\n}", "func (g *Gitlab) ListBranches(scm *api.SCMConfig, repo string) ([]string, error) {\n\tclient, err := newGitlabClient(scm.Server, scm.Username, scm.Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbranches, _, err := client.Branches.ListBranches(repo)\n\tif err != nil {\n\t\tlog.Errorf(\"Fail to list branches for %s\", repo)\n\t\treturn nil, err\n\t}\n\n\tbranchNames := make([]string, len(branches))\n\tfor i, branch := range branches {\n\t\tbranchNames[i] = branch.Name\n\t}\n\n\treturn branchNames, nil\n}", "func (r *repoImpl) getFilteredBranches(ctx context.Context) ([]*git.Branch, error) {\n\tgitilesBranches, err := r.gitiles.Branches(ctx)\n\tif err != nil {\n\t\treturn nil, skerr.Wrap(err)\n\t}\n\t// Filter by includeBranches.\n\tnumBranches := len(gitilesBranches)\n\tif len(r.includeBranches) > 0 {\n\t\tnumBranches = len(r.includeBranches)\n\t}\n\tbranches := make([]*git.Branch, 0, numBranches)\n\tfor _, branch := range gitilesBranches {\n\t\tif (len(r.includeBranches) == 0 || util.In(branch.Name, r.includeBranches)) && (len(r.excludeBranches) == 0 || !util.In(branch.Name, r.excludeBranches)) {\n\t\t\tbranches = append(branches, branch)\n\t\t}\n\t}\n\treturn branches, nil\n}", "func (g *V3) ListBranches(repo string) ([]string, error) {\n\tbranches, resp, err := g.client.Branches.ListBranches(repo)\n\tif err != nil {\n\t\tlog.Errorf(\"Fail to list branches for %s\", repo)\n\t\treturn nil, convertGitlabError(err, resp)\n\t}\n\n\tbranchNames := make([]string, len(branches))\n\tfor i, branch := range branches {\n\t\tbranchNames[i] = branch.Name\n\t}\n\n\treturn branchNames, nil\n}", "func GetBranches(dbOwner, dbFolder, dbName string) (branches map[string]BranchEntry, err error) {\n\tdbQuery := `\n\t\tSELECT db.branch_heads\n\t\tFROM sqlite_databases AS db\n\t\tWHERE db.user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t)\n\t\t\tAND db.folder = $2\n\t\t\tAND db.db_name = $3`\n\terr = pdb.QueryRow(dbQuery, dbOwner, dbFolder, dbName).Scan(&branches)\n\tif err != nil {\n\t\tlog.Printf(\"Error when retrieving branch heads for database '%s%s%s': %v\\n\", dbOwner, dbFolder, dbName,\n\t\t\terr)\n\t\treturn nil, err\n\t}\n\treturn branches, nil\n}", "func Branches(etcdClient *etcd.Client, etcdPrefix string, repo string) col.Collection {\n\treturn col.NewCollection(\n\t\tetcdClient,\n\t\tpath.Join(etcdPrefix, branchesPrefix, repo),\n\t\tnil,\n\t\t&pfs.BranchInfo{},\n\t\tfunc(key string) error {\n\t\t\tif uuid.IsUUIDWithoutDashes(key) {\n\t\t\t\treturn fmt.Errorf(\"branch name cannot be a UUID V4\")\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tnil,\n\t)\n}", "func (handler *InitHandler) handleBranches(c Community, r Repository) error {\n\t// if the branches are defined in the repositories, it means that\n\t// all the branches defined in the community will not inherited by repositories\n\tmapBranches := make(map[string]string)\n\n\tif len(r.ProtectedBranches) > 0 {\n\t\t// using repository branches\n\t\tglog.Infof(\"using repository branches: %s\", *r.Name)\n\t\tfor _, b := range r.ProtectedBranches {\n\t\t\tmapBranches[b] = b\n\t\t}\n\t} else {\n\t\t// using community branches\n\t\tglog.Infof(\"using community branches: %s\", *r.Name)\n\t\tfor _, b := range c.ProtectedBranches {\n\t\t\tmapBranches[b] = b\n\t\t}\n\t}\n\n\t// get branches from DB\n\tvar bs []database.Branches\n\terr := database.DBConnection.Model(&database.Branches{}).\n\t\tWhere(\"owner = ? and repo = ?\", c.Name, r.Name).Find(&bs).Error\n\tif err != nil {\n\t\tglog.Errorf(\"unable to get branches: %v\", err)\n\t\treturn err\n\t}\n\tmapBranchesInDB := make(map[string]string)\n\tfor _, b := range bs {\n\t\tmapBranchesInDB[b.Name] = strconv.Itoa(int(b.ID))\n\t}\n\n\t// un-protected branches\n\terr = handler.removeBranchProtections(c, r, mapBranches, mapBranchesInDB)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to un-protected branches: %v\", err)\n\t}\n\n\t// protected branches\n\terr = handler.addBranchProtections(c, r, mapBranches, mapBranchesInDB)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to protected branches: %v\", err)\n\t}\n\n\treturn nil\n}", "func CreateBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation POST /repos/{owner}/{repo}/branch_protections repository repoCreateBranchProtection\n\t// ---\n\t// summary: Create a branch protections for a repository\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: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/CreateBranchProtectionOption\"\n\t// responses:\n\t// \"201\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"403\":\n\t// \"$ref\": \"#/responses/forbidden\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\t// \"422\":\n\t// \"$ref\": \"#/responses/validationError\"\n\n\tform := web.GetForm(ctx).(*api.CreateBranchProtectionOption)\n\trepo := ctx.Repo.Repository\n\n\truleName := form.RuleName\n\tif ruleName == \"\" {\n\t\truleName = form.BranchName //nolint\n\t}\n\tif len(ruleName) == 0 {\n\t\tctx.Error(http.StatusBadRequest, \"both rule_name and branch_name are empty\", \"both rule_name and branch_name are empty\")\n\t\treturn\n\t}\n\n\tisPlainRule := !git_model.IsRuleNameSpecial(ruleName)\n\tvar isBranchExist bool\n\tif isPlainRule {\n\t\tisBranchExist = git.IsBranchExist(ctx.Req.Context(), ctx.Repo.Repository.RepoPath(), ruleName)\n\t}\n\n\tprotectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, ruleName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectBranchOfRepoByName\", err)\n\t\treturn\n\t} else if protectBranch != nil {\n\t\tctx.Error(http.StatusForbidden, \"Create branch protection\", \"Branch protection already exist\")\n\t\treturn\n\t}\n\n\tvar requiredApprovals int64\n\tif form.RequiredApprovals > 0 {\n\t\trequiredApprovals = form.RequiredApprovals\n\t}\n\n\twhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tmergeWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tapprovalsWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\treturn\n\t\t}\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\treturn\n\t}\n\tvar whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64\n\tif repo.Owner.IsOrganization() {\n\t\twhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t\tmergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t\tapprovalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)\n\t\tif err != nil {\n\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tprotectBranch = &git_model.ProtectedBranch{\n\t\tRepoID: ctx.Repo.Repository.ID,\n\t\tRuleName: ruleName,\n\t\tCanPush: form.EnablePush,\n\t\tEnableWhitelist: form.EnablePush && form.EnablePushWhitelist,\n\t\tEnableMergeWhitelist: form.EnableMergeWhitelist,\n\t\tWhitelistDeployKeys: form.EnablePush && form.EnablePushWhitelist && form.PushWhitelistDeployKeys,\n\t\tEnableStatusCheck: form.EnableStatusCheck,\n\t\tStatusCheckContexts: form.StatusCheckContexts,\n\t\tEnableApprovalsWhitelist: form.EnableApprovalsWhitelist,\n\t\tRequiredApprovals: requiredApprovals,\n\t\tBlockOnRejectedReviews: form.BlockOnRejectedReviews,\n\t\tBlockOnOfficialReviewRequests: form.BlockOnOfficialReviewRequests,\n\t\tDismissStaleApprovals: form.DismissStaleApprovals,\n\t\tRequireSignedCommits: form.RequireSignedCommits,\n\t\tProtectedFilePatterns: form.ProtectedFilePatterns,\n\t\tUnprotectedFilePatterns: form.UnprotectedFilePatterns,\n\t\tBlockOnOutdatedBranch: form.BlockOnOutdatedBranch,\n\t}\n\n\terr = git_model.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, git_model.WhitelistOptions{\n\t\tUserIDs: whitelistUsers,\n\t\tTeamIDs: whitelistTeams,\n\t\tMergeUserIDs: mergeWhitelistUsers,\n\t\tMergeTeamIDs: mergeWhitelistTeams,\n\t\tApprovalsUserIDs: approvalsWhitelistUsers,\n\t\tApprovalsTeamIDs: approvalsWhitelistTeams,\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"UpdateProtectBranch\", err)\n\t\treturn\n\t}\n\n\tif isBranchExist {\n\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, ruleName); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPRsForBaseBranch\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !isPlainRule {\n\t\t\tif ctx.Repo.GitRepo == nil {\n\t\t\t\tctx.Repo.GitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.RepoPath())\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"OpenRepository\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer func() {\n\t\t\t\t\tctx.Repo.GitRepo.Close()\n\t\t\t\t\tctx.Repo.GitRepo = nil\n\t\t\t\t}()\n\t\t\t}\n\t\t\t// FIXME: since we only need to recheck files protected rules, we could improve this\n\t\t\tmatchedBranches, err := git_model.FindAllMatchedBranches(ctx, ctx.Repo.Repository.ID, ruleName)\n\t\t\tif err != nil {\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"FindAllMatchedBranches\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, branchName := range matchedBranches {\n\t\t\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, branchName); err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPRsForBaseBranch\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reload from db to get all whitelists\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, ctx.Repo.Repository.ID, ruleName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != ctx.Repo.Repository.ID {\n\t\tctx.Error(http.StatusInternalServerError, \"New branch protection not found\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusCreated, convert.ToBranchProtection(bp))\n}", "func (repo *HelmRepoRepository) ListHelmReposByProjectID(\n\tprojectID uint,\n) ([]*models.HelmRepo, error) {\n\thrs := []*models.HelmRepo{}\n\n\tif err := repo.db.Preload(\"TokenCache\").Where(\"project_id = ?\", projectID).Find(&hrs).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, hr := range hrs {\n\t\trepo.DecryptHelmRepoData(hr, repo.key)\n\t}\n\n\treturn hrs, nil\n}", "func (c *client) GetBranchProtection(org, repo, branch string) (*BranchProtection, error) {\n\tdurationLogger := c.log(\"GetBranchProtection\", org, repo, branch)\n\tdefer durationLogger()\n\n\tcode, body, err := c.requestRaw(&request{\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/branches/%s/protection\", org, repo, branch),\n\t\torg: org,\n\t\t// GitHub returns 404 for this call if either:\n\t\t// - The branch is not protected\n\t\t// - The access token used does not have sufficient privileges\n\t\t// We therefore need to introspect the response body.\n\t\texitCodes: []int{200, 404},\n\t})\n\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase code == 200:\n\t\tvar bp BranchProtection\n\t\tif err := json.Unmarshal(body, &bp); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &bp, nil\n\tcase code == 404:\n\t\t// continue\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected status code: %d\", code)\n\t}\n\n\tvar ge githubError\n\tif err := json.Unmarshal(body, &ge); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the error was because the branch is not protected, we return a\n\t// nil pointer to indicate this.\n\tif ge.Message == \"Branch not protected\" {\n\t\treturn nil, nil\n\t}\n\n\t// Otherwise we got some other 404 error.\n\treturn nil, fmt.Errorf(\"getting branch protection 404: %s\", ge.Message)\n}", "func (a *RepoAPI) getBranches(params interface{}) (resp *rpc.Response) {\n\tm := objx.New(cast.ToStringMap(params))\n\treturn rpc.Success(util.Map{\"branches\": a.mods.Repo.GetBranches(m.Get(\"name\").Str())})\n}", "func FindCommitsByRepoID(ctx context.Context, db DB, value string) ([]*Commit, error) {\n\tq := \"SELECT `commit`.`id`,`commit`.`checksum`,`commit`.`repo_id`,`commit`.`sha`,`commit`.`branch`,`commit`.`message`,`commit`.`mergecommit`,`commit`.`excluded`,`commit`.`parent`,`commit`.`parent_id`,`commit`.`date`,`commit`.`author_user_id`,`commit`.`committer_user_id`,`commit`.`ordinal`,`commit`.`customer_id`,`commit`.`ref_type`,`commit`.`ref_id`,`commit`.`metadata` FROM `commit` WHERE `repo_id` = ? LIMIT 1\"\n\trows, err := db.QueryContext(ctx, q, orm.ToSQLString(value))\n\tif err == sql.ErrNoRows {\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tresults := make([]*Commit, 0)\n\tfor rows.Next() {\n\t\tvar _ID sql.NullString\n\t\tvar _Checksum sql.NullString\n\t\tvar _RepoID sql.NullString\n\t\tvar _Sha sql.NullString\n\t\tvar _Branch sql.NullString\n\t\tvar _Message sql.NullString\n\t\tvar _Mergecommit sql.NullBool\n\t\tvar _Excluded sql.NullBool\n\t\tvar _Parent sql.NullString\n\t\tvar _ParentID sql.NullString\n\t\tvar _Date sql.NullInt64\n\t\tvar _AuthorUserID sql.NullString\n\t\tvar _CommitterUserID sql.NullString\n\t\tvar _Ordinal sql.NullInt64\n\t\tvar _CustomerID sql.NullString\n\t\tvar _RefType sql.NullString\n\t\tvar _RefID sql.NullString\n\t\tvar _Metadata sql.NullString\n\t\terr := rows.Scan(\n\t\t\t&_ID,\n\t\t\t&_Checksum,\n\t\t\t&_RepoID,\n\t\t\t&_Sha,\n\t\t\t&_Branch,\n\t\t\t&_Message,\n\t\t\t&_Mergecommit,\n\t\t\t&_Excluded,\n\t\t\t&_Parent,\n\t\t\t&_ParentID,\n\t\t\t&_Date,\n\t\t\t&_AuthorUserID,\n\t\t\t&_CommitterUserID,\n\t\t\t&_Ordinal,\n\t\t\t&_CustomerID,\n\t\t\t&_RefType,\n\t\t\t&_RefID,\n\t\t\t&_Metadata,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt := &Commit{}\n\t\tif _ID.Valid {\n\t\t\tt.SetID(_ID.String)\n\t\t}\n\t\tif _Checksum.Valid {\n\t\t\tt.SetChecksum(_Checksum.String)\n\t\t}\n\t\tif _RepoID.Valid {\n\t\t\tt.SetRepoID(_RepoID.String)\n\t\t}\n\t\tif _Sha.Valid {\n\t\t\tt.SetSha(_Sha.String)\n\t\t}\n\t\tif _Branch.Valid {\n\t\t\tt.SetBranch(_Branch.String)\n\t\t}\n\t\tif _Message.Valid {\n\t\t\tt.SetMessage(_Message.String)\n\t\t}\n\t\tif _Mergecommit.Valid {\n\t\t\tt.SetMergecommit(_Mergecommit.Bool)\n\t\t}\n\t\tif _Excluded.Valid {\n\t\t\tt.SetExcluded(_Excluded.Bool)\n\t\t}\n\t\tif _Parent.Valid {\n\t\t\tt.SetParent(_Parent.String)\n\t\t}\n\t\tif _ParentID.Valid {\n\t\t\tt.SetParentID(_ParentID.String)\n\t\t}\n\t\tif _Date.Valid {\n\t\t\tt.SetDate(_Date.Int64)\n\t\t}\n\t\tif _AuthorUserID.Valid {\n\t\t\tt.SetAuthorUserID(_AuthorUserID.String)\n\t\t}\n\t\tif _CommitterUserID.Valid {\n\t\t\tt.SetCommitterUserID(_CommitterUserID.String)\n\t\t}\n\t\tif _Ordinal.Valid {\n\t\t\tt.SetOrdinal(int32(_Ordinal.Int64))\n\t\t}\n\t\tif _CustomerID.Valid {\n\t\t\tt.SetCustomerID(_CustomerID.String)\n\t\t}\n\t\tif _RefType.Valid {\n\t\t\tt.SetRefType(_RefType.String)\n\t\t}\n\t\tif _RefID.Valid {\n\t\t\tt.SetRefID(_RefID.String)\n\t\t}\n\t\tif _Metadata.Valid {\n\t\t\tt.SetMetadata(_Metadata.String)\n\t\t}\n\t\tresults = append(results, t)\n\t}\n\treturn results, nil\n}", "func (c APIClient) ListBranch(repoName string) ([]*pfs.BranchInfo, error) {\n\tbranchInfos, err := c.PfsAPIClient.ListBranch(\n\t\tc.Ctx(),\n\t\t&pfs.ListBranchRequest{\n\t\t\tRepo: NewRepo(repoName),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, grpcutil.ScrubGRPC(err)\n\t}\n\treturn branchInfos.BranchInfo, nil\n}", "func d4getBranches(node *d4nodeT, branch *d4branchT, parVars *d4partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d4maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d4maxNodes] = *branch\n\tparVars.branchCount = d4maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d4maxNodes+1; index++ {\n\t\tparVars.coverSplit = d4combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d4calcRectVolume(&parVars.coverSplit)\n}", "func FindCommitsByRepoIDTx(ctx context.Context, tx Tx, value string) ([]*Commit, error) {\n\tq := \"SELECT `commit`.`id`,`commit`.`checksum`,`commit`.`repo_id`,`commit`.`sha`,`commit`.`branch`,`commit`.`message`,`commit`.`mergecommit`,`commit`.`excluded`,`commit`.`parent`,`commit`.`parent_id`,`commit`.`date`,`commit`.`author_user_id`,`commit`.`committer_user_id`,`commit`.`ordinal`,`commit`.`customer_id`,`commit`.`ref_type`,`commit`.`ref_id`,`commit`.`metadata` FROM `commit` WHERE `repo_id` = ? LIMIT 1\"\n\trows, err := tx.QueryContext(ctx, q, orm.ToSQLString(value))\n\tif err == sql.ErrNoRows {\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tresults := make([]*Commit, 0)\n\tfor rows.Next() {\n\t\tvar _ID sql.NullString\n\t\tvar _Checksum sql.NullString\n\t\tvar _RepoID sql.NullString\n\t\tvar _Sha sql.NullString\n\t\tvar _Branch sql.NullString\n\t\tvar _Message sql.NullString\n\t\tvar _Mergecommit sql.NullBool\n\t\tvar _Excluded sql.NullBool\n\t\tvar _Parent sql.NullString\n\t\tvar _ParentID sql.NullString\n\t\tvar _Date sql.NullInt64\n\t\tvar _AuthorUserID sql.NullString\n\t\tvar _CommitterUserID sql.NullString\n\t\tvar _Ordinal sql.NullInt64\n\t\tvar _CustomerID sql.NullString\n\t\tvar _RefType sql.NullString\n\t\tvar _RefID sql.NullString\n\t\tvar _Metadata sql.NullString\n\t\terr := rows.Scan(\n\t\t\t&_ID,\n\t\t\t&_Checksum,\n\t\t\t&_RepoID,\n\t\t\t&_Sha,\n\t\t\t&_Branch,\n\t\t\t&_Message,\n\t\t\t&_Mergecommit,\n\t\t\t&_Excluded,\n\t\t\t&_Parent,\n\t\t\t&_ParentID,\n\t\t\t&_Date,\n\t\t\t&_AuthorUserID,\n\t\t\t&_CommitterUserID,\n\t\t\t&_Ordinal,\n\t\t\t&_CustomerID,\n\t\t\t&_RefType,\n\t\t\t&_RefID,\n\t\t\t&_Metadata,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt := &Commit{}\n\t\tif _ID.Valid {\n\t\t\tt.SetID(_ID.String)\n\t\t}\n\t\tif _Checksum.Valid {\n\t\t\tt.SetChecksum(_Checksum.String)\n\t\t}\n\t\tif _RepoID.Valid {\n\t\t\tt.SetRepoID(_RepoID.String)\n\t\t}\n\t\tif _Sha.Valid {\n\t\t\tt.SetSha(_Sha.String)\n\t\t}\n\t\tif _Branch.Valid {\n\t\t\tt.SetBranch(_Branch.String)\n\t\t}\n\t\tif _Message.Valid {\n\t\t\tt.SetMessage(_Message.String)\n\t\t}\n\t\tif _Mergecommit.Valid {\n\t\t\tt.SetMergecommit(_Mergecommit.Bool)\n\t\t}\n\t\tif _Excluded.Valid {\n\t\t\tt.SetExcluded(_Excluded.Bool)\n\t\t}\n\t\tif _Parent.Valid {\n\t\t\tt.SetParent(_Parent.String)\n\t\t}\n\t\tif _ParentID.Valid {\n\t\t\tt.SetParentID(_ParentID.String)\n\t\t}\n\t\tif _Date.Valid {\n\t\t\tt.SetDate(_Date.Int64)\n\t\t}\n\t\tif _AuthorUserID.Valid {\n\t\t\tt.SetAuthorUserID(_AuthorUserID.String)\n\t\t}\n\t\tif _CommitterUserID.Valid {\n\t\t\tt.SetCommitterUserID(_CommitterUserID.String)\n\t\t}\n\t\tif _Ordinal.Valid {\n\t\t\tt.SetOrdinal(int32(_Ordinal.Int64))\n\t\t}\n\t\tif _CustomerID.Valid {\n\t\t\tt.SetCustomerID(_CustomerID.String)\n\t\t}\n\t\tif _RefType.Valid {\n\t\t\tt.SetRefType(_RefType.String)\n\t\t}\n\t\tif _RefID.Valid {\n\t\t\tt.SetRefID(_RefID.String)\n\t\t}\n\t\tif _Metadata.Valid {\n\t\t\tt.SetMetadata(_Metadata.String)\n\t\t}\n\t\tresults = append(results, t)\n\t}\n\treturn results, nil\n}", "func d12getBranches(node *d12nodeT, branch *d12branchT, parVars *d12partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d12maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d12maxNodes] = *branch\n\tparVars.branchCount = d12maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d12maxNodes+1; index++ {\n\t\tparVars.coverSplit = d12combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d12calcRectVolume(&parVars.coverSplit)\n}", "func (r *Bitbucket) GetRepos(user *model.User) ([]*model.Repo, error) {\n\tvar repos []*model.Repo\n\tvar client = bitbucket.New(\n\t\tr.Client,\n\t\tr.Secret,\n\t\tuser.Access,\n\t\tuser.Secret,\n\t)\n\tvar list, err = client.Repos.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar remote = r.GetKind()\n\tvar hostname = r.GetHost()\n\n\tfor _, item := range list {\n\t\t// for now we only support git repos\n\t\tif item.Scm != \"git\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// these are the urls required to clone the repository\n\t\t// TODO use the bitbucketurl.Host and bitbucketurl.Scheme instead of hardcoding\n\t\t// so that we can support Stash.\n\t\tvar html = fmt.Sprintf(\"https://bitbucket.org/%s/%s\", item.Owner, item.Slug)\n\t\tvar clone = fmt.Sprintf(\"https://bitbucket.org/%s/%s.git\", item.Owner, item.Slug)\n\t\tvar ssh = fmt.Sprintf(\"git@bitbucket.org:%s/%s.git\", item.Owner, item.Slug)\n\n\t\tvar repo = model.Repo{\n\t\t\tUserID: user.ID,\n\t\t\tRemote: remote,\n\t\t\tHost: hostname,\n\t\t\tOwner: item.Owner,\n\t\t\tName: item.Slug,\n\t\t\tPrivate: item.Private,\n\t\t\tURL: html,\n\t\t\tCloneURL: clone,\n\t\t\tGitURL: clone,\n\t\t\tSSHURL: ssh,\n\t\t\tRole: &model.Perm{\n\t\t\t\tAdmin: true,\n\t\t\t\tWrite: true,\n\t\t\t\tRead: true,\n\t\t\t},\n\t\t}\n\n\t\tif repo.Private {\n\t\t\trepo.CloneURL = repo.SSHURL\n\t\t}\n\n\t\trepos = append(repos, &repo)\n\t}\n\n\treturn repos, err\n}", "func (app *App) HandleGetBranches(w http.ResponseWriter, r *http.Request) {\n\n\tclient, err := app.githubAppClientFromRequest(r)\n\n\tif err != nil {\n\t\tapp.handleErrorInternal(err, w)\n\t\treturn\n\t}\n\n\towner := chi.URLParam(r, \"owner\")\n\tname := chi.URLParam(r, \"name\")\n\n\t// List all branches for a specified repo\n\tallBranches, resp, err := client.Repositories.ListBranches(context.Background(), owner, name, &github.ListOptions{\n\t\tPerPage: 100,\n\t})\n\n\tif err != nil {\n\t\tapp.handleErrorInternal(err, w)\n\t\treturn\n\t}\n\n\t// make workers to get branches concurrently\n\tconst WCOUNT = 5\n\tnumPages := resp.LastPage + 1\n\tvar workerErr error\n\tvar mu sync.Mutex\n\tvar wg sync.WaitGroup\n\n\tworker := func(cp int) {\n\t\tdefer wg.Done()\n\n\t\tfor cp < numPages {\n\t\t\topts := &github.ListOptions{\n\t\t\t\tPage: cp,\n\t\t\t\tPerPage: 100,\n\t\t\t}\n\n\t\t\tbranches, _, err := client.Repositories.ListBranches(context.Background(), owner, name, opts)\n\n\t\t\tif err != nil {\n\t\t\t\tmu.Lock()\n\t\t\t\tworkerErr = err\n\t\t\t\tmu.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tallBranches = append(allBranches, branches...)\n\t\t\tmu.Unlock()\n\n\t\t\tcp += WCOUNT\n\t\t}\n\t}\n\n\tvar numJobs int\n\tif numPages > WCOUNT {\n\t\tnumJobs = WCOUNT\n\t} else {\n\t\tnumJobs = numPages\n\t}\n\n\twg.Add(numJobs)\n\n\t// page 1 is already loaded so we start with 2\n\tfor i := 1; i <= numJobs; i++ {\n\t\tgo worker(i + 1)\n\t}\n\n\twg.Wait()\n\n\tif workerErr != nil {\n\t\tapp.handleErrorInternal(workerErr, w)\n\t\treturn\n\t}\n\n\tres := make([]string, 0)\n\tfor _, b := range allBranches {\n\t\tres = append(res, b.GetName())\n\t}\n\n\tjson.NewEncoder(w).Encode(res)\n}", "func GetBranchProtection(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *BranchProtectionState, opts ...pulumi.ResourceOption) (*BranchProtection, error) {\n\tvar resource BranchProtection\n\terr := ctx.ReadResource(\"gitlab:index/branchProtection:BranchProtection\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (u *URL) SplitRepoPath() []string {\n\treturn strings.Split(u.RepoPath, \"/\")\n}", "func DeleteBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation DELETE /repos/{owner}/{repo}/branch_protections/{name} repository repoDeleteBranchProtection\n\t// ---\n\t// summary: Delete a specific branch protection for the repository\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// responses:\n\t// \"204\":\n\t// \"$ref\": \"#/responses/empty\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tif err := git_model.DeleteProtectedBranch(ctx, ctx.Repo.Repository.ID, bp.ID); err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"DeleteProtectedBranch\", err)\n\t\treturn\n\t}\n\n\tctx.Status(http.StatusNoContent)\n}", "func (c APIClient) ListCommitByRepo(repoName string) ([]*pfs.CommitInfo, error) {\n\treturn c.ListCommit(repoName, \"\", \"\", 0)\n}", "func EditBranchProtection(ctx *context.APIContext) {\n\t// swagger:operation PATCH /repos/{owner}/{repo}/branch_protections/{name} repository repoEditBranchProtection\n\t// ---\n\t// summary: Edit a branch protections for a repository. Only fields that are set will be changed\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: name\n\t// in: path\n\t// description: name of protected branch\n\t// type: string\n\t// required: true\n\t// - name: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/EditBranchProtectionOption\"\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/BranchProtection\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\t// \"422\":\n\t// \"$ref\": \"#/responses/validationError\"\n\tform := web.GetForm(ctx).(*api.EditBranchProtectionOption)\n\trepo := ctx.Repo.Repository\n\tbpName := ctx.Params(\":name\")\n\tprotectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchByID\", err)\n\t\treturn\n\t}\n\tif protectBranch == nil || protectBranch.RepoID != repo.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tif form.EnablePush != nil {\n\t\tif !*form.EnablePush {\n\t\t\tprotectBranch.CanPush = false\n\t\t\tprotectBranch.EnableWhitelist = false\n\t\t\tprotectBranch.WhitelistDeployKeys = false\n\t\t} else {\n\t\t\tprotectBranch.CanPush = true\n\t\t\tif form.EnablePushWhitelist != nil {\n\t\t\t\tif !*form.EnablePushWhitelist {\n\t\t\t\t\tprotectBranch.EnableWhitelist = false\n\t\t\t\t\tprotectBranch.WhitelistDeployKeys = false\n\t\t\t\t} else {\n\t\t\t\t\tprotectBranch.EnableWhitelist = true\n\t\t\t\t\tif form.PushWhitelistDeployKeys != nil {\n\t\t\t\t\t\tprotectBranch.WhitelistDeployKeys = *form.PushWhitelistDeployKeys\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif form.EnableMergeWhitelist != nil {\n\t\tprotectBranch.EnableMergeWhitelist = *form.EnableMergeWhitelist\n\t}\n\n\tif form.EnableStatusCheck != nil {\n\t\tprotectBranch.EnableStatusCheck = *form.EnableStatusCheck\n\t}\n\n\tif form.StatusCheckContexts != nil {\n\t\tprotectBranch.StatusCheckContexts = form.StatusCheckContexts\n\t}\n\n\tif form.RequiredApprovals != nil && *form.RequiredApprovals >= 0 {\n\t\tprotectBranch.RequiredApprovals = *form.RequiredApprovals\n\t}\n\n\tif form.EnableApprovalsWhitelist != nil {\n\t\tprotectBranch.EnableApprovalsWhitelist = *form.EnableApprovalsWhitelist\n\t}\n\n\tif form.BlockOnRejectedReviews != nil {\n\t\tprotectBranch.BlockOnRejectedReviews = *form.BlockOnRejectedReviews\n\t}\n\n\tif form.BlockOnOfficialReviewRequests != nil {\n\t\tprotectBranch.BlockOnOfficialReviewRequests = *form.BlockOnOfficialReviewRequests\n\t}\n\n\tif form.DismissStaleApprovals != nil {\n\t\tprotectBranch.DismissStaleApprovals = *form.DismissStaleApprovals\n\t}\n\n\tif form.RequireSignedCommits != nil {\n\t\tprotectBranch.RequireSignedCommits = *form.RequireSignedCommits\n\t}\n\n\tif form.ProtectedFilePatterns != nil {\n\t\tprotectBranch.ProtectedFilePatterns = *form.ProtectedFilePatterns\n\t}\n\n\tif form.UnprotectedFilePatterns != nil {\n\t\tprotectBranch.UnprotectedFilePatterns = *form.UnprotectedFilePatterns\n\t}\n\n\tif form.BlockOnOutdatedBranch != nil {\n\t\tprotectBranch.BlockOnOutdatedBranch = *form.BlockOnOutdatedBranch\n\t}\n\n\tvar whitelistUsers []int64\n\tif form.PushWhitelistUsernames != nil {\n\t\twhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\twhitelistUsers = protectBranch.WhitelistUserIDs\n\t}\n\tvar mergeWhitelistUsers []int64\n\tif form.MergeWhitelistUsernames != nil {\n\t\tmergeWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tmergeWhitelistUsers = protectBranch.MergeWhitelistUserIDs\n\t}\n\tvar approvalsWhitelistUsers []int64\n\tif form.ApprovalsWhitelistUsernames != nil {\n\t\tapprovalsWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"User does not exist\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetUserIDsByNames\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tapprovalsWhitelistUsers = protectBranch.ApprovalsWhitelistUserIDs\n\t}\n\n\tvar whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64\n\tif repo.Owner.IsOrganization() {\n\t\tif form.PushWhitelistTeams != nil {\n\t\t\twhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\twhitelistTeams = protectBranch.WhitelistTeamIDs\n\t\t}\n\t\tif form.MergeWhitelistTeams != nil {\n\t\t\tmergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tmergeWhitelistTeams = protectBranch.MergeWhitelistTeamIDs\n\t\t}\n\t\tif form.ApprovalsWhitelistTeams != nil {\n\t\t\tapprovalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)\n\t\t\tif err != nil {\n\t\t\t\tif organization.IsErrTeamNotExist(err) {\n\t\t\t\t\tctx.Error(http.StatusUnprocessableEntity, \"Team does not exist\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"GetTeamIDsByNames\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tapprovalsWhitelistTeams = protectBranch.ApprovalsWhitelistTeamIDs\n\t\t}\n\t}\n\n\terr = git_model.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, git_model.WhitelistOptions{\n\t\tUserIDs: whitelistUsers,\n\t\tTeamIDs: whitelistTeams,\n\t\tMergeUserIDs: mergeWhitelistUsers,\n\t\tMergeTeamIDs: mergeWhitelistTeams,\n\t\tApprovalsUserIDs: approvalsWhitelistUsers,\n\t\tApprovalsTeamIDs: approvalsWhitelistTeams,\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"UpdateProtectBranch\", err)\n\t\treturn\n\t}\n\n\tisPlainRule := !git_model.IsRuleNameSpecial(bpName)\n\tvar isBranchExist bool\n\tif isPlainRule {\n\t\tisBranchExist = git.IsBranchExist(ctx.Req.Context(), ctx.Repo.Repository.RepoPath(), bpName)\n\t}\n\n\tif isBranchExist {\n\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, bpName); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPrsForBaseBranch\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !isPlainRule {\n\t\t\tif ctx.Repo.GitRepo == nil {\n\t\t\t\tctx.Repo.GitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.RepoPath())\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"OpenRepository\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer func() {\n\t\t\t\t\tctx.Repo.GitRepo.Close()\n\t\t\t\t\tctx.Repo.GitRepo = nil\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\t// FIXME: since we only need to recheck files protected rules, we could improve this\n\t\t\tmatchedBranches, err := git_model.FindAllMatchedBranches(ctx, ctx.Repo.Repository.ID, protectBranch.RuleName)\n\t\t\tif err != nil {\n\t\t\t\tctx.Error(http.StatusInternalServerError, \"FindAllMatchedBranches\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, branchName := range matchedBranches {\n\t\t\t\tif err = pull_service.CheckPRsForBaseBranch(ctx, ctx.Repo.Repository, branchName); err != nil {\n\t\t\t\t\tctx.Error(http.StatusInternalServerError, \"CheckPrsForBaseBranch\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reload from db to ensure get all whitelists\n\tbp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetProtectedBranchBy\", err)\n\t\treturn\n\t}\n\tif bp == nil || bp.RepoID != ctx.Repo.Repository.ID {\n\t\tctx.Error(http.StatusInternalServerError, \"New branch protection not found\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, convert.ToBranchProtection(bp))\n}", "func (gc *GithubClient) ListCommits(org, repo string, ID int) ([]*github.RepositoryCommit, error) {\n\toptions := &github.ListOptions{}\n\tgenericList, err := gc.depaginate(\n\t\tfmt.Sprintf(\"listing commits in Pull Requests '%d'\", ID),\n\t\tmaxRetryCount,\n\t\toptions,\n\t\tfunc() ([]interface{}, *github.Response, error) {\n\t\t\tpage, resp, err := gc.Client.PullRequests.ListCommits(ctx, org, repo, ID, options)\n\t\t\tvar interfaceList []interface{}\n\t\t\tif nil == err {\n\t\t\t\tfor _, commit := range page {\n\t\t\t\t\tinterfaceList = append(interfaceList, commit)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn interfaceList, resp, err\n\t\t},\n\t)\n\tres := make([]*github.RepositoryCommit, len(genericList))\n\tfor i, elem := range genericList {\n\t\tres[i] = elem.(*github.RepositoryCommit)\n\t}\n\treturn res, err\n}", "func (client *Client) FetchBranches(ctx context.Context, owner string, repo string) ([]model.Branch, error) {\n\topt := github.ListOptions{}\n\n\titems := []model.Branch{}\n\n\tfor {\n\t\tbranches, resp, err := client.github.Repositories.ListBranches(ctx, owner, repo, &opt)\n\t\tif err != nil {\n\t\t\treturn items, err\n\t\t}\n\n\t\tfor _, branch := range branches {\n\t\t\titems = append(items, model.ConvertBranch(owner, repo, branch))\n\t\t}\n\n\t\tif resp.NextPage == 0 {\n\t\t\treturn items, nil\n\t\t}\n\n\t\topt.Page = resp.NextPage\n\t}\n}", "func d16getBranches(node *d16nodeT, branch *d16branchT, parVars *d16partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d16maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d16maxNodes] = *branch\n\tparVars.branchCount = d16maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d16maxNodes+1; index++ {\n\t\tparVars.coverSplit = d16combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d16calcRectVolume(&parVars.coverSplit)\n}", "func d2getBranches(node *d2nodeT, branch *d2branchT, parVars *d2partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d2maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d2maxNodes] = *branch\n\tparVars.branchCount = d2maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d2maxNodes+1; index++ {\n\t\tparVars.coverSplit = d2combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d2calcRectVolume(&parVars.coverSplit)\n}", "func (b *BranchList) GetBranches() []*Branch {\n\treturn b.Branches\n}", "func GetBranchesMethods(w *wiki.WikiData) (r entities.Result) {\n\tr.WikiData, _ = wiki.FilterPagesRegs(w, wiki.MakeRegs(false, []string{`\\[\\[Kategorie:VSgS.*\\]\\]`, `\\[\\[Kategorie:Směry, školy, teorie a koncepce sociologického a sociálního myšlení\\]\\]`}))\n\tfor _, p := range r.WikiData.Page {\n\t\tr.Nodes = append(r.Nodes, entities.Node{\"Metody\", p.Title, p.Revision.Text, []string{}, GetLinks(string(p.Revision.Text)), \"\"})\n\t}\n\treturn r\n}", "func (c *singleClient) ListRepository(repo string) ([]string, error) {\n\treturn c.doList(repo, func(repo string, filter ListFilter) (\n\t\ttagmodels.ListResponse, error) {\n\n\t\treturn c.ListRepositoryWithPagination(repo, filter)\n\t})\n}", "func d9getBranches(node *d9nodeT, branch *d9branchT, parVars *d9partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d9maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d9maxNodes] = *branch\n\tparVars.branchCount = d9maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d9maxNodes+1; index++ {\n\t\tparVars.coverSplit = d9combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d9calcRectVolume(&parVars.coverSplit)\n}", "func d10getBranches(node *d10nodeT, branch *d10branchT, parVars *d10partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d10maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d10maxNodes] = *branch\n\tparVars.branchCount = d10maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d10maxNodes+1; index++ {\n\t\tparVars.coverSplit = d10combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d10calcRectVolume(&parVars.coverSplit)\n}", "func getRepoList(projectID int64) ([]string, error) {\n\t/*\n\t\tuiUser := os.Getenv(\"UI_USR\")\n\t\tif len(uiUser) == 0 {\n\t\t\tuiUser = \"admin\"\n\t\t}\n\t\tuiPwd := os.Getenv(\"UI_PWD\")\n\t\tif len(uiPwd) == 0 {\n\t\t\tuiPwd = \"Harbor12345\"\n\t\t}\n\t*/\n\tuiURL := config.LocalUIURL()\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", uiURL+\"/api/repositories?project_id=\"+strconv.Itoa(int(projectID)), nil)\n\tif err != nil {\n\t\tlog.Errorf(\"Error when creating request: %v\", err)\n\t\treturn nil, err\n\t}\n\t//req.SetBasicAuth(uiUser, uiPwd)\n\treq.AddCookie(&http.Cookie{Name: models.UISecretCookie, Value: config.UISecret()})\n\t//dump, err := httputil.DumpRequest(req, true)\n\t//log.Debugf(\"req: %q\", dump)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Error when calling UI api to get repositories, error: %v\", err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Errorf(\"Unexpected status code: %d\", resp.StatusCode)\n\t\tdump, _ := httputil.DumpResponse(resp, true)\n\t\tlog.Debugf(\"response: %q\", dump)\n\t\treturn nil, fmt.Errorf(\"Unexpected status code when getting repository list: %d\", resp.StatusCode)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to read the response body, error: %v\", err)\n\t\treturn nil, err\n\t}\n\tvar repoList []string\n\terr = json.Unmarshal(body, &repoList)\n\treturn repoList, err\n}", "func (b *BranchListBuilder) obtainReflogBranches() []*models.Branch {\n\tfoundBranchesMap := map[string]bool{}\n\tre := regexp.MustCompile(`checkout: moving from ([\\S]+) to ([\\S]+)`)\n\treflogBranches := make([]*models.Branch, 0, len(b.ReflogCommits))\n\tfor _, commit := range b.ReflogCommits {\n\t\tif match := re.FindStringSubmatch(commit.Name); len(match) == 3 {\n\t\t\trecency := utils.UnixToTimeAgo(commit.UnixTimestamp)\n\t\t\tfor _, branchName := range match[1:] {\n\t\t\t\tif !foundBranchesMap[branchName] {\n\t\t\t\t\tfoundBranchesMap[branchName] = true\n\t\t\t\t\treflogBranches = append(reflogBranches, &models.Branch{\n\t\t\t\t\t\tRecency: recency,\n\t\t\t\t\t\tName: branchName,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn reflogBranches\n}", "func (p GithubRepoHost) AddBranchProtection(repoID string) (BranchProtectionRule, error) {\n\tif isDebug() {\n\t\tfmt.Printf(\"Adding branch protection on %s\\n\", repoID)\n\t}\n\n\trules := fetchBranchProtectionRules()\n\tinput := githubv4.CreateBranchProtectionRuleInput{\n\t\tRepositoryID: repoID,\n\t\tPattern: *githubv4.NewString(githubv4.String(rules.Pattern)),\n\t\tDismissesStaleReviews: githubv4.NewBoolean(githubv4.Boolean(rules.DismissesStaleReviews)),\n\t\tIsAdminEnforced: githubv4.NewBoolean(githubv4.Boolean(rules.IsAdminEnforced)),\n\t\tRequiresApprovingReviews: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresApprovingReviews)),\n\t\tRequiredApprovingReviewCount: githubv4.NewInt(githubv4.Int(rules.RequiredApprovingReviewCount)),\n\t\tRequiresStatusChecks: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresStatusChecks)),\n\t}\n\n\tchecks := make([]githubv4.String, len(rules.RequiredStatusCheckContexts))\n\tfor i, name := range rules.RequiredStatusCheckContexts {\n\t\tchecks[i] = *githubv4.NewString(githubv4.String(name))\n\t}\n\tinput.RequiredStatusCheckContexts = &checks\n\n\tvar m CreateRuleMutation\n\tclient := buildClient()\n\terr := client.Mutate(context.Background(), &m, input, nil)\n\treturn m.CreateBranchProtectionRule.BranchProtectionRule, err\n}", "func (c *client) ListTeamRepos(org string, id int) ([]Repo, error) {\n\tc.logger.WithField(\"methodName\", \"ListTeamRepos\").\n\t\tWarn(\"method is deprecated, and will result in multiple api calls to achieve result\")\n\tdurationLogger := c.log(\"ListTeamRepos\", org, id)\n\tdefer durationLogger()\n\n\tif c.fake {\n\t\treturn nil, nil\n\t}\n\n\torganization, err := c.GetOrg(org)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := fmt.Sprintf(\"/organizations/%d/team/%d/repos\", organization.Id, id)\n\tvar repos []Repo\n\terr = c.readPaginatedResultsWithValues(\n\t\tpath,\n\t\turl.Values{\n\t\t\t\"per_page\": []string{\"100\"},\n\t\t},\n\t\t\"application/vnd.github+json\",\n\t\torg,\n\t\tfunc() interface{} {\n\t\t\treturn &[]Repo{}\n\t\t},\n\t\tfunc(obj interface{}) {\n\t\t\tfor _, repo := range *obj.(*[]Repo) {\n\t\t\t\t// Currently, GitHub API returns false for all permission levels\n\t\t\t\t// for a repo on which the team has 'Maintain' or 'Triage' role.\n\t\t\t\t// This check is to avoid listing a repo under the team but\n\t\t\t\t// showing the permission level as none.\n\t\t\t\tif LevelFromPermissions(repo.Permissions) != None {\n\t\t\t\t\trepos = append(repos, repo)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repos, nil\n}", "func repoBranchesDecode(b []byte) (map[string][]string, error) {\n\t// binaryReader returns strings pointing into b to avoid allocations. We\n\t// don't own b, so we create a copy of it.\n\tr := binaryReader{b: append([]byte{}, b...)}\n\n\t// Version\n\tif v := r.byt(); v != 1 {\n\t\treturn nil, fmt.Errorf(\"unsupported RepoBranches encoding version %d\", v)\n\t}\n\n\t// Length\n\tl := r.uvarint()\n\trepoBranches := make(map[string][]string, l)\n\n\tfor i := 0; i < l; i++ {\n\t\tname := r.str()\n\n\t\tbranchesLen := int(r.byt())\n\n\t\t// Special case \"HEAD\"\n\t\tif branchesLen == 0 {\n\t\t\trepoBranches[name] = head\n\t\t\tcontinue\n\t\t}\n\n\t\tbranches := make([]string, branchesLen)\n\t\tfor j := 0; j < branchesLen; j++ {\n\t\t\tbranches[j] = r.str()\n\t\t}\n\t\trepoBranches[name] = branches\n\t}\n\n\treturn repoBranches, r.err\n}", "func (g *GitRepo) sortBranches() []string {\n\tsorted := []string{\"master\"}\n\tfor _, branch := range g.branches {\n\t\tif branch == \"master\" || branch == \"origin/master\" {\n\t\t\tcontinue\n\t\t}\n\t\tsorted = append(sorted, branch)\n\t}\n\treturn sorted\n}", "func (c *client) ListRepoHooks(org, repo string) ([]Hook, error) {\n\tc.log(\"ListRepoHooks\", org, repo)\n\treturn c.listHooks(org, &repo)\n}", "func (g *GitLocal) RemoteBranches(dir string) ([]string, error) {\n\treturn g.GitCLI.RemoteBranches(dir)\n}", "func d14getBranches(node *d14nodeT, branch *d14branchT, parVars *d14partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d14maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d14maxNodes] = *branch\n\tparVars.branchCount = d14maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d14maxNodes+1; index++ {\n\t\tparVars.coverSplit = d14combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d14calcRectVolume(&parVars.coverSplit)\n}", "func d18getBranches(node *d18nodeT, branch *d18branchT, parVars *d18partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d18maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d18maxNodes] = *branch\n\tparVars.branchCount = d18maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d18maxNodes+1; index++ {\n\t\tparVars.coverSplit = d18combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d18calcRectVolume(&parVars.coverSplit)\n}", "func GetBranches(web *router.WebRequest) *model.Container {\n\tprojectName := web.GetQueryParam(\"project\")\n\tname := web.GetQueryParam(\"name\")\n\tif projectName == \"\" || name == \"\" {\n\t\treturn model.ErrorResponse(model.MessageItem{\n\t\t\tCode: \"invalid-request\",\n\t\t\tMessage: \"project name is required\",\n\t\t}, 500)\n\t}\n\tlist, err := factory.GetGitClient().ListBranches(projectName, name)\n\tif err != nil {\n\t\treturn model.ErrorResponse(model.MessageItem{\n\t\t\tCode: \"list-tag-error\",\n\t\t\tMessage: err.Error(),\n\t\t}, 500)\n\t}\n\tdata := make([]interface{}, 0)\n\tfor _, item := range list {\n\t\tdata = append(data, item)\n\t}\n\treturn model.ListResponse(data)\n}", "func UpdateBranchProtection() error {\n\tvar wg sync.WaitGroup\n\trequests, err := getBranchProtectionRequests()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twg.Add(len(requests))\n\towner, repo := getOwnerRepo()\n\n\tfor _, bp := range requests {\n\t\tgo func(bp BranchProtection) {\n\t\t\tdefer wg.Done()\n\t\t\t_, _, err := cli.Repositories.UpdateBranchProtection(ctx, owner, repo, bp.Branch, bp.Protection)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\t_, err = fmt.Fprintln(writer, fmt.Sprintf(\"branch %v has been protected\", bp.Branch))\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}(bp)\n\t}\n\n\twg.Wait()\n\n\treturn nil\n}", "func (mr *MockRepositoryClientMockRecorder) GetBranches(org, repo, onlyProtected interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBranches\", reflect.TypeOf((*MockRepositoryClient)(nil).GetBranches), org, repo, onlyProtected)\n}", "func GetBotsForRepo(repo string) ([]string, error) {\n\tcfg, err := GetProjectConfig(repo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn GetBotsForConfig(cfg), nil\n}", "func d20getBranches(node *d20nodeT, branch *d20branchT, parVars *d20partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d20maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d20maxNodes] = *branch\n\tparVars.branchCount = d20maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d20maxNodes+1; index++ {\n\t\tparVars.coverSplit = d20combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d20calcRectVolume(&parVars.coverSplit)\n}", "func d19getBranches(node *d19nodeT, branch *d19branchT, parVars *d19partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d19maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d19maxNodes] = *branch\n\tparVars.branchCount = d19maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d19maxNodes+1; index++ {\n\t\tparVars.coverSplit = d19combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d19calcRectVolume(&parVars.coverSplit)\n}", "func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whitelistUserIDs, whitelistTeamIDs string) (err error) {\n\tif err = repo.GetOwner(); err != nil {\n\t\treturn fmt.Errorf(\"GetOwner: %v\", err)\n\t} else if !repo.Owner.IsOrganization() {\n\t\treturn fmt.Errorf(\"expect repository owner to be an organization\")\n\t}\n\n\thasUsersChanged := false\n\tvalidUserIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistUserIDs, \",\"))\n\tif protectBranch.WhitelistUserIDs != whitelistUserIDs {\n\t\thasUsersChanged = true\n\t\tuserIDs := tool.StringsToInt64s(strings.Split(whitelistUserIDs, \",\"))\n\t\tvalidUserIDs = make([]int64, 0, len(userIDs))\n\t\tfor _, userID := range userIDs {\n\t\t\tif !Perms.Authorize(context.TODO(), userID, repo.ID, AccessModeWrite,\n\t\t\t\tAccessModeOptions{\n\t\t\t\t\tOwnerID: repo.OwnerID,\n\t\t\t\t\tPrivate: repo.IsPrivate,\n\t\t\t\t},\n\t\t\t) {\n\t\t\t\tcontinue // Drop invalid user ID\n\t\t\t}\n\n\t\t\tvalidUserIDs = append(validUserIDs, userID)\n\t\t}\n\n\t\tprotectBranch.WhitelistUserIDs = strings.Join(tool.Int64sToStrings(validUserIDs), \",\")\n\t}\n\n\thasTeamsChanged := false\n\tvalidTeamIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistTeamIDs, \",\"))\n\tif protectBranch.WhitelistTeamIDs != whitelistTeamIDs {\n\t\thasTeamsChanged = true\n\t\tteamIDs := tool.StringsToInt64s(strings.Split(whitelistTeamIDs, \",\"))\n\t\tteams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v\", repo.OwnerID, repo.ID, err)\n\t\t}\n\t\tvalidTeamIDs = make([]int64, 0, len(teams))\n\t\tfor i := range teams {\n\t\t\tif teams[i].HasWriteAccess() && com.IsSliceContainsInt64(teamIDs, teams[i].ID) {\n\t\t\t\tvalidTeamIDs = append(validTeamIDs, teams[i].ID)\n\t\t\t}\n\t\t}\n\n\t\tprotectBranch.WhitelistTeamIDs = strings.Join(tool.Int64sToStrings(validTeamIDs), \",\")\n\t}\n\n\t// Make sure protectBranch.ID is not 0 for whitelists\n\tif protectBranch.ID == 0 {\n\t\tif _, err = x.Insert(protectBranch); err != nil {\n\t\t\treturn fmt.Errorf(\"Insert: %v\", err)\n\t\t}\n\t}\n\n\t// Merge users and members of teams\n\tvar whitelists []*ProtectBranchWhitelist\n\tif hasUsersChanged || hasTeamsChanged {\n\t\tmergedUserIDs := make(map[int64]bool)\n\t\tfor _, userID := range validUserIDs {\n\t\t\t// Empty whitelist users can cause an ID with 0\n\t\t\tif userID != 0 {\n\t\t\t\tmergedUserIDs[userID] = true\n\t\t\t}\n\t\t}\n\n\t\tfor _, teamID := range validTeamIDs {\n\t\t\tmembers, err := GetTeamMembers(teamID)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"GetTeamMembers [team_id: %d]: %v\", teamID, err)\n\t\t\t}\n\n\t\t\tfor i := range members {\n\t\t\t\tmergedUserIDs[members[i].ID] = true\n\t\t\t}\n\t\t}\n\n\t\twhitelists = make([]*ProtectBranchWhitelist, 0, len(mergedUserIDs))\n\t\tfor userID := range mergedUserIDs {\n\t\t\twhitelists = append(whitelists, &ProtectBranchWhitelist{\n\t\t\t\tProtectBranchID: protectBranch.ID,\n\t\t\t\tRepoID: repo.ID,\n\t\t\t\tName: protectBranch.Name,\n\t\t\t\tUserID: userID,\n\t\t\t})\n\t\t}\n\t}\n\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\tif err = sess.Begin(); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {\n\t\treturn fmt.Errorf(\"Update: %v\", err)\n\t}\n\n\t// Refresh whitelists\n\tif hasUsersChanged || hasTeamsChanged {\n\t\tif _, err = sess.Delete(&ProtectBranchWhitelist{ProtectBranchID: protectBranch.ID}); err != nil {\n\t\t\treturn fmt.Errorf(\"delete old protect branch whitelists: %v\", err)\n\t\t} else if _, err = sess.Insert(whitelists); err != nil {\n\t\t\treturn fmt.Errorf(\"insert new protect branch whitelists: %v\", err)\n\t\t}\n\t}\n\n\treturn sess.Commit()\n}", "func handleRepo(ctx context.Context, client *github.Client, repo *github.Repository) error {\n\topt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tteams, resp, err := client.Repositories.ListTeams(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {\n\t\tif _, ok := err.(*github.RateLimitError); ok {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcollabs, resp, err := client.Repositories.ListCollaborators(ctx, repo.GetOwner().GetLogin(), repo.GetName(), &github.ListCollaboratorsOptions{ListOptions: *opt})\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {\n\t\tif _, ok := err.(*github.RateLimitError); ok {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkeys, resp, err := client.Repositories.ListKeys(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {\n\t\tif _, ok := err.(*github.RateLimitError); ok {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thooks, resp, err := client.Repositories.ListHooks(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {\n\t\tif _, ok := err.(*github.RateLimitError); ok {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbranches, _, err := client.Repositories.ListBranches(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprotectedBranches := []string{}\n\tunprotectedBranches := []string{}\n\tfor _, branch := range branches {\n\t\t// we must get the individual branch for the branch protection to work\n\t\tb, _, err := client.Repositories.GetBranch(ctx, repo.GetOwner().GetLogin(), repo.GetName(), branch.GetName())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif b.GetProtected() {\n\t\t\tprotectedBranches = append(protectedBranches, b.GetName())\n\t\t} else {\n\t\t\tunprotectedBranches = append(unprotectedBranches, b.GetName())\n\t\t}\n\t}\n\n\t// only print whole status if we have more that one collaborator\n\tif len(collabs) <= 1 && len(keys) < 1 && len(hooks) < 1 && len(protectedBranches) < 1 && len(unprotectedBranches) < 1 {\n\t\treturn nil\n\t}\n\n\toutput := fmt.Sprintf(\"%s -> \\n\", repo.GetFullName())\n\n\tif len(collabs) > 1 {\n\t\tpush := []string{}\n\t\tpull := []string{}\n\t\tadmin := []string{}\n\t\tfor _, c := range collabs {\n\t\t\tuserTeams := []github.Team{}\n\t\t\tfor _, t := range teams {\n\t\t\t\tisMember, resp, err := client.Teams.GetTeamMembership(ctx, t.GetID(), c.GetLogin())\n\t\t\t\tif resp.StatusCode != http.StatusNotFound && resp.StatusCode != http.StatusForbidden && err == nil && isMember.GetState() == \"active\" {\n\t\t\t\t\tuserTeams = append(userTeams, *t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tperms := c.GetPermissions()\n\n\t\t\tswitch {\n\t\t\tcase perms[\"admin\"]:\n\t\t\t\tpermTeams := []string{}\n\t\t\t\tfor _, t := range userTeams {\n\t\t\t\t\tif t.GetPermission() == \"admin\" {\n\t\t\t\t\t\tpermTeams = append(permTeams, t.GetName())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tadmin = append(admin, fmt.Sprintf(\"\\t\\t\\t%s (teams: %s)\", c.GetLogin(), strings.Join(permTeams, \", \")))\n\t\t\tcase perms[\"push\"]:\n\t\t\t\tpush = append(push, fmt.Sprintf(\"\\t\\t\\t%s\", c.GetLogin()))\n\t\t\tcase perms[\"pull\"]:\n\t\t\t\tpull = append(pull, fmt.Sprintf(\"\\t\\t\\t%s\", c.GetLogin()))\n\t\t\t}\n\t\t}\n\t\toutput += fmt.Sprintf(\"\\tCollaborators (%d):\\n\", len(collabs))\n\t\toutput += fmt.Sprintf(\"\\t\\tAdmin (%d):\\n%s\\n\", len(admin), strings.Join(admin, \"\\n\"))\n\t\toutput += fmt.Sprintf(\"\\t\\tWrite (%d):\\n%s\\n\", len(push), strings.Join(push, \"\\n\"))\n\t\toutput += fmt.Sprintf(\"\\t\\tRead (%d):\\n%s\\n\", len(pull), strings.Join(pull, \"\\n\"))\n\t}\n\n\tif len(keys) > 0 {\n\t\tkstr := []string{}\n\t\tfor _, k := range keys {\n\t\t\tkstr = append(kstr, fmt.Sprintf(\"\\t\\t%s - ro:%t (%s)\", k.GetTitle(), k.GetReadOnly(), k.GetURL()))\n\t\t}\n\t\toutput += fmt.Sprintf(\"\\tKeys (%d):\\n%s\\n\", len(kstr), strings.Join(kstr, \"\\n\"))\n\t}\n\n\tif len(hooks) > 0 {\n\t\thstr := []string{}\n\t\tfor _, h := range hooks {\n\t\t\thstr = append(hstr, fmt.Sprintf(\"\\t\\t%s - active:%t (%s)\", h.GetName(), h.GetActive(), h.GetURL()))\n\t\t}\n\t\toutput += fmt.Sprintf(\"\\tHooks (%d):\\n%s\\n\", len(hstr), strings.Join(hstr, \"\\n\"))\n\t}\n\n\tif len(protectedBranches) > 0 {\n\t\toutput += fmt.Sprintf(\"\\tProtected Branches (%d): %s\\n\", len(protectedBranches), strings.Join(protectedBranches, \", \"))\n\t}\n\n\tif len(unprotectedBranches) > 0 {\n\t\toutput += fmt.Sprintf(\"\\tUnprotected Branches (%d): %s\\n\", len(unprotectedBranches), strings.Join(unprotectedBranches, \", \"))\n\t}\n\n\trepo, _, err = client.Repositories.Get(ctx, repo.GetOwner().GetLogin(), repo.GetName())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmergeMethods := \"\\tMerge Methods:\"\n\tif repo.GetAllowMergeCommit() {\n\t\tmergeMethods += \" mergeCommit\"\n\t}\n\tif repo.GetAllowSquashMerge() {\n\t\tmergeMethods += \" squash\"\n\t}\n\tif repo.GetAllowRebaseMerge() {\n\t\tmergeMethods += \" rebase\"\n\t}\n\toutput += mergeMethods + \"\\n\"\n\n\tfmt.Printf(\"%s--\\n\\n\", output)\n\n\treturn nil\n}", "func (t *Commit) GetRepoID() string {\n\treturn t.RepoID\n}", "func NewListRepoTokensForbidden() *ListRepoTokensForbidden {\n\treturn &ListRepoTokensForbidden{}\n}", "func (m *MockGitUseCaseI) GetBranchList(requestUserID *int64, userName, repoName string) (git.BranchSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetBranchList\", requestUserID, userName, repoName)\n\tret0, _ := ret[0].(git.BranchSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepositoryClient) GetBranchProtection(org, repo, branch string) (*github.BranchProtection, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetBranchProtection\", org, repo, branch)\n\tret0, _ := ret[0].(*github.BranchProtection)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetBranch(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/branches/{branch} repository repoGetBranch\n\t// ---\n\t// summary: Retrieve a specific branch from a repository, including its effective branch protection\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: branch\n\t// in: path\n\t// description: branch to get\n\t// type: string\n\t// required: true\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/Branch\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\tbranchName := ctx.Params(\"*\")\n\n\tbranch, err := ctx.Repo.GitRepo.GetBranch(branchName)\n\tif err != nil {\n\t\tif git.IsErrBranchNotExist(err) {\n\t\t\tctx.NotFound(err)\n\t\t} else {\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetBranch\", err)\n\t\t}\n\t\treturn\n\t}\n\n\tc, err := branch.GetCommit()\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetCommit\", err)\n\t\treturn\n\t}\n\n\tbranchProtection, err := git_model.GetFirstMatchProtectedBranchRule(ctx, ctx.Repo.Repository.ID, branchName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetBranchProtection\", err)\n\t\treturn\n\t}\n\n\tbr, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch.Name, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"convert.ToBranch\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, br)\n}", "func (s *ActionsService) ListRepoSecrets(ctx context.Context, owner, repo string, opts *ListOptions) (*Secrets, *Response, error) {\n\turl := fmt.Sprintf(\"repos/%v/%v/actions/secrets\", owner, repo)\n\treturn s.listSecrets(ctx, url, opts)\n}", "func extractBranches(r *git.Repository) ([]string, error) {\n\titer, err := r.NewBranchIterator(git.BranchAll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbranchRef := []string{}\n\terr = iter.ForEach(func(branch *git.Branch, branchType git.BranchType) error {\n\t\tname, err := branch.Name()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tname = strings.TrimPrefix(name, originPrefix)\n\t\tbranchRef = append(branchRef, name)\n\t\treturn nil\n\t})\n\treturn branchRef, err\n}", "func (fn GetReposOwnerRepoBranchesHandlerFunc) Handle(params GetReposOwnerRepoBranchesParams) middleware.Responder {\n\treturn fn(params)\n}", "func (r *BetRepository) GetBySelectionID(ctx context.Context, id string) ([]domainmodels.Bet, error) {\n\tstorageBets, err := r.queryGetBetsBySelectionID(ctx, id)\n\tif err == sql.ErrNoRows {\n\t\treturn []domainmodels.Bet{}, nil\n\t}\n\tif err != nil {\n\t\treturn []domainmodels.Bet{}, errors.Wrap(err, \"bet repository failed to get bets with selection id \"+id)\n\t}\n\n\tvar domainBets []domainmodels.Bet\n\tfor _, storageBet := range storageBets {\n\t\tdomainBet := r.betMapper.MapStorageBetToDomainBet(storageBet)\n\t\tdomainBets = append(domainBets, domainBet)\n\t}\n\n\treturn domainBets, nil\n}", "func (mr *MockClientMockRecorder) GetBranches(org, repo, onlyProtected interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBranches\", reflect.TypeOf((*MockClient)(nil).GetBranches), org, repo, onlyProtected)\n}", "func (b *BranchDAG) ChildBranches(branchID BranchID) (cachedChildBranches CachedChildBranches) {\n\tcachedChildBranches = make(CachedChildBranches, 0)\n\tb.childBranchStorage.ForEach(func(key []byte, cachedObject objectstorage.CachedObject) bool {\n\t\tcachedChildBranches = append(cachedChildBranches, &CachedChildBranch{CachedObject: cachedObject})\n\n\t\treturn true\n\t}, objectstorage.WithIteratorPrefix(branchID.Bytes()))\n\n\treturn\n}", "func getRepoForks(client *ginclient.Client, repo string) ([]gogs.Repository, error) {\n\treqpath := fmt.Sprintf(\"api/v1/repos/%s/forks\", repo)\n\tresp, err := client.Get(reqpath)\n\tif err != nil {\n\t\tlog.Printf(\"Failed get forks for %q: %s\", repo, err.Error())\n\t\treturn nil, err\n\t}\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Failed read forks from response for %q: %s\", repo, err.Error())\n\t\treturn nil, err\n\t}\n\tforks := make([]gogs.Repository, 0)\n\terr = json.Unmarshal(data, &forks)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to unmarshal forks for %q: %s\", repo, err.Error())\n\t}\n\treturn forks, err\n}", "func (r *Repository) GitHubGetRepositoriesByCLAGroupDisabled(ctx context.Context, claGroupID string) ([]*repoModels.RepositoryDBModel, error) {\n\tcondition := expression.Key(repoModels.RepositoryCLAGroupIDColumn).Equal(expression.Value(claGroupID))\n\tfilter := expression.Name(repoModels.RepositoryTypeColumn).Equal(expression.Value(utils.GitLabLower)).\n\t\tAnd(expression.Name(repoModels.RepositoryEnabledColumn).Equal(expression.Value(false)))\n\trecords, err := r.getRepositoriesWithConditionFilter(ctx, condition, filter, repoModels.RepositoryProjectIndex)\n\tif err != nil {\n\t\t// Catch the error - return the same error with the appropriate details\n\t\tif _, ok := err.(*utils.GitLabRepositoryNotFound); ok {\n\t\t\treturn nil, &utils.GitLabRepositoryNotFound{\n\t\t\t\tCLAGroupID: claGroupID,\n\t\t\t}\n\t\t}\n\n\t\t// Some other error\n\t\treturn nil, err\n\t}\n\n\treturn records, nil\n}", "func (m *MockClient) GetBranchProtection(org, repo, branch string) (*github.BranchProtection, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetBranchProtection\", org, repo, branch)\n\tret0, _ := ret[0].(*github.BranchProtection)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func d8getBranches(node *d8nodeT, branch *d8branchT, parVars *d8partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d8maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d8maxNodes] = *branch\n\tparVars.branchCount = d8maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d8maxNodes+1; index++ {\n\t\tparVars.coverSplit = d8combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d8calcRectVolume(&parVars.coverSplit)\n}", "func d15getBranches(node *d15nodeT, branch *d15branchT, parVars *d15partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d15maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d15maxNodes] = *branch\n\tparVars.branchCount = d15maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d15maxNodes+1; index++ {\n\t\tparVars.coverSplit = d15combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d15calcRectVolume(&parVars.coverSplit)\n}", "func (p GithubRepoHost) UpdateBranchProtection(repoID string, rule BranchProtectionRule) error {\n\tif isDebug() {\n\t\tfmt.Printf(\"Updating branch protection on %s\\n\", repoID)\n\t}\n\n\trules := fetchBranchProtectionRules()\n\tinput := githubv4.UpdateBranchProtectionRuleInput{\n\t\tBranchProtectionRuleID: rule.ID,\n\t\tPattern: githubv4.NewString(githubv4.String(rules.Pattern)),\n\t\tDismissesStaleReviews: githubv4.NewBoolean(githubv4.Boolean(rules.DismissesStaleReviews)),\n\t\tIsAdminEnforced: githubv4.NewBoolean(githubv4.Boolean(rules.IsAdminEnforced)),\n\t\tRequiresApprovingReviews: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresApprovingReviews)),\n\t\tRequiredApprovingReviewCount: githubv4.NewInt(githubv4.Int(rules.RequiredApprovingReviewCount)),\n\t\tRequiresStatusChecks: githubv4.NewBoolean(githubv4.Boolean(rules.RequiresStatusChecks)),\n\t\tRequiredStatusCheckContexts: &[]githubv4.String{\n\t\t\t*githubv4.NewString(\"build\"),\n\t\t},\n\t}\n\n\tvar m UpdateBranchProtectionRuleMutation\n\tclient := buildClient()\n\terr := client.Mutate(context.Background(), &m, input, nil)\n\treturn err\n}", "func IsUserInProtectBranchWhitelist(repoID, userID int64, branch string) bool {\n\thas, err := x.Where(\"repo_id = ?\", repoID).And(\"user_id = ?\", userID).And(\"name = ?\", branch).Get(new(ProtectBranchWhitelist))\n\treturn has && err == nil\n}", "func (c APIClient) ListRepo() ([]*pfs.RepoInfo, error) {\n\trequest := &pfs.ListRepoRequest{}\n\trepoInfos, err := c.PfsAPIClient.ListRepo(\n\t\tc.Ctx(),\n\t\trequest,\n\t)\n\tif err != nil {\n\t\treturn nil, grpcutil.ScrubGRPC(err)\n\t}\n\treturn repoInfos.RepoInfo, nil\n}", "func (o *PostWebhook) GetBranchesToIgnore() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.BranchesToIgnore\n}", "func d1getBranches(node *d1nodeT, branch *d1branchT, parVars *d1partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d1maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d1maxNodes] = *branch\n\tparVars.branchCount = d1maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d1maxNodes+1; index++ {\n\t\tparVars.coverSplit = d1combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d1calcRectVolume(&parVars.coverSplit)\n}", "func RetrieveGitRepositories(rootpath string) ([]string, error) {\n\tvar gitPaths []string\n\terr := filepath.Walk(rootpath, func(pathdir string, fileInfo os.FileInfo, err error) error {\n\t\tif fileInfo.IsDir() && filepath.Base(pathdir) == consts.GitFileName {\n\t\t\tfileDir := filepath.Dir(pathdir)\n\t\t\ttraces.DebugTracer.Printf(\"Just found in hard drive %s\\n\", fileDir)\n\t\t\tgitPaths = append(gitPaths, fileDir)\n\t\t}\n\t\treturn nil\n\t})\n\treturn gitPaths, err\n}", "func (h *branchesService) setGitBranchTips(repo *Repo) {\n\tvar invalidBranches []string\n\tfor _, b := range repo.Branches {\n\t\ttip, ok := repo.TryGetCommitByID(b.TipID)\n\t\tif !ok {\n\t\t\t// A branch tip id, which commit id does not exist in the repo\n\t\t\t// Store that branch name so it can be removed from the list below\n\t\t\tinvalidBranches = append(invalidBranches, b.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Adding the branch to the branch tip commit\n\t\ttip.addBranch(b)\n\t\ttip.BranchTipNames = append(tip.BranchTipNames, b.Name)\n\n\t\tif b.IsCurrent {\n\t\t\t// Mark the current branch tip commit as the current commit\n\t\t\ttip.IsCurrent = true\n\t\t}\n\t}\n\n\t// If some branches do not have existing tip commit id,\n\t// Remove them from the list of repo.Branches\n\tif len(invalidBranches) > 0 {\n\t\trepo.Branches = linq.Filter(repo.Branches, func(v *Branch) bool {\n\t\t\treturn !linq.Contains(invalidBranches, v.Name)\n\t\t})\n\t}\n}", "func (v *VersionHistory) GetBranchToken() []byte {\n\ttoken := make([]byte, len(v.BranchToken))\n\tcopy(token, v.BranchToken)\n\treturn token\n}", "func (c *Client) ListRepoAccounts(namespace, repoName string) ([]*api.Account, error) {\n\tout := []*api.Account{}\n\trawURL := fmt.Sprintf(pathRepoAccounts, c.base.String(), namespace, repoName)\n\terr := c.get(rawURL, true, &out)\n\treturn out, errio.Error(err)\n}", "func (o *VulnerabilitiesRequest) GetRepositoryList() []string {\n\tif o == nil || o.RepositoryList == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.RepositoryList\n}", "func (g *GitHub) GetRepos(userID string) (Repos []api.Repo, username, avatarURL string, err error) {\n\tds := store.NewStore()\n\tdefer ds.Close()\n\n\ttok, err := ds.FindtokenByUserID(userID, \"github\")\n\tif err != nil {\n\t\tlog.ErrorWithFields(\"find token failed\", log.Fields{\"user_id\": userID, \"error\": err})\n\t\treturn Repos, username, avatarURL, err\n\t}\n\n\t// Use token to get repo list.\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: tok.Vsctoken.AccessToken},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\n\tclient := github.NewClient(tc)\n\n\t// List all repositories for the authenticated user.\n\topt := &github.RepositoryListOptions{\n\t\tListOptions: github.ListOptions{PerPage: 30},\n\t}\n\t// Get all pages of results.\n\tvar allRepos []*github.Repository\n\tfor {\n\t\trepos, resp, err := client.Repositories.List(\"\", opt)\n\t\tif err != nil {\n\t\t\tmessage := \"Unable to list repo by token\"\n\t\t\tlog.ErrorWithFields(message, log.Fields{\"user_id\": userID, \"token\": tok, \"error\": err})\n\t\t\treturn Repos, username, avatarURL, fmt.Errorf(\"Unable to list repo by token\")\n\t\t}\n\t\tallRepos = append(allRepos, repos...)\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.ListOptions.Page = resp.NextPage\n\t}\n\n\tRepos = make([]api.Repo, len(allRepos))\n\tfor i, repo := range allRepos {\n\t\tRepos[i].Name = *repo.Name\n\t\tRepos[i].URL = *repo.CloneURL\n\t\tRepos[i].Owner = *repo.Owner.Login\n\t}\n\n\tuser, _, err := client.Users.Get(\"\")\n\tif err != nil {\n\t\tlog.ErrorWithFields(\"Users.Get returned error\", log.Fields{\"user_id\": userID,\n\t\t\t\"token\": tok, \"error\": err})\n\t\treturn Repos, username, avatarURL, err\n\t}\n\tusername = *user.Login\n\tavatarURL = *user.AvatarURL\n\n\treturn Repos, username, avatarURL, nil\n}", "func NewPatchReposOwnerRepoReleasesIDForbidden() *PatchReposOwnerRepoReleasesIDForbidden {\n\treturn &PatchReposOwnerRepoReleasesIDForbidden{}\n}", "func (r *Repository) GitHubGetRepositoriesByProjectSFID(ctx context.Context, projectSFID string) ([]*repoModels.RepositoryDBModel, error) {\n\tcondition := expression.Key(repoModels.RepositoryProjectIDColumn).Equal(expression.Value(projectSFID))\n\tfilter := expression.Name(repoModels.RepositoryTypeColumn).Equal(expression.Value(utils.GitLabLower))\n\n\trecords, err := r.getRepositoriesWithConditionFilter(ctx, condition, filter, repoModels.RepositoryProjectSFIDIndex)\n\tif err != nil {\n\t\t// Catch the error - return the same error with the appropriate details\n\t\tif _, ok := err.(*utils.GitLabRepositoryNotFound); ok {\n\t\t\treturn nil, &utils.GitLabRepositoryNotFound{\n\t\t\t\tProjectSFID: projectSFID,\n\t\t\t}\n\t\t}\n\n\t\t// Some other error\n\t\treturn nil, err\n\t}\n\n\treturn records, nil\n}", "func (o *BranchingModelSettings) GetBranchTypes() []BranchingModelSettingsBranchTypes {\n\tif o == nil || o.BranchTypes == nil {\n\t\tvar ret []BranchingModelSettingsBranchTypes\n\t\treturn ret\n\t}\n\treturn *o.BranchTypes\n}", "func d3getBranches(node *d3nodeT, branch *d3branchT, parVars *d3partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d3maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d3maxNodes] = *branch\n\tparVars.branchCount = d3maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d3maxNodes+1; index++ {\n\t\tparVars.coverSplit = d3combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d3calcRectVolume(&parVars.coverSplit)\n}", "func getAndMergeFetchedBranches(branches []Branch) []Branch {\n\trawString, err := runDirectCommand(\"git branch --sort=-committerdate --no-color\")\n\tif err != nil {\n\t\treturn branches\n\t}\n\tbranchLines := splitLines(rawString)\n\tfor _, line := range branchLines {\n\t\tline = strings.Replace(line, \"* \", \"\", -1)\n\t\tline = strings.TrimSpace(line)\n\t\tif branchAlreadyStored(line, branches) {\n\t\t\tcontinue\n\t\t}\n\t\tbranches = append(branches, constructBranch(\"\", line, len(branches)))\n\t}\n\treturn branches\n}", "func ListBranchesAndTags(branchType git.BranchType, repoLocation data.RepoLocation, repoIdentifier data.RepoIdentifier) (data.BranchesAndTags, error) {\n\tvar (\n\t\tremoteBranches = make([]data.Remotes, 0)\n\t\tremoteTags = make([]data.Remotes, 0)\n\t\trepoId = repoIdentifier.RepoId()\n\t)\n\trepo, err := git.OpenRepository(repoLocation.GetRepoPath(repoId))\n\tif err != nil {\n\t\treturn data.BranchesAndTags{}, err\n\t}\n\tbranchIterator, err := repo.NewBranchIterator(branchType)\n\tif err != nil {\n\t\treturn data.BranchesAndTags{}, err\n\t}\n\n\tbranchIterator.ForEach(func(b *git.Branch, bt git.BranchType) error {\n\t\tname, err := b.Name()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treg := regexp.MustCompile(\"^[A-Za-z0-9_-]+\\\\/\")\n\t\tname = reg.ReplaceAllString(name, \"\")\n\t\ttarget := b.Target()\n\t\tvar hash string\n\t\tif nil == target {\n\t\t\thash = \"\"\n\t\t} else {\n\t\t\thash = target.String()\n\t\t}\n\n\t\tremoteBranches = append(remoteBranches, data.Remotes{Type: \"branch\", Hash: hash, Value: name})\n\n\t\treturn nil\n\t})\n\n\trefIt, err := repo.NewReferenceIteratorGlob(\"refs/tags/*\")\n\n\tif err != nil {\n\t\treturn data.BranchesAndTags{}, err\n\t}\n\n\ttag, err := refIt.Next()\n\tfor err == nil {\n\t\tname := strings.Replace(tag.Name(), \"refs/tags/\", \"\", 1)\n\t\tremoteTags = append(remoteTags, data.Remotes{Type: \"tag\", Hash: tag.Target().String(), Value: name})\n\t\ttag, err = refIt.Next()\n\t}\n\n\treturn data.BranchesAndTags{Tags: remoteTags, Branches: remoteBranches}, nil\n}", "func (gc *GithubClient) ListFiles(org, repo string, ID int) ([]*github.CommitFile, error) {\n\toptions := &github.ListOptions{}\n\tgenericList, err := gc.depaginate(\n\t\tfmt.Sprintf(\"listing files in Pull Requests '%d'\", ID),\n\t\tmaxRetryCount,\n\t\toptions,\n\t\tfunc() ([]interface{}, *github.Response, error) {\n\t\t\tpage, resp, err := gc.Client.PullRequests.ListFiles(ctx, org, repo, ID, options)\n\t\t\tvar interfaceList []interface{}\n\t\t\tif nil == err {\n\t\t\t\tfor _, f := range page {\n\t\t\t\t\tinterfaceList = append(interfaceList, f)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn interfaceList, resp, err\n\t\t},\n\t)\n\tres := make([]*github.CommitFile, len(genericList))\n\tfor i, elem := range genericList {\n\t\tres[i] = elem.(*github.CommitFile)\n\t}\n\treturn res, err\n}" ]
[ "0.63642013", "0.6320566", "0.5900391", "0.56682706", "0.5501149", "0.54667157", "0.54543006", "0.54134506", "0.51837456", "0.51545143", "0.4974663", "0.49698856", "0.496513", "0.494982", "0.49366364", "0.48883775", "0.48778513", "0.48493487", "0.48474577", "0.4751535", "0.4738013", "0.4727116", "0.46891257", "0.46279487", "0.46260476", "0.46001658", "0.4584099", "0.4443153", "0.43944657", "0.4355819", "0.4330614", "0.43177867", "0.42948732", "0.428859", "0.42869312", "0.42554495", "0.42474577", "0.42436764", "0.42427632", "0.42196605", "0.42130962", "0.42129242", "0.42037672", "0.4185289", "0.41805115", "0.41713718", "0.415691", "0.41369703", "0.41276246", "0.41234654", "0.41199735", "0.41189623", "0.4118698", "0.4107066", "0.41066894", "0.41031754", "0.40986046", "0.40965202", "0.40940282", "0.4078522", "0.40735498", "0.40721348", "0.40634027", "0.40613437", "0.40541816", "0.40349302", "0.40340856", "0.4020747", "0.40184954", "0.39898738", "0.39852864", "0.39805168", "0.39771998", "0.3975001", "0.39733595", "0.39705288", "0.39460677", "0.39407125", "0.3935295", "0.39310738", "0.39125556", "0.38983607", "0.3891863", "0.38907406", "0.3878355", "0.38698998", "0.38690582", "0.38684618", "0.38672388", "0.3834461", "0.38306448", "0.38193005", "0.38117662", "0.38116118", "0.37996015", "0.37980378", "0.37955904", "0.37910184", "0.37893963", "0.37875175" ]
0.90316087
0
QuickExec quick exec an simple command line
QuickExec быстрое выполнение простой командной строки
func QuickExec(cmdLine string, workDir ...string) (string, error) { return ExecLine(cmdLine, workDir...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\tlines := util.ReadLines()\n\n\tansP1, ansP2 := Exec(lines)\n\tfmt.Printf(\"Part1: %v\\n\", ansP1)\n\tfmt.Printf(\"Part2: %v\\n\", ansP2)\n}", "func main() {\n\tInitVars()\n\ttfmBins := InitTfmBins(&OsPath)\n\tverConstraints, err := ParseTfmConfigs(\"./\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"[ERROR] %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\ttfmBinFile := SelectTfmBin(verConstraints, tfmBins)\n\tmyDebug(\"Calling: %s\", tfmBinFile)\n\tif tfmBinFile == \"\" {\n\t\tfmt.Println(\"[ERROR] there is no file to execute\")\n\t\tos.Exit(1)\n\t}\n\tout, err := exec.Command(tfmBinFile, os.Args[1:]...).CombinedOutput()\n\tfmt.Println(string(out[:]))\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}", "func main() {\n\tcmd.Execute()\n}", "func main() {\n\tcmd.Execute()\n}", "func main() {\n\tcmd.Execute()\n}", "func main() {\n\tcmd.Execute()\n}", "func main() {\n\tcmd.Execute()\n}", "func main() {\n\tcmd.Execute()\n}", "func main() {\n\tcmd.Execute()\n}", "func main() {\n\terr := cmd.Execute(version)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func main() {\n\tcmd.Root().Execute()\n}", "func Exec(cmd string) {\n\n\tfmt.Printf(\"Você digitou: %s \", cmd)\n\n}", "func Executable() (string, error)", "func Setup(c *exec.Cmd) {}", "func ExecBuiltin(args []string) {\n\tif len(args) <= 0 {\n\t\tPanic(\"No parameters\")\n\t}\n\n\t//TODO: Loadings\n\tswitch args[0] {\n\tcase \"Error\":\n\t\tError(strings.Join(args[1:], \" \"))\n\tcase \"Warn\":\n\t\tWarn(strings.Join(args[1:], \" \"))\n\tcase \"Info\":\n\t\tInfo(strings.Join(args[1:], \" \"))\n\tcase \"Made\":\n\t\tMade(strings.Join(args[1:], \" \"))\n\tcase \"Ask\":\n\t\tif noColor {\n\t\t\tfmt.Print(\"[?] \")\n\t\t} else {\n\t\t\tfmt.Print(\"\\033[38;5;99;01m[?]\\033[00m \")\n\t\t}\n\t\tfmt.Println(strings.Join(args[1:], \" \"))\n\tcase \"AskYN\":\n\t\tif AskYN(strings.Join(args[1:], \" \")) {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tos.Exit(1)\n\tcase \"Read\":\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tfmt.Print(text)\n\tcase \"ReadSecure\":\n\t\tfmt.Print(ReadSecure())\n\tcase \"AskList\":\n\t\tvalues := \"\"\n\t\tdflt := -1\n\n\t\tif len(args) >= 3 {\n\t\t\tvalues = args[2]\n\t\t\tif len(args) >= 4 {\n\t\t\t\tif i, err := strconv.Atoi(args[3]); err == nil {\n\t\t\t\t\tdflt = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tos.Exit(AskList(strings.Split(values, \",\"), dflt, args[1]))\n\tcase \"Bell\":\n\t\tBell()\n\t}\n\tos.Exit(0)\n}", "func main() {\n cmd.Execute ()\n}", "func main() {\n\n\tif err := qml.Run(run); err != nil {\n\t\tfmt.Fprint(os.Stderr, \"error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func (s *GitTestHelper) Exec(first string, arg ...string) bool {\n\tif s.err != nil {\n\t\treturn false\n\t}\n\tcmd := s.runner.Command(first, arg...).WithDir(s.Getwd())\n\tbytearr, err := cmd.CombinedOutput()\n\tif s.debugExec {\n\t\twords := append([]string{\">>>\", first}, arg...)\n\t\tfmt.Println(strings.Join(words, \" \"))\n\t\tfmt.Println(string(bytearr))\n\t}\n\tif err != nil {\n\t\ts.err = fmt.Errorf(\"%v %v\", err, string(bytearr))\n\t\ts.errCause = first + \" \" + strings.Join(arg, \" \")\n\t\treturn false\n\t}\n\treturn true\n}", "func main() {\n\tapp := getRootCmd()\n\n\t// ignore error so we don't exit non-zero and break gfmrun README example tests\n\t_ = app.Execute()\n}", "func main() {\n\tif err := cmd.Cmd.Execute(); err != nil {\n\t\tos.Exit(1)\n\t}\n}", "func SimpleExec(name string, args ...string) (string, error) {\n\tTrace(name, args...)\n\treturn Output(ExecCommand(name, args...))\n}", "func SimpleExec(name string, args ...string) (string, error) {\n\treturn Output(ExecCommand(name, args...))\n}", "func main() {\n\n // Go requires an absolute path to the binary we want to execute, so we’ll use exec.LookPath to find it (probably /bin/ls).\n // Exec requires arguments in slice form (as apposed to one big string).\n binary, lookErr := exec.LookPath(\"ls\")\n if lookErr != nil {\n panic(lookErr)\n }\n\n args := []string{\"ls\", \"-a\", \"-l\", \"-h\"} //Exec requires arguments in slice form (as apposed to one big string). first argument should be the program name\n\n //Exec also needs a set of environment variables to use. Here we just provide our current environment.\n env := os.Environ()\n\n execErr := syscall.Exec(binary, args, env) //Here’s the actual syscall.Exec call.\n //If this call is successful, the execution of our process will end here and be replaced by the /bin/ls -a -l -h process.\n if execErr != nil {// If there is an error we’ll get a return value.\n panic(execErr)\n }\n}", "func exec(c *lxc.Container, conf *Config) {\n\tvar output []byte\n\tvar err error\n\t// stdout and stderr are unfornutately concatenated\n\tif output, err = c.Execute(conf.Args.Command...); err != nil {\n\t\tif len(output) != 0 {\n\t\t\tfmt.Printf(\"%s\\n\", output)\n\t\t}\n\t\terrorExit(2, err)\n\t} else {\n\t\tfmt.Printf(\"%s\", output)\n\t}\n}", "func (c *cmdVersion) Exec(args []string) error {\n\n\tif len(args) != 0 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: mashling version \\n\\nToo many arguments given.\\n\")\n\t\tos.Exit(2)\n\t} else {\n\t\tc.versionNumber = version\n\t\tfmt.Printf(\"mashling version %s\\n\", c.versionNumber)\n\t}\n\n\treturn nil\n}", "func cmdLine() string {\n\treturn \"go run mksyscall_aix_ppc64.go \" + strings.Join(os.Args[1:], \" \")\n}", "func main() {\n\texecute.Execute()\n}", "func startQuickQuit(i *app.Indicator) {\n\ti.AddQuick(\"QUIT\", qQuit, func(args ...interface{}) {\n\t\ti := args[0].(*app.Indicator)\n\t\ti.Quit()\n\t}, i)\n}", "func (t *Test) exec(tc testCommand) error {\n\tswitch cmd := tc.(type) {\n\tcase *clearCmd:\n\t\treturn t.clear()\n\n\tcase *loadCmd:\n\t\treturn cmd.append()\n\n\tcase *evalCmd:\n\t\texpr, err := parser.ParseExpr(cmd.expr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt := time.Unix(0, startingTime+(cmd.start.Unix()*1000000000))\n\t\tbodyBytes, err := cmd.m3query.query(expr.String(), t)\n\t\tif err != nil {\n\t\t\tif cmd.fail {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errors.Wrapf(err, \"error in %s %s, line %d\", cmd, cmd.expr, cmd.line)\n\t\t}\n\t\tif cmd.fail {\n\t\t\treturn fmt.Errorf(\"expected to fail at %s %s, line %d\", cmd, cmd.expr, cmd.line)\n\t\t}\n\n\t\terr = cmd.compareResult(bodyBytes)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error in %s %s, line %d. m3query response: %s\", cmd, cmd.expr, cmd.line, string(bodyBytes))\n\t\t}\n\n\tdefault:\n\t\tpanic(\"promql.Test.exec: unknown test command type\")\n\t}\n\treturn nil\n}", "func main() {\n\terr := cmd.RootCmd.Execute()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Executor(s string) {\n\ts = strings.TrimSpace(s)\n\tcmdStrings := strings.Split(s, \" \")\n\tif s == \"\" {\n\t\treturn\n\t} else if s == \"quit\" || s == \"exit\" {\n\t\tfmt.Println(\"Bye!\")\n\t\tos.Exit(0)\n\t\treturn\n\t}\n\tswitch cmdStrings[0] {\n\tcase \"install-px\":\n\t\tinstallPX()\n\tcase \"deploy\":\n\t\tif len(cmdStrings) < 2 {\n\t\t\tfmt.Println(\"deploy requires an application name\")\n\t\t\treturn\n\t\t}\n\t\tdeploy(\"default\", cmdStrings[1])\n\tcase \"benchmark\":\n\t\tswitch cmdStrings[1] {\n\t\tcase \"postgres\":\n\t\t\tpodExec(\"default\", \"app=postgres\", \"/usr/bin/psql -c 'create database pxdemo;'\")\n\t\t\tpodExec(\"default\", \"app=postgres\", \"/usr/bin/pgbench -n -i -s 50 pxdemo;\")\n\t\t\tpodExec(\"default\", \"app=postgres\", \"/usr/bin/psql pxdemo -c 'select count(*) from pgbench_accounts;'\")\n\t\tdefault:\n\t\t\tfmt.Printf(\"%s benchmark not supported\\n\", cmdStrings[1])\n\t\t}\n\tcase \"px\":\n\t\tif len(cmdStrings) < 2 {\n\t\t\tfmt.Println(\"deploy requires an application name\")\n\t\t\treturn\n\t\t}\n\t\tswitch cmdStrings[1] {\n\t\tcase \"connect\":\n\t\t\tpxInit()\n\t\tcase \"snap\":\n\t\t\tif len(cmdStrings) < 3 {\n\t\t\t\tfmt.Println(\"px snap requires an application name\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpxSnap(cmdStrings[2])\n\t\tcase \"backup\":\n\t\t\tif len(cmdStrings) < 3 {\n\t\t\t\tfmt.Println(\"px backup requires an PVC name\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpxBackup(cmdStrings[2])\n\t\tcase \"backup-status\":\n\t\t\tif len(cmdStrings) < 3 {\n\t\t\t\tfmt.Println(\"px backup-status requires a PVC name\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpxBackupStatus(cmdStrings[2])\n\t\tdefault:\n\t\t\tfmt.Printf(\"px %s is not a valid command\\n\", cmdStrings[1])\n\t\t}\n\tcase \"pre-flight-check\":\n\t\tpreflight()\n\tdefault:\n\t\tfmt.Printf(\"%s is not a supported option\", s)\n\t}\n\treturn\n}", "func main() {\n\tcmd.Execute(version, gitCommit, buildDate)\n}", "func SimpleExec(cmdName string, arguments ...string) {\n\tcmd := exec.Command(cmdName, arguments...) // nolint: gosec\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n cli := CLI{}\n cli.Run()\n}", "func Exec(name string, args ...string) string {\n\tout, err := exec.Command(name, args...).Output()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\treturn string(out)\n}", "func startQuickLiqoWebsite(i *app.Indicator) {\n\ti.AddQuick(\"ⓘ About Liqo\", qWeb, func(args ...interface{}) {\n\t\tcmd := exec.Command(\"xdg-open\", \"http://liqo.io\")\n\t\t_ = cmd.Run()\n\t})\n}", "func Exec(name string, args ...string) error {\n\treturn syscall.Exec(name, args, os.Environ())\n}", "func Execute(osArgs []string) {\n\tif len(osArgs) == 2 && osArgs[1] == \"-i\" {\n\t\tinteractive = true\n\t}\n\tif interactive {\n\t\tshell = ishell.NewWithConfig(\n\t\t\t&readline.Config{\n\t\t\t\tPrompt: fmt.Sprintf(\"%c[1;0;32m%s%c[0m\", 0x1B, \">> \", 0x1B),\n\t\t\t\tHistoryFile: \"/tmp/readline.tmp\",\n\t\t\t\t//AutoComplete: completer,\n\t\t\t\tInterruptPrompt: \"^C\",\n\t\t\t\tEOFPrompt: \"exit\",\n\t\t\t\tHistorySearchFold: true,\n\t\t\t\t//FuncFilterInputRune: filterInput,\n\t\t\t})\n\t\tshell.Println(\"QLC Chain Server\")\n\t\taddCommand()\n\t\tshell.Run()\n\t} else {\n\t\trootCmd = &cobra.Command{\n\t\t\tUse: \"gqlc\",\n\t\t\tShort: \"CLI for QLCChain Server\",\n\t\t\tLong: `QLC Chain is the next generation public block chain designed for the NaaS.`,\n\t\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\t\terr := start()\n\t\t\t\tif err != nil {\n\t\t\t\t\tcmd.Println(err)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t\trootCmd.PersistentFlags().StringVar(&cfgPathP, \"config\", \"\", \"config file\")\n\t\trootCmd.PersistentFlags().StringVar(&accountP, \"account\", \"\", \"wallet address, if is nil,just run a node\")\n\t\trootCmd.PersistentFlags().StringVar(&passwordP, \"password\", \"\", \"password for wallet\")\n\t\trootCmd.PersistentFlags().StringVar(&seedP, \"seed\", \"\", \"seed for accounts\")\n\t\trootCmd.PersistentFlags().StringVar(&privateKeyP, \"privateKey\", \"\", \"seed for accounts\")\n\t\trootCmd.PersistentFlags().BoolVar(&isProfileP, \"profile\", false, \"enable profile\")\n\t\trootCmd.PersistentFlags().BoolVar(&noBootstrapP, \"nobootnode\", false, \"disable bootstrap node\")\n\t\trootCmd.PersistentFlags().StringVar(&configParamsP, \"configParams\", \"\", \"parameter set that needs to be changed\")\n\t\trootCmd.PersistentFlags().StringVar(&testModeP, \"testMode\", \"\", \"testing mode\")\n\t\taddCommand()\n\t\tif err := rootCmd.Execute(); err != nil {\n\t\t\tlog.Root.Info(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func (p *Qlang) Exec(codeText []byte, fname string) (err error) {\n\n\tcode := p.cl.Code()\n\tstart := code.Len()\n\tend, err := p.Cl(codeText, fname)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif qcl.DumpCode != 0 {\n\t\tcode.Dump(start)\n\t}\n\n\tp.ExecBlock(start, end, p.cl.GlobalSymbols())\n\treturn\n}", "func (h *Howdoi) Execute() {\n\tflag.Parse()\n\n\tif h.ShowHelp {\n\t\tfmt.Println(help)\n\t\tos.Exit(0)\n\t}\n\n\tif h.ShowVersion {\n\t\tfmt.Println(version)\n\t\tos.Exit(0)\n\t}\n\n\t// position must be > 0\n\tif h.Position == 0 {\n\t\th.Position = 1\n\t}\n\n\terr := h.sanitizeQuestion(flag.Args())\n\tif err != nil {\n\t\tfmt.Println(help)\n\t\tos.Exit(1)\n\t}\n\n\tlinks, err := h.getLinks()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tanswer, err := h.getAnswer(links)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(answer)\n}", "func main() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tapp := cliapp.NewApp()\n\tapp.Version = \"1.0.3\"\n\tapp.Description = \"this is my cli application\"\n\n\tapp.SetVerbose(cliapp.VerbDebug)\n\t// app.DefaultCmd(\"exampl\")\n\n\tapp.Add(cmd.GitCommand())\n\t// app.Add(cmd.ColorCommand())\n\tapp.Add(builtin.GenShAutoComplete())\n\t// fmt.Printf(\"%+v\\n\", cliapp.CommandNames())\n\tapp.Run()\n}", "func main() {\n\terr := app.Execute()\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error while Execute lookatch\")\n\t}\n}", "func main() {\n\t// test mode\n\tif len(os.Args) >= 2 && os.Args[1] == \"test\" {\n\t\ttestCmdSet.Parse(os.Args[2:])\n\t\tif path := testCmdSet.Arg(0); path != \"\" {\n\t\t\texitCode := runTest(path)\n\t\t\tos.Exit(exitCode)\n\t\t}\n\t}\n\n\t// normal mode\n\tflag.Parse()\n\n\t// show version\n\tif *version {\n\t\tshowVersion()\n\t\tos.Exit(0)\n\t}\n\n\tsrc := \"\"\n\tif *jargon {\n\t\tsrc = readJargon()\n\t}\n\n\t// run one-liner\n\tif *oneLiner != \"\" {\n\t\tsrc += wrapSource(*oneLiner, *readsLines, *readsAndWritesLines)\n\t\texitCode := run(src, object.StrFileName)\n\t\tos.Exit(exitCode)\n\t}\n\n\tif srcFileName := flag.Arg(0); srcFileName != \"\" {\n\t\tfileSrc, exitCode := runscript.ReadFile(srcFileName)\n\t\tif exitCode != 0 {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\t\tsrc += fileSrc\n\n\t\texitCode = run(src, srcFileName)\n\t\tos.Exit(exitCode)\n\t}\n\n\trunRepl(src)\n}", "func Exec(name string, arg ...string) error {\n\tcmd := exec.Command(name, arg...)\n\tif len(cmdExePath) != 0 {\n\t\tcmd.Dir = cmdExePath\n\t\tcmdExePath = \"\"\n\t}\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Fatal(\"error: \", string(output), err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func main() {\n\ta := createHelp()\n\terr := a.Run(os.Args)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}", "func main() {\n\tfmt.Println(\"=======================================\")\n\tfmt.Println(\"This is a TeamSpeak3 plugin, do not run this as a CLI application!\")\n\tfmt.Println(\"Args were: \", os.Args)\n\tfmt.Println(\"=======================================\")\n}", "func main() {\n\tprocess_command_line()\n}", "func Console(args ...string) {\n cfg.StartCmd = \"/bin/bash -c\"\n cfg.QuotedOpts = \"'\" + cfg.Console + \"'\"\n runInteractive(\"run\", settingsToParams(0, false)...)\n}", "func main() {\n\tvar options core.Options\n\n\tespressoCmd := &cobra.Command{\n\t\tUse: \"espresso\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn cmd.Help()\n\t\t},\n\t}\n\n\tbuildCmd := &cobra.Command{\n\t\tUse: \"build <PATH>\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tbuildPath := args[0]\n\t\t\tvar s config.Site\n\n\t\t\tif err := config.FromFile(buildPath, settingsFile, &s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn core.RunBuild(buildPath, &s, &options)\n\t\t},\n\t}\n\n\tbuildCmd.Flags().StringVarP(&options.OutputDir, \"output-dir\", \"o\", \"\", `Path to the target directory`)\n\tbuildCmd.Flags().BoolVar(&options.RenderRSS, \"render-rss\", false, `Render an Atom RSS feed`)\n\n\tversionCmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tfmt.Printf(\"Espresso %s\\n\", version)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tespressoCmd.AddCommand(buildCmd)\n\tespressoCmd.AddCommand(versionCmd)\n\n\tif err := espressoCmd.Execute(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func what(s selection, args []string) {\n\tfmt.Println(runWithStdin(s.archive(), \"guru\", \"-modified\", \"what\", s.pos()))\n}", "func Exec(client *Client, args []string, timeoutSecs int) (*pb.ExecResult, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSecs)*time.Second)\n\tdefer cancel()\n\n\trequest := &pb.ExecRequest{\n\t\tExecutable: args[0],\n\t\tArgs: args[1:],\n\t}\n\n\treturn client.Exec(ctx, request)\n}", "func Exec(command string, args ...string) (string, error) {\n\tLogger.DebugC(color.Yellow, \"$ %v %v\", command, strings.Join(args, \" \"))\n\tb, err := exec.Command(command, args...).CombinedOutput()\n\tLogger.Debug(\"%s\\n\", b)\n\treturn string(b), err\n}", "func main() {\n\tflag.Parse()\n\tvar ex execer.Execer\n\tswitch *execerType {\n\tcase \"sim\":\n\t\tex = execers.NewSimExecer()\n\tcase \"os\":\n\t\tex = os_exec.NewExecer()\n\tdefault:\n\t\tlog.Fatalf(\"Unknown execer type %v\", *execerType)\n\t}\n\n\ttempDir, err := temp.TempDirDefault()\n\tif err != nil {\n\t\tlog.Fatal(\"error creating temp dir: \", err)\n\t}\n\t//defer os.RemoveAll(tempDir.Dir) //TODO: this may become necessary if we start testing with larger snapshots.\n\n\ttmp, err := temp.NewTempDir(\"\", \"daemon\")\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot create tmp dir: \", err)\n\t}\n\n\toutputCreator, err := runners.NewHttpOutputCreator(tempDir, \"\")\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot create OutputCreator: \", err)\n\t}\n\tfiler := snapshots.MakeTempFiler(tempDir)\n\tr := runners.NewQueueRunner(ex, filer, outputCreator, tmp, *qLen)\n\th := server.NewHandler(r, filer, 50*time.Millisecond)\n\ts, err := server.NewServer(h)\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot create Scoot server: \", err)\n\t}\n\terr = s.ListenAndServe()\n\tif err != nil {\n\t\tlog.Fatal(\"Error serving Scoot Daemon: \", err)\n\t}\n}", "func Exec(name string, args ...string) (output []byte, err error) {\n\treturn exec.Command(name, args...).Output()\n}", "func Exec(t testing.TB, cmd *cobra.Command, stdIn io.Reader, args ...string) (string, string, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tt.Cleanup(cancel)\n\n\treturn ExecCtx(ctx, cmd, stdIn, args...)\n}", "func main() {\n\tcli.CommandLineInterface()\n}", "func executeShell(ctx context.Context, context ActionExecutionContext) error {\n\t//log.Printf(\"Exec: %s\", context.Action.Shell)\n\t//cmdAndArgs := strings.Split(s.Shell, \" \")\n\t//cmd := cmdAndArgs[0]\n\t//args := cmdAndArgs[1:]\n\tshuttlePath, _ := filepath.Abs(filepath.Dir(os.Args[0]))\n\n\tcmdOptions := go_cmd.Options{\n\t\tBuffered: false,\n\t\tStreaming: true,\n\t}\n\n\texecCmd := go_cmd.NewCmdOptions(cmdOptions, \"sh\", \"-c\", \"cd '\"+context.ScriptContext.Project.ProjectPath+\"'; \"+context.Action.Shell)\n\n\t//execCmd := exec.Command(\"sh\", \"-c\", context.Action.Shell)\n\texecCmd.Env = os.Environ()\n\tfor name, value := range context.ScriptContext.Args {\n\t\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"%s=%s\", name, value))\n\t}\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"plan=%s\", context.ScriptContext.Project.LocalPlanPath))\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"tmp=%s\", context.ScriptContext.Project.TempDirectoryPath))\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"project=%s\", context.ScriptContext.Project.ProjectPath))\n\t// TODO: Add project path as a shuttle specific ENV\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"PATH=%s\", shuttlePath+string(os.PathListSeparator)+os.Getenv(\"PATH\")))\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"SHUTTLE_PLANS_ALREADY_VALIDATED=%s\", context.ScriptContext.Project.LocalPlanPath))\n\n\tdoneChan := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneChan)\n\t\tfor execCmd.Stdout != nil || execCmd.Stderr != nil {\n\t\t\tselect {\n\t\t\tcase line, open := <-execCmd.Stdout:\n\t\t\t\tif !open {\n\t\t\t\t\texecCmd.Stdout = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcontext.ScriptContext.Project.UI.Infoln(\"%s\", line)\n\t\t\tcase line, open := <-execCmd.Stderr:\n\t\t\t\tif !open {\n\t\t\t\t\texecCmd.Stderr = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcontext.ScriptContext.Project.UI.Errorln(\"%s\", line)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Run and wait for Cmd to return, discard Status\n\tcontext.ScriptContext.Project.UI.Titleln(\"shell: %s\", context.Action.Shell)\n\n\t// stop cmd if context is cancelled\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\terr := execCmd.Stop()\n\t\t\tif err != nil {\n\t\t\t\tcontext.ScriptContext.Project.UI.Errorln(\"Failed to stop script '%s': %v\", context.Action.Shell, err)\n\t\t\t}\n\t\tcase <-doneChan:\n\t\t}\n\t}()\n\n\tselect {\n\tcase status := <-execCmd.Start():\n\t\t<-doneChan\n\t\tif status.Exit > 0 {\n\t\t\treturn errors.NewExitCode(4, \"Failed executing script `%s`: shell script `%s`\\nExit code: %v\", context.ScriptContext.ScriptName, context.Action.Shell, status.Exit)\n\t\t}\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func Shell(t *testing.T, name string, arg ...string) {\n\tt.Helper()\n\n\tbin, err := exec.LookPath(name)\n\tif err != nil {\n\t\tt.Skipf(\"skipping, binary %q not found: %v\", name, err)\n\t}\n\n\tt.Logf(\"$ %s %v\", bin, arg)\n\n\tcmd := exec.Command(bin, arg...)\n\tif err := cmd.Start(); err != nil {\n\t\tt.Fatalf(\"failed to start command %q: %v\", name, err)\n\t}\n\n\tif err := cmd.Wait(); err != nil {\n\t\t// Shell operations in these tests require elevated privileges.\n\t\tif cmd.ProcessState.ExitCode() == 1 /* unix.EPERM */ {\n\t\t\tt.Skipf(\"skipping, permission denied: %v\", err)\n\t\t}\n\n\t\tt.Fatalf(\"failed to wait for command %q: %v\", name, err)\n\t}\n}", "func main() {\n\t// os.Args provides access to raw command-line arguments. Note that the first value in this\n\t// slice is the path to the program, and os.Args[1:] holds the arguments to the program.\n\targsWithProg := os.Args\n\targsWithoutProg := os.Args[1:]\n\n\t// You can get individual args with normal indexing.\n\targ := os.Args[3]\n\n\tfmt.Println(argsWithProg)\n\tfmt.Println(argsWithoutProg)\n\tfmt.Println(arg)\n}", "func main() {\n\tapp := &cli.App{\n\t\tName: \"RULEX, a lightweight iot data rule gateway\",\n\t\tUsage: \"http://rulex.ezlinker.cn\",\n\t\tCommands: []*cli.Command{\n\t\t\t{\n\t\t\t\tName: \"run\",\n\t\t\t\tUsage: \"rulex run [path of 'rulex.db']\",\n\t\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\t\tutils.ShowBanner()\n\t\t\t\t\tif c.Args().Len() > 0 {\n\t\t\t\t\t\tlog.Info(\"Use config db:\", c.Args().Get(0))\n\t\t\t\t\t\tengine.RunRulex(c.Args().Get(0))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tengine.RunRulex(\"rulex.db\")\n\t\t\t\t\t}\n\t\t\t\t\tlog.Debug(\"Run rulex successfully.\")\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t},\n\t\t\t// version\n\t\t\t{\n\t\t\t\tName: \"version\",\n\t\t\t\tUsage: \"rulex version\",\n\t\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\t\tfmt.Println(\"Current Version is: \" + typex.DefaultVersion.Version)\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (self *Build) exec(moduleLabel core.Label, fileType core.FileType) error {\n\tthread := createThread(self, moduleLabel, fileType)\n\n\tsourceData, err := self.sourceFileReader(moduleLabel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to execute %v: read failed: %v\", moduleLabel, err)\n\t}\n\n\t_, err = starlark.ExecFile(thread, moduleLabel.String(), sourceData,\n\t\tbuiltins.InitialGlobals(fileType))\n\treturn err\n}", "func Main() {\n\n\tcheckSupportArch()\n\n\tif len(os.Args) > 1 {\n\t\tcmd := os.Args[1]\n\t\tfmt.Println(cmd)\n\t}\n\n\tstartEtcdOrProxyV2()\n}", "func (flower *Flower) Exec(commandName string, capture bool, args []string) (string, error) {\n\tflowerCommandData, err := flower.GetFlowerCommandData(commandName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar command []string\n\tif flowerCommandData.Workdir != \"\" {\n\t\tcommand = append([]string{\"cd\", flowerCommandData.Workdir, \"&&\"})\n\t}\n\n\tcommand = append([]string{flowerCommandData.Bin})\n\tfor _, arg := range args {\n\t\tcommand = append([]string{arg})\n\t}\n\n\tvar dockerExecOptions *DockerExecOptions\n\tswitch flowerCommandData.DockerExecOptions {\n\tcase nil:\n\t\tdockerExecOptions = flowerCommandData.DockerExecOptions\n\tdefault:\n\t\tdockerExecOptions = &DockerExecOptions{}\n\t}\n\n\treturn flower.Container.Exec(command, dockerExecOptions, capture)\n}", "func Execute(ver string) {\n\tVERSION = version{\n\t\tVersion: ver,\n\t\tRedmineAPIVersion: \"3.3+\",\n\t}\n\n\tRClient = &client.Client{\n\t\tHTTPClient: &http.Client{},\n\t\tUserAgent: fmt.Sprintf(\"arcli/v%s\", VERSION.Version),\n\t}\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func (c *Tool) Exec() ([]byte, error) {\n\treturn c.Run()\n}", "func ExecLine(cmdLine string, workDir ...string) (string, error) {\n\tp := cmdline.NewParser(cmdLine)\n\n\t// create a new Cmd instance\n\tcmd := p.NewExecCmd()\n\tif len(workDir) > 0 {\n\t\tcmd.Dir = workDir[0]\n\t}\n\n\tbs, err := cmd.Output()\n\treturn string(bs), err\n}", "func sysExec(args ...OBJ) OBJ {\n\tif len(args) < 1 {\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tvar command string\n\tswitch c := args[0].(type) {\n\tcase *object.String:\n\t\tcommand = c.Value\n\tdefault:\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tif len(command) < 1 {\n\t\treturn NewError(\"`sys.exec` expected string, got invalid argument\")\n\t}\n\t// split the command\n\ttoExec := splitCommand(command)\n\tcmd := exec.Command(toExec[0], toExec[1:]...)\n\n\t// get the result\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout = &outb\n\tcmd.Stderr = &errb\n\terr := cmd.Run()\n\n\t// If the command exits with a non-zero exit-code it\n\t// is regarded as a failure. Here we test for ExitError\n\t// to regard that as a non-failure.\n\tif err != nil && err != err.(*exec.ExitError) {\n\t\tfmt.Printf(\"Failed to run '%s' -> %s\\n\", command, err.Error())\n\t\treturn &object.Error{Message: \"Failed to run command!\"}\n\t}\n\n\t// The result-objects to store in our hash.\n\tstdout := &object.String{Value: outb.String()}\n\tstderr := &object.String{Value: errb.String()}\n\n\treturn NewHash(StringObjectMap{\n\t\t\"stdout\": stdout,\n\t\t\"stderr\": stderr,\n\t})\n}", "func (o *CreateQuickstartOptions) Run() error {\n\tinstallOpts := InstallOptions{\n\t\tCommonOptions: CommonOptions{\n\t\t\tFactory: o.Factory,\n\t\t\tOut: o.Out,\n\t\t},\n\t}\n\tuserAuth, err := installOpts.getGitUser(\"git username to create the quickstart\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauthConfigSvc, err := o.Factory.CreateGitAuthConfigService()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar server *auth.AuthServer\n\tconfig := authConfigSvc.Config()\n\tif o.GitHub {\n\t\tserver = config.GetOrCreateServer(gits.GitHubHost)\n\t} else {\n\t\tif o.GitHost != \"\" {\n\t\t\tserver = config.GetOrCreateServer(o.GitHost)\n\t\t} else {\n\t\t\tserver, err = config.PickServer(\"Pick the git server to search for repositories\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tif server == nil {\n\t\treturn fmt.Errorf(\"no git server provided\")\n\t}\n\n\to.GitProvider, err = gits.CreateProvider(server, userAuth)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmodel, err := o.LoadQuickstarts()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to load quickstarts: %s\", err)\n\t}\n\tq, err := model.CreateSurvey(&o.Filter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif q == nil {\n\t\treturn fmt.Errorf(\"no quickstart chosen\")\n\t}\n\n\tdir := o.OutDir\n\tif dir == \"\" {\n\t\tdir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tgenDir, err := o.createQuickstart(q, dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Printf(\"Created project at %s\\n\\n\", util.ColorInfo(genDir))\n\n\to.CreateProjectOptions.ImportOptions.GitProvider = o.GitProvider\n\to.Organisation = userAuth.Username\n\treturn o.ImportCreatedProject(genDir)\n}", "func execute_plugin(filename string, input []byte) []byte {\n cmd := filename\n arg := string(input)\n out, err := exec.Command(cmd, arg).Output()\n if err != nil {\n println(err.Error())\n return nil\n }\n return out\n}", "func Action(c *cli.Context) {\n\texec := c.String(\"exec\")\n\tfmt.Printf(\"Action: %v\\n\", exec)\n}", "func (exec *Executhor) Exec(execArg []string) {\n\tif exec.execBuiltin(execArg) == nil {\n\t\treturn\n\t}\n\tpath, err := exec.getBinaryPath(execArg[0])\n\tif err == nil {\n\t\tpid := C.fork()\n\t\tif pid != 0 {\n\t\t\tvar status C.int\n\t\t\tC.wait(&status)\n\t\t} else {\n\t\t\tsyscall.Exec(path, execArg, exec.env.GetEnv())\n\t\t}\n\t} else {\n\t\tfmt.Println(err)\n\t}\n}", "func SystemExec(command string, args []string) *BuildahTestSession {\n\tfmt.Printf(\"Running: %s %s\\n\", command, strings.Join(args, \" \"))\n\tc := exec.Command(command, args...)\n\tsession, err := gexec.Start(c, GinkgoWriter, GinkgoWriter)\n\tif err != nil {\n\t\tFail(fmt.Sprintf(\"unable to run command: %s %s\", command, strings.Join(args, \" \")))\n\t}\n\treturn &BuildahTestSession{session}\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func Exec() error {\n\treturn scoreboardCmd.Execute()\n}", "func main() {\n\tcmd := parseCmd()\n\tif cmd.versionFlag {\n\t\tfmt.Println(\"hyf-jvm-version 0.0.1\")\n\t} else if cmd.helpFlag || cmd.class == \"\" {\n\t\tprintUsage()\n\t} else {\n\t\tstartJVM(cmd)\n\t}\n\t//entry := &Mylist{entry:make([]string,10)}\n\t//findAllFile(\"./\",entry)\n\t//fmt.Println(entry.entry)\n\t//fmt.Println(len(entry.entry))\n\n}", "func (c *actionTests) actionExec(t *testing.T) {\n\te2e.EnsureImage(t, c.env)\n\n\tuser := e2e.CurrentUser(t)\n\n\t// Create a temp testfile\n\ttmpfile, err := ioutil.TempFile(\"\", \"testSingularityExec.tmp\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(tmpfile.Name()) // clean up\n\n\ttestfile, err := tmpfile.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\targv []string\n\t\texit int\n\t}{\n\t\t{\n\t\t\tname: \"NoCommand\",\n\t\t\targv: []string{c.env.ImagePath},\n\t\t\texit: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"True\",\n\t\t\targv: []string{c.env.ImagePath, \"true\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"TrueAbsPAth\",\n\t\t\targv: []string{c.env.ImagePath, \"/bin/true\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"False\",\n\t\t\targv: []string{c.env.ImagePath, \"false\"},\n\t\t\texit: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"FalseAbsPath\",\n\t\t\targv: []string{c.env.ImagePath, \"/bin/false\"},\n\t\t\texit: 1,\n\t\t},\n\t\t// Scif apps tests\n\t\t{\n\t\t\tname: \"ScifTestAppGood\",\n\t\t\targv: []string{\"--app\", \"testapp\", c.env.ImagePath, \"testapp.sh\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestAppBad\",\n\t\t\targv: []string{\"--app\", \"fakeapp\", c.env.ImagePath, \"testapp.sh\"},\n\t\t\texit: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-d\", \"/scif\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-d\", \"/scif/apps\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-d\", \"/scif/data\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-d\", \"/scif/apps/foo\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-d\", \"/scif/apps/bar\"},\n\t\t\texit: 0,\n\t\t},\n\t\t// blocked by issue [scif-apps] Files created at install step fall into an unexpected path #2404\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-f\", \"/scif/apps/foo/filefoo.exec\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-f\", \"/scif/apps/bar/filebar.exec\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-d\", \"/scif/data/foo/output\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"ScifTestfolderOrg\",\n\t\t\targv: []string{c.env.ImagePath, \"test\", \"-d\", \"/scif/data/foo/input\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"WorkdirContain\",\n\t\t\targv: []string{\"--contain\", c.env.ImagePath, \"test\", \"-f\", tmpfile.Name()},\n\t\t\texit: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"Workdir\",\n\t\t\targv: []string{\"--workdir\", \"testdata\", c.env.ImagePath, \"test\", \"-f\", tmpfile.Name()},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"PwdGood\",\n\t\t\targv: []string{\"--pwd\", \"/etc\", c.env.ImagePath, \"true\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"Home\",\n\t\t\targv: []string{\"--home\", pwd + \"testdata\", c.env.ImagePath, \"test\", \"-f\", tmpfile.Name()},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"HomePath\",\n\t\t\targv: []string{\"--home\", \"/tmp:/home\", c.env.ImagePath, \"test\", \"-f\", \"/home/\" + testfile.Name()},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"HomeTmp\",\n\t\t\targv: []string{\"--home\", \"/tmp\", c.env.ImagePath, \"true\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"HomeTmpExplicit\",\n\t\t\targv: []string{\"--home\", \"/tmp:/home\", c.env.ImagePath, \"true\"},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"UserBind\",\n\t\t\targv: []string{\"--bind\", \"/tmp:/var/tmp\", c.env.ImagePath, \"test\", \"-f\", \"/var/tmp/\" + testfile.Name()},\n\t\t\texit: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"NoHome\",\n\t\t\targv: []string{\"--no-home\", c.env.ImagePath, \"ls\", \"-ld\", user.Dir},\n\t\t\texit: 2,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tc.env.RunSingularity(\n\t\t\tt,\n\t\t\te2e.AsSubtest(tt.name),\n\t\t\te2e.WithProfile(e2e.UserProfile),\n\t\t\te2e.WithCommand(\"exec\"),\n\t\t\te2e.WithDir(\"/tmp\"),\n\t\t\te2e.WithArgs(tt.argv...),\n\t\t\te2e.ExpectExit(tt.exit),\n\t\t)\n\t}\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func executeLaunch() {\n\tfmt.Println(\"Launching ...\")\n}", "func (h Client) Exec(arg ...string) (string, string, error) {\n\tcmd := exec.Command(h.HelmExecutable, arg...)\n\n\tklog.V(8).Infof(\"running helm command: %v\", cmd)\n\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\n\tcmd.Stdout = &stdoutBuf\n\tcmd.Stderr = &stderrBuf\n\n\terr := cmd.Run()\n\toutStr, errStr := stdoutBuf.String(), stderrBuf.String()\n\tif err != nil {\n\t\tklog.V(8).Infof(\"stdout: %s\", outStr)\n\t\tklog.V(7).Infof(\"stderr: %s\", errStr)\n\t\treturn \"\", errStr, fmt.Errorf(\"exit code %d running command %s\", cmd.ProcessState.ExitCode(), cmd.String())\n\t}\n\n\treturn outStr, errStr, nil\n}", "func main() {\n\tcmd.Run()\n}", "func main() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func main() {\n\texecuteReadFile()\n\tfmt.Println(\"Nunca me ejecutare\")\n}", "func (t *Test) Exec() (err error) {\n\ts, e, err := Exec(t.Command)\n\tif err != nil {\n\t\tt.Result.Error(err)\n\t\treturn err\n\t}\n\tt.stdOut = s\n\tt.stdErr = e\n\tt.Result.Success()\n\treturn nil\n}", "func printHint() {\n\tprint(\"orbi - Embeddable Interactive ORuby Shell\\n\\n\")\n}", "func Exec(name string, arg ...string) error {\n\tcmd := exec.Command(name, arg...)\n\tvar outBuffer = new(bytes.Buffer)\n\tvar errBuffer = new(bytes.Buffer)\n\tif viper.GetBool(\"verbose\") {\n\t\t_, err := fmt.Fprintf(os.Stdout, \"Executing command: %s\\n\", strings.Join(append([]string{name}, arg...), \" \"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stdout\n\t} else {\n\t\tcmd.Stdout = outBuffer\n\t\tcmd.Stderr = errBuffer\n\t}\n\tif err := cmd.Run(); err != nil {\n\t\tlines := strings.Split(outBuffer.String(), \"\\n\")\n\t\tfiltered := []string{errBuffer.String()}\n\t\tfor _, x := range lines {\n\t\t\tif strings.HasPrefix(x, \"fatal:\") {\n\t\t\t\tfiltered = append(filtered, x)\n\t\t\t}\n\t\t}\n\n\t\treturn fmt.Errorf(strings.Join(filtered, \"\\n\"))\n\t}\n\treturn nil\n}", "func execSynopsis(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := doc.Synopsis(args[0].(string))\n\tp.Ret(1, ret)\n}", "func (n *mockAgent) exec(sandbox *Sandbox, c Container, cmd types.Cmd) (*Process, error) {\n\treturn nil, nil\n}", "func main() {\n\tflag.Parse()\n\tif err := echoargs(!*n, *s, flag.Args()); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"echo %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func newSimpleExec(code int, err error) simpleExec {\n\treturn simpleExec{code: code, err: err}\n}", "func Execute() {\n\n\tif len(flag.Args()) == 0 {\n\t\tshowHelp(nil)\n\t\tos.Exit(1)\n\t}\n\n\t// Check if the first argument is a native command\n\tfor _, nc := range nativeCmds {\n\t\tif nc.ID == flag.Arg(0) {\n\t\t\tnc.Cmd(flag.Args()[1:]...)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\tfor _, a := range flag.Args() {\n\t\tartifact.Call(a)\n\t}\n}", "func Exec(exe string, args ...string) (outStr string, err error) {\n\tvar (\n\t\tcmd *exec.Cmd\n\t\tout []byte\n\t)\n\n\tif exe == \"docker-compose\" {\n\t\targs = append(dockerComposeDefaultArgs(), args...)\n\t}\n\n\tcmd = exec.Command(exe, args...)\n\tcmd.Env = os.Environ()\n\tcmd.Stdin = os.Stdin\n\n\tout, err = cmd.CombinedOutput()\n\toutStr = strings.TrimSpace(string(out))\n\treturn\n}", "func (x *InstallCommand) Exec(args []string) error {\n\terr := fmt.Errorf(\"Sample warning: Instance not found\")\n\tclis.WarnOn(\"Install, Exec\", err)\n\t// or,\n\t// clis.AbortOn(\"Doing Install\", err)\n\treturn nil\n}", "func main() {\n\n\tflag.Parse()\n\tif *arguments.help || *arguments.url == \"\" || *arguments.querySelector == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\tvar err error\n\n\t// create context\n\t// > go - How to use Chrome headless with chromedp? - Stack Overflow\n\t// > https://stackoverflow.com/questions/44067030/how-to-use-chrome-headless-with-chromedp\n\t// > How to run chromedp on foreground? · Issue #495 · chromedp/chromedp\n\t// > https://github.com/chromedp/chromedp/issues/495\n\tctxt, cancel := chromedp.NewExecAllocator(context.Background(), append(\n\t\tchromedp.DefaultExecAllocatorOptions[:],\n\t\tchromedp.Flag(\"headless\", !*arguments.noHeadless),\n\t\tchromedp.Flag(\"disable-gpu\", true),\n\t\tchromedp.Flag(\"no-first-run\", true),\n\t\tchromedp.Flag(\"no-default-browser-check\", true),\n\t)...,\n\t)\n\tdefer cancel()\n\tloggingContextOption := chromedp.WithLogf(log.Printf)\n\tif *arguments.debug {\n\t\t// debug log mode\n\t\tloggingContextOption = chromedp.WithDebugf(log.Printf)\n\t}\n\tctxt, cancel = chromedp.NewContext(ctxt, loggingContextOption)\n\tdefer cancel()\n\t// handle kill signal\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, os.Kill, os.Interrupt)\n\tgo func() {\n\t\t<-signals\n\t\tcancel()\n\t\tos.Exit(0)\n\t}()\n\n\t// run task list\n\tvar res string\n\terr = chromedp.Run(ctxt, createTasks(*arguments.url, *arguments.querySelector, &res))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"\\n\\nresult: \\n%s\\n\\n\\n\", res)\n}", "func combCli(cmd string, args ...string) ([]byte, error) {\n\targs = append([]string{cmd}, args...)\n\tfmt.Printf(\"args=%s\\n\", args)\n\treturn exec.Command(\"./comb\", args...).Output()\n}", "func (c *Cmd) Exec(args []string) error {\n\tc.flag.Uint64Var(&version, \"version\", 0, \"\")\n\tc.flag.Parse(args)\n\n\t// Load config\n\tif driver != nil {\n\t\tconfig = &core.Config{\n\t\t\tData: make(map[string]core.Internal),\n\t\t}\n\t\tconfig.Data[\"\"] = core.Internal{\n\t\t\tDriver: *driver,\n\t\t\tDsn: *dsn,\n\t\t\tDirectory: *directory,\n\t\t}\n\t} else {\n\t\tconfig = core.MustNewConfig(*dirPath).WithEnv(*env)\n\t}\n\n\treturn c.Run(c, c.flag.Args()...)\n}", "func main() {\n\tbasedir := flag.String(\"basedir\", \"/tmp\", \"basedir of tmp C binary\")\n\tinput := flag.String(\"input\", \"<input>\", \"test case input\")\n\texpected := flag.String(\"expected\", \"<expected>\", \"test case expected\")\n\ttimeout := flag.String(\"timeout\", \"2000\", \"timeout in milliseconds\")\n\tmemory := flag.String(\"memory\", \"256\", \"memory limitation in MB\")\n\tflag.Parse()\n\n\tresult, u := new(model.Result), uuid.NewV4()\n\tif err := sandbox.InitCGroup(strconv.Itoa(os.Getpid()), u.String(), *memory); err != nil {\n\t\tresult, _ := json.Marshal(result.GetRuntimeErrorTaskResult())\n\t\t_, _ = os.Stdout.Write(result)\n\t\tos.Exit(0)\n\t}\n\n\tcmd := reexec.Command(\"justiceInit\", *basedir, *input, *expected, *timeout, *memory)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tCloneflags: syscall.CLONE_NEWNS |\n\t\t\tsyscall.CLONE_NEWUTS |\n\t\t\tsyscall.CLONE_NEWIPC |\n\t\t\tsyscall.CLONE_NEWPID |\n\t\t\tsyscall.CLONE_NEWNET |\n\t\t\tsyscall.CLONE_NEWUSER,\n\t\tUidMappings: []syscall.SysProcIDMap{\n\t\t\t{\n\t\t\t\tContainerID: 0,\n\t\t\t\tHostID: os.Getuid(),\n\t\t\t\tSize: 1,\n\t\t\t},\n\t\t},\n\t\tGidMappings: []syscall.SysProcIDMap{\n\t\t\t{\n\t\t\t\tContainerID: 0,\n\t\t\t\tHostID: os.Getgid(),\n\t\t\t\tSize: 1,\n\t\t\t},\n\t\t},\n\t}\n\n\tif err := cmd.Run(); err != nil {\n\t\tresult, _ := json.Marshal(result.GetRuntimeErrorTaskResult())\n\t\t_, _ = os.Stderr.WriteString(fmt.Sprintf(\"%s\\n\", err.Error()))\n\t\t_, _ = os.Stdout.Write(result)\n\t}\n\n\tos.Exit(0)\n}", "func main() {\n\tlog.Printf(\"Build var 'version' is: %s\", version)\n\tlog.Printf(\"Build var 'time' is: %s\", buildDate)\n\tcmd.Execute()\n}", "func (v *DevbindMock) Exec(args ...string) ([]byte, error) {\n\tif debugMocks {\n\t\tfmt.Printf(\"MOCK [Devind received: ./dpdk-devbind.py %s]\\n\", args)\n\t}\n\tv.receivedArgs = append(v.receivedArgs, args)\n\n\tif len(v.devbindResults) == 0 {\n\t\treturn nil, errors.New(\"DevbindMock - results not set\")\n\t}\n\n\tout, err := v.devbindResults[0].resultOutcome, v.devbindResults[0].resultError\n\tv.devbindResults = v.devbindResults[1:]\n\tif debugMocks {\n\t\tfmt.Printf(\"MOCK [Devind response: %s]\\n\", out)\n\t}\n\treturn []byte(out), err\n}", "func Exec() {\n\tcmd := &cobra.Command{\n\t\tUse: \"func\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Fprintln(os.Stderr, cmd.UsageString())\n\t\t},\n\t}\n\n\tcmd.AddCommand(versionCommand())\n\tcmd.AddCommand(generateCommand())\n\tcmd.AddCommand(deployCommand())\n\n\t_ = cmd.Execute()\n}", "func main() {\n\tlog.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)\n\tif err := cmd.RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}" ]
[ "0.6264366", "0.6004395", "0.5772538", "0.5772538", "0.5772538", "0.5772538", "0.5772538", "0.5772538", "0.5772538", "0.57653713", "0.5761175", "0.57583976", "0.5720655", "0.566654", "0.5643779", "0.562086", "0.55483186", "0.5535528", "0.55332303", "0.553222", "0.55076367", "0.5468675", "0.54634637", "0.544216", "0.54124343", "0.534704", "0.53363276", "0.53195477", "0.5306151", "0.5298281", "0.5293399", "0.5273138", "0.523621", "0.5234418", "0.5233896", "0.52326", "0.523069", "0.52231115", "0.5217501", "0.52116936", "0.5206525", "0.51972646", "0.517387", "0.5171835", "0.51363057", "0.5132878", "0.51243484", "0.51170594", "0.5099081", "0.5097317", "0.50832134", "0.5062289", "0.505513", "0.505393", "0.5053473", "0.50520456", "0.50493294", "0.5042732", "0.5040086", "0.5039902", "0.50372034", "0.5036177", "0.5027414", "0.5026401", "0.50256217", "0.50169826", "0.50147915", "0.50063646", "0.5004885", "0.5003954", "0.5001463", "0.49979585", "0.4991917", "0.49889475", "0.49888232", "0.4979754", "0.49786747", "0.49782434", "0.49758345", "0.4965617", "0.49637404", "0.4954164", "0.4952816", "0.49470073", "0.4933595", "0.4928142", "0.49203265", "0.4918156", "0.4911783", "0.49057597", "0.49042448", "0.4896785", "0.48964483", "0.48952985", "0.48869058", "0.48863107", "0.48862132", "0.48818502", "0.48715326", "0.48653919" ]
0.7113928
0
ExecLine quick exec an command line string
ExecLine быстрое выполнение командной строки
func ExecLine(cmdLine string, workDir ...string) (string, error) { p := cmdline.NewParser(cmdLine) // create a new Cmd instance cmd := p.NewExecCmd() if len(workDir) > 0 { cmd.Dir = workDir[0] } bs, err := cmd.Output() return string(bs), err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func QuickExec(cmdLine string, workDir ...string) (string, error) {\n\treturn ExecLine(cmdLine, workDir...)\n}", "func (ui *UI) exec(ctx context.Context, line string, reqCh chan execReq) int {\n\treq := execReq{\n\t\tctx: ctx,\n\t\tline: line,\n\t\tui: ui,\n\t\trespCh: make(chan int),\n\t}\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn 0\n\tcase reqCh <- req:\n\t}\n\treturn <-req.respCh\n}", "func (cl *Client) ExecString(cmd string, args ...interface{}) (string, error) {\n\tvar s string\n\terr := cl.Conn(func(c *Conn) error {\n\t\tvar err error\n\t\ts, err = c.ExecString(cmd, args...)\n\t\treturn err\n\t})\n\treturn s, err\n}", "func Line(cmd *exec.Cmd) string {\n\treturn strings.Join(cmd.Args, \" \")\n}", "func WrapExec(cmd string, args []String, nArg uint32) (status syscall.Status){\n\n\n\tpath := \"/programs/\"+cmd\n\n\tif nArg == 0 {\n\n\t\tstatus = altEthos.Exec(path)\n\n\t} else if nArg == 1 {\n\n\t\tstatus = altEthos.Exec(path, &args[0])\n\n\t} else if nArg == 2 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1])\n\n\t} else if nArg == 3 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1], &args[2])\n\n\t} else if nArg == 4 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1], &args[2], &args[3])\n\n\t}\n\n\treturn\n\n}", "func ExecCommand(commandLine string) (*exec.Cmd, error) {\n\n\tvar args, err = shellquote.Split(commandLine)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exec.Command(args[0], args[1:]...), nil // #nosec\n\n}", "func commandLine( line []byte, data string, quote bool ) []byte {\n\t// Empty data ?\n\tif len( data ) == ( 0 ) {\n\t\tif !( quote ) { // Nothing to do\n\t\t\treturn line\n\t\t}\n\t}\n\t// Argument ?\n\tif ( !quote ) {\n\t\tdata = strings.TrimSpace( data )\n\t} else if len( data ) > ( 0 ) {\n\t\tquote = ( -1 < strings.IndexByte( data, ' ' ))\n\t}\n\n\tif ( quote ) { // Begin argument !\n\t\tline = append( line, '\\'' )\n\t}\n\n\tvar r rune\n\tfor off := 0; len( data ) > 0; data = data[off:] {\n\t\tr, off = rune( data[0] ), 1\n\t\tif r >= utf8.RuneSelf {\n\t\t\tr, off = utf8.DecodeRuneInString(data)\n\t\t}\n\t\tif ( off == 1 ) && ( r == utf8.RuneError ) {\n\t\t\tline = append( line, `\\x`...)\n\t\t\tline = append( line, lowerhex[ data[0]>>4 ])\n\t\t\tline = append( line, lowerhex[ data[0]&0xF ])\n\t\t\tcontinue\n\t\t}\n\t\tline = commandRune( line, r, quote )\n\t}\n\n\tif ( quote ) { // End argument !\n\t\tline = append( line, '\\'' )\n\t}\n\t\n\treturn line\n}", "func processLine(cmdLine string) {\n\tcmdLine = strings.TrimSpace(cmdLine)\n\n\tcommandList := make([]exec.Cmd, 0)\n\n\tif len(cmdLine) == 0 {\n\t\treturn\n\t}\n\n\tpipeStages := strings.Split(cmdLine, pipeChar)\n\n\terr := createPipeStages(&commandList, pipeStages)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v: %v.\\n\", shellName, err)\n\t\treturn\n\t}\n\n\terr = connectPipeline(commandList)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v: Error with pipes: %v.\\n\", shellName, err)\n\t\treturn\n\t}\n\n\terr = executePipeline(commandList)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v: Error during execution: %v\\n\", shellName, err)\n\t\treturn\n\t}\n}", "func ExecuteCommandline(time time.Duration, command string, extraArgs []string) (string, error) {\n\t// Create a new context and add a timeout to it\n\tctx, cancel := context.WithTimeout(context.Background(), time)\n\tdefer cancel() // The cancel should be deferred so resources are cleaned up\n\n\t// Create the command with our context\n\targs := strings.Split(command, \" \")\n\tvar cmd *exec.Cmd\n\n\tif len(args) == 1 {\n\t\tcmd = exec.CommandContext(ctx, args[0], extraArgs...)\n\t} else {\n\t\tcmd = exec.CommandContext(ctx, args[0], append(args[1:], extraArgs...)...)\n\t}\n\n\tcmd.Wait()\n\t// This time we can simply use Output() to get the result.\n\tout, err := cmd.CombinedOutput()\n\n\t// We want to check the context error to see if the timeout was executed.\n\t// The error returned by cmd.Output() will be OS specific based on what\n\t// happens when a process is killed.\n\tif ctx.Err() == context.DeadlineExceeded {\n\t\treturn \"\", ctx.Err()\n\t}\n\n\t// If there's no context error, we know the command completed (or errored).\n\tif err != nil {\n\t\treturn string(out), err\n\t}\n\treturn string(out), nil\n}", "func ShellExec(cmdLine string, shells ...string) (string, error) {\n\t// shell := \"/bin/sh\"\n\tshell := \"sh\"\n\tif len(shells) > 0 {\n\t\tshell = shells[0]\n\t}\n\n\tvar out bytes.Buffer\n\tcmd := exec.Command(shell, \"-c\", cmdLine)\n\tcmd.Stdout = &out\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn out.String(), nil\n}", "func Exec(client *Client, args []string, timeoutSecs int) (*pb.ExecResult, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSecs)*time.Second)\n\tdefer cancel()\n\n\trequest := &pb.ExecRequest{\n\t\tExecutable: args[0],\n\t\tArgs: args[1:],\n\t}\n\n\treturn client.Exec(ctx, request)\n}", "func exec(c *lxc.Container, conf *Config) {\n\tvar output []byte\n\tvar err error\n\t// stdout and stderr are unfornutately concatenated\n\tif output, err = c.Execute(conf.Args.Command...); err != nil {\n\t\tif len(output) != 0 {\n\t\t\tfmt.Printf(\"%s\\n\", output)\n\t\t}\n\t\terrorExit(2, err)\n\t} else {\n\t\tfmt.Printf(\"%s\", output)\n\t}\n}", "func Exec(cmd string) {\n\n\tfmt.Printf(\"Você digitou: %s \", cmd)\n\n}", "func (ar *ActiveRecord) ExecString() string {\n\tstr := strings.Join(ar.Tokens, \" \")\n\tif len(ar.Args) > 0 {\n\t\tfor i, _ := range ar.Args {\n\t\t\tstr = strings.Replace(str, holder, fmt.Sprintf(\"$%d\", i+1), 1)\n\t\t}\n\t}\n\treturn str\n}", "func (r RealExecute) ExecCommand(com string, args ...string) ([]byte, error) {\n\t/* #nosec */\n\tcommand := exec.Command(com, args...)\n\treturn command.CombinedOutput()\n}", "func (cmd InspectCmd) Exec(ctx context.Context, commandStr string, args []string, dEnv *env.DoltEnv, cliCtx cli.CliContext) int {\n\tap := cmd.ArgParser()\n\thelp, usage := cli.HelpAndUsagePrinters(cli.CommandDocsForCommandString(commandStr, cli.CommandDocumentationContent{}, ap))\n\tapr := cli.ParseArgsOrDie(ap, args, help)\n\n\tvar verr errhand.VerboseError\n\tif apr.Contains(tableFileIndexFlag) {\n\t\tverr = cmd.measureChunkIndexDistribution(ctx, dEnv)\n\t}\n\n\treturn HandleVErrAndExitCode(verr, usage)\n}", "func (s pathRuntime) Exec(args []string) error {\n\truntimeArgs := []string{s.path}\n\tif len(args) > 1 {\n\t\truntimeArgs = append(runtimeArgs, args[1:]...)\n\t}\n\n\treturn s.execRuntime.Exec(runtimeArgs)\n}", "func Exec(t testing.TB, cmd *cobra.Command, stdIn io.Reader, args ...string) (string, string, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tt.Cleanup(cancel)\n\n\treturn ExecCtx(ctx, cmd, stdIn, args...)\n}", "func Exec(command string, args ...string) (string, error) {\n\tLogger.DebugC(color.Yellow, \"$ %v %v\", command, strings.Join(args, \" \"))\n\tb, err := exec.Command(command, args...).CombinedOutput()\n\tLogger.Debug(\"%s\\n\", b)\n\treturn string(b), err\n}", "func execExprString(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := types.ExprString(args[0].(ast.Expr))\n\tp.Ret(1, ret)\n}", "func main() {\n\tlines := util.ReadLines()\n\n\tansP1, ansP2 := Exec(lines)\n\tfmt.Printf(\"Part1: %v\\n\", ansP1)\n\tfmt.Printf(\"Part2: %v\\n\", ansP2)\n}", "func cmdLine() string {\n\treturn \"go run mksyscall_aix_ppc64.go \" + strings.Join(os.Args[1:], \" \")\n}", "func (s *GitTestHelper) Exec(first string, arg ...string) bool {\n\tif s.err != nil {\n\t\treturn false\n\t}\n\tcmd := s.runner.Command(first, arg...).WithDir(s.Getwd())\n\tbytearr, err := cmd.CombinedOutput()\n\tif s.debugExec {\n\t\twords := append([]string{\">>>\", first}, arg...)\n\t\tfmt.Println(strings.Join(words, \" \"))\n\t\tfmt.Println(string(bytearr))\n\t}\n\tif err != nil {\n\t\ts.err = fmt.Errorf(\"%v %v\", err, string(bytearr))\n\t\ts.errCause = first + \" \" + strings.Join(arg, \" \")\n\t\treturn false\n\t}\n\treturn true\n}", "func ParseExecutableLine(name string, fullLine string) (Executable, error) {\n\tline := strings.Replace(fullLine, asdfPluginPrefix, \"\", -1)\n\ttokens := strings.Split(line, \" \")\n\tif len(tokens) != 2 {\n\t\treturn Executable{}, fmt.Errorf(\"bad line %s\", fullLine)\n\t}\n\treturn Executable{\n\t\tName: name,\n\t\tPluginName: strings.TrimSpace(tokens[0]),\n\t\tPluginVersion: strings.TrimSpace(tokens[1]),\n\t}, nil\n}", "func (c *cmdVersion) Exec(args []string) error {\n\n\tif len(args) != 0 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: mashling version \\n\\nToo many arguments given.\\n\")\n\t\tos.Exit(2)\n\t} else {\n\t\tc.versionNumber = version\n\t\tfmt.Printf(\"mashling version %s\\n\", c.versionNumber)\n\t}\n\n\treturn nil\n}", "func Exec(container string, cmdLine ...string) (string, error) {\n\tparts := []string{\"exec\", \"-t\", container}\n\tparts = append(parts, cmdLine...)\n\tcmd := exec.Command(\"docker\", parts...)\n\toutput, err := cmd.CombinedOutput()\n\treturn string(output), err\n}", "func execute(w io.Writer, commandline string, req io.Reader) error {\n\targv, err := cmd.SplitQuoted(commandline)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We treat a pipe command specially.\n\t// It will be splitted by the pipe binary.\n\tif strings.HasPrefix(commandline, \"pipe \") {\n\t\targv = []string{\"pipe\", commandline[5:]}\n\t}\n\n\tif len(argv) < 1 {\n\t\treturn fmt.Errorf(\"request contains no command\")\n\t}\n\n\t// Get installation directory of editor binary.\n\t// All subcommands must be in the same directory.\n\tvar installDir string\n\tprogname := os.Args[0]\n\tif p, err := filepath.Abs(progname); err != nil {\n\t\treturn fmt.Errorf(\"cannot get editor directory\")\n\t} else {\n\t\tinstallDir = filepath.Dir(p)\n\t}\n\n\tvar buf bytes.Buffer\n\tvar errbuf bytes.Buffer\n\targv[0] = filepath.Join(installDir, argv[0])\n\tctx, cancel := context.WithCancel(context.Background())\n\tc := exec.CommandContext(ctx, argv[0], argv[1:]...)\n\tc.Stdin = req\n\tc.Stdout = &buf\n\tc.Stderr = &errbuf\n\tif err := c.Start(); err != nil {\n\t\treturn err\n\t}\n\tpid := c.Process.Pid\n\tProcessList.Add(pid, argv, cancel)\n\n\terr = c.Wait()\n\tProcessList.Remove(pid)\n\tio.Copy(w, &buf)\n\n\t// Write stderr of commands to the console.\n\tif errbuf.Len() > 0 {\n\t\tif err != nil {\n\t\t\terrmsg, _ := ioutil.ReadAll(&errbuf)\n\t\t\terr = fmt.Errorf(\"%s\\n%s\\n\", err.Error(), string(errmsg))\n\t\t} else {\n\t\t\tio.Copy(os.Stdout, &errbuf)\n\t\t}\n\t}\n\treturn err\n}", "func Exec(name string, arg ...string) error {\n\tcmd := exec.Command(name, arg...)\n\tif len(cmdExePath) != 0 {\n\t\tcmd.Dir = cmdExePath\n\t\tcmdExePath = \"\"\n\t}\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Fatal(\"error: \", string(output), err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Executable() (string, error)", "func (flower *Flower) Exec(commandName string, capture bool, args []string) (string, error) {\n\tflowerCommandData, err := flower.GetFlowerCommandData(commandName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar command []string\n\tif flowerCommandData.Workdir != \"\" {\n\t\tcommand = append([]string{\"cd\", flowerCommandData.Workdir, \"&&\"})\n\t}\n\n\tcommand = append([]string{flowerCommandData.Bin})\n\tfor _, arg := range args {\n\t\tcommand = append([]string{arg})\n\t}\n\n\tvar dockerExecOptions *DockerExecOptions\n\tswitch flowerCommandData.DockerExecOptions {\n\tcase nil:\n\t\tdockerExecOptions = flowerCommandData.DockerExecOptions\n\tdefault:\n\t\tdockerExecOptions = &DockerExecOptions{}\n\t}\n\n\treturn flower.Container.Exec(command, dockerExecOptions, capture)\n}", "func (m *MockExec) Exec(path *string, name string, extra ...string) ([]byte, error) {\n\targs := m.Called(name, extra)\n\n\tif args.Error(1) != nil {\n\t\treturn nil, args.Error(1)\n\t}\n\treturn []byte(args.String(0)), nil\n}", "func (exec *Executhor) Exec(execArg []string) {\n\tif exec.execBuiltin(execArg) == nil {\n\t\treturn\n\t}\n\tpath, err := exec.getBinaryPath(execArg[0])\n\tif err == nil {\n\t\tpid := C.fork()\n\t\tif pid != 0 {\n\t\t\tvar status C.int\n\t\t\tC.wait(&status)\n\t\t} else {\n\t\t\tsyscall.Exec(path, execArg, exec.env.GetEnv())\n\t\t}\n\t} else {\n\t\tfmt.Println(err)\n\t}\n}", "func comandoExec(comando string) {\n\tfmt.Println(\"\\nEJECUTANDO: \" + comando)\n\ts := strings.Split(comando, \" -\")\n\tif len(s) == 2 {\n\t\ts2 := strings.Split(s[1], \"->\")\n\t\tif strings.Compare(s2[0], \"path\") == 0 {\n\t\t\t_, err := os.Stat(strings.ReplaceAll(s2[1], \"\\\"\", \"\"))\n\t\t\tif err == nil {\n\t\t\t\ts3 := strings.Split(s2[1], \".\")\n\t\t\t\tif strings.Compare(s3[1], \"mia\") == 0 {\n\t\t\t\t\tfmt.Println(\"RESULTADO: Lectura de archivo\")\n\t\t\t\t\tfmt.Println(\"\")\n\t\t\t\t\tarchivo := leerArchivo(s2[1])\n\t\t\t\t\t//mandar a analizar ese archivo\n\t\t\t\t\tanalizarArchivo(archivo)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"RESULTADO: La extension del archivo debe ser .MIA\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"RESULTADO: No existe el archivo especificado\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"RESULTADO: El parametro PATH es obligatorio\")\n\t\t}\n\t} else if len(s) > 2 {\n\t\tfmt.Println(\"RESULTADO: Demasiados parametros para el comando EXEC\")\n\t} else {\n\t\tfmt.Println(\"RESULTADO: Faltan parametros para el comando EXEC\")\n\t}\n}", "func sysExec(args ...OBJ) OBJ {\n\tif len(args) < 1 {\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tvar command string\n\tswitch c := args[0].(type) {\n\tcase *object.String:\n\t\tcommand = c.Value\n\tdefault:\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tif len(command) < 1 {\n\t\treturn NewError(\"`sys.exec` expected string, got invalid argument\")\n\t}\n\t// split the command\n\ttoExec := splitCommand(command)\n\tcmd := exec.Command(toExec[0], toExec[1:]...)\n\n\t// get the result\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout = &outb\n\tcmd.Stderr = &errb\n\terr := cmd.Run()\n\n\t// If the command exits with a non-zero exit-code it\n\t// is regarded as a failure. Here we test for ExitError\n\t// to regard that as a non-failure.\n\tif err != nil && err != err.(*exec.ExitError) {\n\t\tfmt.Printf(\"Failed to run '%s' -> %s\\n\", command, err.Error())\n\t\treturn &object.Error{Message: \"Failed to run command!\"}\n\t}\n\n\t// The result-objects to store in our hash.\n\tstdout := &object.String{Value: outb.String()}\n\tstderr := &object.String{Value: errb.String()}\n\n\treturn NewHash(StringObjectMap{\n\t\t\"stdout\": stdout,\n\t\t\"stderr\": stderr,\n\t})\n}", "func (c *Cmd) Exec(args []string) error {\n\tc.flag.Uint64Var(&version, \"version\", 0, \"\")\n\tc.flag.Parse(args)\n\n\t// Load config\n\tif driver != nil {\n\t\tconfig = &core.Config{\n\t\t\tData: make(map[string]core.Internal),\n\t\t}\n\t\tconfig.Data[\"\"] = core.Internal{\n\t\t\tDriver: *driver,\n\t\t\tDsn: *dsn,\n\t\t\tDirectory: *directory,\n\t\t}\n\t} else {\n\t\tconfig = core.MustNewConfig(*dirPath).WithEnv(*env)\n\t}\n\n\treturn c.Run(c, c.flag.Args()...)\n}", "func WinExec(lpCmdLine /*const*/ LPCSTR, uCmdShow UINT) UINT {\n\tret1 := syscall3(winExec, 2,\n\t\tuintptr(unsafe.Pointer(lpCmdLine)),\n\t\tuintptr(uCmdShow),\n\t\t0)\n\treturn UINT(ret1)\n}", "func Exec(name string, arg ...string) error {\n\tcmd := exec.Command(name, arg...)\n\tvar outBuffer = new(bytes.Buffer)\n\tvar errBuffer = new(bytes.Buffer)\n\tif viper.GetBool(\"verbose\") {\n\t\t_, err := fmt.Fprintf(os.Stdout, \"Executing command: %s\\n\", strings.Join(append([]string{name}, arg...), \" \"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stdout\n\t} else {\n\t\tcmd.Stdout = outBuffer\n\t\tcmd.Stderr = errBuffer\n\t}\n\tif err := cmd.Run(); err != nil {\n\t\tlines := strings.Split(outBuffer.String(), \"\\n\")\n\t\tfiltered := []string{errBuffer.String()}\n\t\tfor _, x := range lines {\n\t\t\tif strings.HasPrefix(x, \"fatal:\") {\n\t\t\t\tfiltered = append(filtered, x)\n\t\t\t}\n\t\t}\n\n\t\treturn fmt.Errorf(strings.Join(filtered, \"\\n\"))\n\t}\n\treturn nil\n}", "func CommandLine( line []byte, cmd ...string ) [ ]byte {\n\tfor i := 0; i < len( cmd ); i++ {\n\t\t// Separate argument(s) !\n\t\tif len( line ) > 0 && line[ len( line )-1 ] != ( ' ' ) {\n\t\t\tline = append( line, ' ' )\n\t\t}\n\t\tline = commandLine( line, cmd[ i ], len( line ) > 0 )\n\t}\n\treturn line\n}", "func Exec(name string, args ...string) string {\n\tout, err := exec.Command(name, args...).Output()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\treturn string(out)\n}", "func SimpleExec(name string, args ...string) (string, error) {\n\tTrace(name, args...)\n\treturn Output(ExecCommand(name, args...))\n}", "func runExec(serviceName string, operation string) (string, error) {\n\tbytes, err := exec.Command(Configuration.ExecutorPath, serviceName, operation).CombinedOutput()\n\treturn string(bytes), err\n}", "func Exec(name string, args ...string) error {\n\treturn syscall.Exec(name, args, os.Environ())\n}", "func (h Client) Exec(arg ...string) (string, string, error) {\n\tcmd := exec.Command(h.HelmExecutable, arg...)\n\n\tklog.V(8).Infof(\"running helm command: %v\", cmd)\n\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\n\tcmd.Stdout = &stdoutBuf\n\tcmd.Stderr = &stderrBuf\n\n\terr := cmd.Run()\n\toutStr, errStr := stdoutBuf.String(), stderrBuf.String()\n\tif err != nil {\n\t\tklog.V(8).Infof(\"stdout: %s\", outStr)\n\t\tklog.V(7).Infof(\"stderr: %s\", errStr)\n\t\treturn \"\", errStr, fmt.Errorf(\"exit code %d running command %s\", cmd.ProcessState.ExitCode(), cmd.String())\n\t}\n\n\treturn outStr, errStr, nil\n}", "func main() {\n\n // Go requires an absolute path to the binary we want to execute, so we’ll use exec.LookPath to find it (probably /bin/ls).\n // Exec requires arguments in slice form (as apposed to one big string).\n binary, lookErr := exec.LookPath(\"ls\")\n if lookErr != nil {\n panic(lookErr)\n }\n\n args := []string{\"ls\", \"-a\", \"-l\", \"-h\"} //Exec requires arguments in slice form (as apposed to one big string). first argument should be the program name\n\n //Exec also needs a set of environment variables to use. Here we just provide our current environment.\n env := os.Environ()\n\n execErr := syscall.Exec(binary, args, env) //Here’s the actual syscall.Exec call.\n //If this call is successful, the execution of our process will end here and be replaced by the /bin/ls -a -l -h process.\n if execErr != nil {// If there is an error we’ll get a return value.\n panic(execErr)\n }\n}", "func ExecContainsString(command, contains string) error {\n\tstdOut, _, err := Exec(command)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ContainsString(stdOut, contains)\n}", "func SimpleExec(name string, args ...string) (string, error) {\n\treturn Output(ExecCommand(name, args...))\n}", "func (cx *Context) Exec(source string) (err error) {\n\treturn cx.exec(source, \"exec\")\n}", "func (t *Test) exec(tc testCommand) error {\n\tswitch cmd := tc.(type) {\n\tcase *clearCmd:\n\t\treturn t.clear()\n\n\tcase *loadCmd:\n\t\treturn cmd.append()\n\n\tcase *evalCmd:\n\t\texpr, err := parser.ParseExpr(cmd.expr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt := time.Unix(0, startingTime+(cmd.start.Unix()*1000000000))\n\t\tbodyBytes, err := cmd.m3query.query(expr.String(), t)\n\t\tif err != nil {\n\t\t\tif cmd.fail {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errors.Wrapf(err, \"error in %s %s, line %d\", cmd, cmd.expr, cmd.line)\n\t\t}\n\t\tif cmd.fail {\n\t\t\treturn fmt.Errorf(\"expected to fail at %s %s, line %d\", cmd, cmd.expr, cmd.line)\n\t\t}\n\n\t\terr = cmd.compareResult(bodyBytes)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error in %s %s, line %d. m3query response: %s\", cmd, cmd.expr, cmd.line, string(bodyBytes))\n\t\t}\n\n\tdefault:\n\t\tpanic(\"promql.Test.exec: unknown test command type\")\n\t}\n\treturn nil\n}", "func (a *AGI) Exec(cmd ...string) (string, error) {\n\tcmd = append([]string{\"EXEC\"}, cmd...)\n\treturn a.Command(cmd...).Val()\n}", "func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (libcontainerdtypes.Process, error) {\n\thcsContainer, err := t.getHCSContainer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger := t.ctr.client.logger.WithFields(log.Fields{\n\t\t\"container\": t.ctr.id,\n\t\t\"exec\": processID,\n\t})\n\n\t// Note we always tell HCS to\n\t// create stdout as it's required regardless of '-i' or '-t' options, so that\n\t// docker can always grab the output through logs. We also tell HCS to always\n\t// create stdin, even if it's not used - it will be closed shortly. Stderr\n\t// is only created if it we're not -t.\n\tcreateProcessParms := &hcsshim.ProcessConfig{\n\t\tCreateStdInPipe: true,\n\t\tCreateStdOutPipe: true,\n\t\tCreateStdErrPipe: !spec.Terminal,\n\t}\n\tif spec.Terminal {\n\t\tcreateProcessParms.EmulateConsole = true\n\t\tif spec.ConsoleSize != nil {\n\t\t\tcreateProcessParms.ConsoleSize[0] = uint(spec.ConsoleSize.Height)\n\t\t\tcreateProcessParms.ConsoleSize[1] = uint(spec.ConsoleSize.Width)\n\t\t}\n\t}\n\n\t// Take working directory from the process to add if it is defined,\n\t// otherwise take from the first process.\n\tif spec.Cwd != \"\" {\n\t\tcreateProcessParms.WorkingDirectory = spec.Cwd\n\t} else {\n\t\tcreateProcessParms.WorkingDirectory = t.ctr.ociSpec.Process.Cwd\n\t}\n\n\t// Configure the environment for the process\n\tcreateProcessParms.Environment = setupEnvironmentVariables(spec.Env)\n\n\t// Configure the CommandLine/CommandArgs\n\tsetCommandLineAndArgs(spec, createProcessParms)\n\tlogger.Debugf(\"exec commandLine: %s\", createProcessParms.CommandLine)\n\n\tcreateProcessParms.User = spec.User.Username\n\n\t// Start the command running in the container.\n\tnewProcess, err := hcsContainer.CreateProcess(createProcessParms)\n\tif err != nil {\n\t\tlogger.WithError(err).Errorf(\"exec's CreateProcess() failed\")\n\t\treturn nil, err\n\t}\n\tpid := newProcess.Pid()\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err := newProcess.Kill(); err != nil {\n\t\t\t\tlogger.WithError(err).Error(\"failed to kill process\")\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tif err := newProcess.Wait(); err != nil {\n\t\t\t\t\tlogger.WithError(err).Error(\"failed to wait for process\")\n\t\t\t\t}\n\t\t\t\tif err := newProcess.Close(); err != nil {\n\t\t\t\t\tlogger.WithError(err).Error(\"failed to clean process resources\")\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}()\n\n\tdio, err := newIOFromProcess(newProcess, spec.Terminal)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"failed to get stdio pipes\")\n\t\treturn nil, err\n\t}\n\t// Tell the engine to attach streams back to the client\n\t_, err = attachStdio(dio)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &process{\n\t\tid: processID,\n\t\tctr: t.ctr,\n\t\thcsProcess: newProcess,\n\t\twaitCh: make(chan struct{}),\n\t}\n\n\t// Spin up a goroutine to notify the backend and clean up resources when\n\t// the process exits. Defer until after the start event is sent so that\n\t// the exit event is not sent out-of-order.\n\tdefer func() { go p.reap() }()\n\n\tt.ctr.client.eventQ.Append(t.ctr.id, func() {\n\t\tei := libcontainerdtypes.EventInfo{\n\t\t\tContainerID: t.ctr.id,\n\t\t\tProcessID: p.id,\n\t\t\tPid: uint32(pid),\n\t\t}\n\t\tt.ctr.client.logger.WithFields(log.Fields{\n\t\t\t\"container\": t.ctr.id,\n\t\t\t\"event\": libcontainerdtypes.EventExecAdded,\n\t\t\t\"event-info\": ei,\n\t\t}).Info(\"sending event\")\n\t\terr := t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecAdded, ei)\n\t\tif err != nil {\n\t\t\tt.ctr.client.logger.WithError(err).WithFields(log.Fields{\n\t\t\t\t\"container\": t.ctr.id,\n\t\t\t\t\"event\": libcontainerdtypes.EventExecAdded,\n\t\t\t\t\"event-info\": ei,\n\t\t\t}).Error(\"failed to process event\")\n\t\t}\n\t\terr = t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecStarted, ei)\n\t\tif err != nil {\n\t\t\tt.ctr.client.logger.WithError(err).WithFields(log.Fields{\n\t\t\t\t\"container\": t.ctr.id,\n\t\t\t\t\"event\": libcontainerdtypes.EventExecStarted,\n\t\t\t\t\"event-info\": ei,\n\t\t\t}).Error(\"failed to process event\")\n\t\t}\n\t})\n\n\treturn p, nil\n}", "func (c *VirtLauncherClient) Exec(domainName, command string, args []string, timeoutSeconds int32) (int, string, error) {\n\trequest := &cmdv1.ExecRequest{\n\t\tDomainName: domainName,\n\t\tCommand: command,\n\t\tArgs: args,\n\t\tTimeoutSeconds: int32(timeoutSeconds),\n\t}\n\texitCode := -1\n\tstdOut := \"\"\n\n\tctx, cancel := context.WithTimeout(\n\t\tcontext.Background(),\n\t\t// we give the context a bit more time as the timeout should kick\n\t\t// on the actual execution\n\t\ttime.Duration(timeoutSeconds)*time.Second+shortTimeout,\n\t)\n\tdefer cancel()\n\n\tresp, err := c.v1client.Exec(ctx, request)\n\tif resp == nil {\n\t\treturn exitCode, stdOut, err\n\t}\n\n\texitCode = int(resp.ExitCode)\n\tstdOut = resp.StdOut\n\n\treturn exitCode, stdOut, err\n}", "func execute_plugin(filename string, input []byte) []byte {\n cmd := filename\n arg := string(input)\n out, err := exec.Command(cmd, arg).Output()\n if err != nil {\n println(err.Error())\n return nil\n }\n return out\n}", "func (p *Init) exec(path string, r *ExecConfig) (process.Process, error) {\n\tvar spec specs.Process\n\tif err := json.Unmarshal(r.Spec.Value, &spec); err != nil {\n\t\treturn nil, err\n\t}\n\tspec.Terminal = r.Terminal\n\n\te := &execProcess{\n\t\tid: r.ID,\n\t\tpath: path,\n\t\tparent: p,\n\t\tspec: spec,\n\t\tstdio: stdio.Stdio{\n\t\t\tStdin: r.Stdin,\n\t\t\tStdout: r.Stdout,\n\t\t\tStderr: r.Stderr,\n\t\t\tTerminal: r.Terminal,\n\t\t},\n\t\twaitBlock: make(chan struct{}),\n\t}\n\te.execState = &execCreatedState{p: e}\n\treturn e, nil\n}", "func (p *Qlang) Exec(codeText []byte, fname string) (err error) {\n\n\tcode := p.cl.Code()\n\tstart := code.Len()\n\tend, err := p.Cl(codeText, fname)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif qcl.DumpCode != 0 {\n\t\tcode.Dump(start)\n\t}\n\n\tp.ExecBlock(start, end, p.cl.GlobalSymbols())\n\treturn\n}", "func execCommand(log bool, name string, args ...string) (bytes.Buffer, bytes.Buffer, error) {\n\tvar (\n\t\tstdout bytes.Buffer\n\t\tstderr bytes.Buffer\n\t)\n\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr := cmd.Run()\n\tif log {\n\t\tLogf(\"run command '%s %v':\\n out=%s\\n err=%s\\n ret=%v\",\n\t\t\tname, args, strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err)\n\t}\n\n\treturn stdout, stderr, err\n}", "func (c *ServerConn) Exec(expected int, format string, args ...interface{}) (int, string, error) {\n\treturn c.cmd(expected, format, args...)\n}", "func (cmd RemoteCmd) Exec(ctx context.Context, commandStr string, args []string, dEnv *env.DoltEnv, cliCtx cli.CliContext) int {\n\tap := cmd.ArgParser()\n\thelp, usage := cli.HelpAndUsagePrinters(cli.CommandDocsForCommandString(commandStr, remoteDocs, ap))\n\tapr := cli.ParseArgsOrDie(ap, args, help)\n\n\tvar verr errhand.VerboseError\n\n\tswitch {\n\tcase apr.NArg() == 0:\n\t\tverr = printRemotes(dEnv, apr)\n\tcase apr.Arg(0) == addRemoteId:\n\t\tverr = addRemote(dEnv, apr)\n\tcase apr.Arg(0) == removeRemoteId:\n\t\tverr = removeRemote(ctx, dEnv, apr)\n\tcase apr.Arg(0) == removeRemoteShortId:\n\t\tverr = removeRemote(ctx, dEnv, apr)\n\tdefault:\n\t\tverr = errhand.BuildDError(\"\").SetPrintUsage().Build()\n\t}\n\n\treturn HandleVErrAndExitCode(verr, usage)\n}", "func (fs *Fs) ExecCommand(name string, args ...string) ([]byte, error) {\n\treturn exec.Command(name, args...).CombinedOutput() // #nosec G204\n}", "func execCommand(name string, arg ...string) error {\n\tcmd := exec.Command(name, arg...)\n\t// For locating the GCC runtime library (libgcc_s.so.1):\n\tcmd.Env = append(os.Environ(), \"LD_LIBRARY_PATH=/ro/lib:/ro/lib64\")\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"%v: %v\", cmd.Args, err)\n\t}\n\treturn nil\n}", "func (n *mockAgent) exec(sandbox *Sandbox, c Container, cmd types.Cmd) (*Process, error) {\n\treturn nil, nil\n}", "func (c *Tool) Exec() ([]byte, error) {\n\treturn c.Run()\n}", "func (player *Player) ExecAs(commandLine string, callback func(statusCode int)) {\n\tplayer.Exec(fmt.Sprintf(\"execute %v ~ ~ ~ %v\", player.name, commandLine), func(response map[string]interface{}) {\n\t\tcodeInterface, exists := response[\"statusCode\"]\n\t\tif !exists {\n\t\t\tlog.Printf(\"exec as: invalid response JSON\")\n\t\t\treturn\n\t\t}\n\t\tcode, _ := codeInterface.(int)\n\t\tif callback != nil {\n\t\t\tcallback(code)\n\t\t}\n\t})\n}", "func CommandExec() *cobra.Command {\n\n\tvar expandCmd = &cobra.Command{\n\t\tUse: \"exec [flags] <command> <shortcuts...>\",\n\t\tExample: \"$ scmpuff exec git add 1-4\",\n\t\tAliases: []string{\"execute\"},\n\t\tShort: \"Execute cmd with numeric shortcuts\",\n\t\tLong: `Expands numeric shortcuts to their full filepath and executes the command.\n\nTakes a list of digits (1 4 5) or numeric ranges (1-5) or even both.`,\n\t\tRun: func(cmd *cobra.Command, inputArgs []string) {\n\t\t\tif len(inputArgs) < 1 {\n\t\t\t\tcmd.Usage()\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\texpandedArgs := Process(inputArgs)\n\t\t\ta := expandedArgs[1:]\n\t\t\tsubcmd := exec.Command(expandedArgs[0], a...)\n\t\t\tsubcmd.Stdin = os.Stdin\n\t\t\tsubcmd.Stdout = os.Stdout\n\t\t\tsubcmd.Stderr = os.Stderr\n\t\t\terr := subcmd.Run()\n\t\t\tif err == nil {\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\t\tos.Exit(exitError.ExitCode())\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\n\t// --relative\n\texpandCmd.Flags().BoolVarP(\n\t\t&expandRelative,\n\t\t\"relative\",\n\t\t\"r\",\n\t\tfalse,\n\t\t\"make path relative to current working directory\",\n\t)\n\n\treturn expandCmd\n}", "func Exec(exe string, args ...string) (outStr string, err error) {\n\tvar (\n\t\tcmd *exec.Cmd\n\t\tout []byte\n\t)\n\n\tif exe == \"docker-compose\" {\n\t\targs = append(dockerComposeDefaultArgs(), args...)\n\t}\n\n\tcmd = exec.Command(exe, args...)\n\tcmd.Env = os.Environ()\n\tcmd.Stdin = os.Stdin\n\n\tout, err = cmd.CombinedOutput()\n\toutStr = strings.TrimSpace(string(out))\n\treturn\n}", "func (h *DriverHandle) Exec(timeout time.Duration, cmd string, args []string) ([]byte, int, error) {\n\tcommand := append([]string{cmd}, args...)\n\tres, err := h.driver.ExecTask(h.taskID, command, timeout)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn res.Stdout, res.ExitResult.ExitCode, res.ExitResult.Err\n}", "func Exec(name string, args ...string) (output []byte, err error) {\n\treturn exec.Command(name, args...).Output()\n}", "func Exec(argv0 string, argv []string, envv []string) error {\n\treturn syscall.Exec(argv0, argv, envv)\n}", "func (c *RealtimeCommand) Exec(_ io.Reader, out io.Writer) error {\n\tserviceID, source, flag, err := cmd.ServiceID(c.serviceName, c.manifest, c.Globals.APIClient, c.Globals.ErrLog)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c.Globals.Verbose() {\n\t\tcmd.DisplayServiceID(serviceID, flag, source, out)\n\t}\n\n\tswitch c.formatFlag {\n\tcase \"json\":\n\t\tif err := loopJSON(c.Globals.RTSClient, serviceID, out); err != nil {\n\t\t\tc.Globals.ErrLog.AddWithContext(err, map[string]any{\n\t\t\t\t\"Service ID\": serviceID,\n\t\t\t})\n\t\t\treturn err\n\t\t}\n\n\tdefault:\n\t\tif err := loopText(c.Globals.RTSClient, serviceID, out); err != nil {\n\t\t\tc.Globals.ErrLog.AddWithContext(err, map[string]any{\n\t\t\t\t\"Service ID\": serviceID,\n\t\t\t})\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (git *Git) Exec(subcmd string, args ...string) (string, error) {\n\tb, err := git.Command(subcmd, args...).CombinedOutput()\n\n\t// Chop last newline\n\tl := len(b)\n\tif l > 0 && b[l-1] == '\\n' {\n\t\tb = b[:l-1]\n\t}\n\n\t// Make output in oneline in error cases\n\tif err != nil {\n\t\tfor i := range b {\n\t\t\tif b[i] == '\\n' {\n\t\t\t\tb[i] = ' '\n\t\t\t}\n\t\t}\n\t}\n\n\treturn string(b), err\n}", "func (ts *TaskService) Exec(requestCtx context.Context, req *taskAPI.ExecProcessRequest) (*types.Empty, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\n\ttaskID := req.ID\n\texecID := req.ExecID\n\n\tlogger := log.G(requestCtx).WithField(\"TaskID\", taskID).WithField(\"ExecID\", execID)\n\tlogger.Debug(\"exec\")\n\n\textraData, err := unmarshalExtraData(req.Spec)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal extra data\")\n\t}\n\n\t// Just provide runc the options it knows about, not our wrapper\n\treq.Spec = extraData.RuncOptions\n\n\tbundleDir := bundle.Dir(filepath.Join(containerRootDir, taskID))\n\n\tvar ioConnectorSet vm.IOProxy\n\n\tif vm.IsAgentOnlyIO(req.Stdout, logger) {\n\t\tioConnectorSet = vm.NewNullIOProxy()\n\t} else {\n\t\t// Override the incoming stdio FIFOs, which have paths from the host that we can't use\n\t\tfifoSet, err := cio.NewFIFOSetInDir(bundleDir.RootPath(), fifoName(taskID, execID), req.Terminal)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"failed opening stdio FIFOs\")\n\t\t\treturn nil, errors.Wrap(err, \"failed to open stdio FIFOs\")\n\t\t}\n\n\t\tvar stdinConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdin != \"\" {\n\t\t\treq.Stdin = fifoSet.Stdin\n\t\t\tstdinConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.VSockAcceptConnector(extraData.StdinPort),\n\t\t\t\tWriteConnector: vm.FIFOConnector(fifoSet.Stdin),\n\t\t\t}\n\t\t}\n\n\t\tvar stdoutConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdout != \"\" {\n\t\t\treq.Stdout = fifoSet.Stdout\n\t\t\tstdoutConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stdout),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StdoutPort),\n\t\t\t}\n\t\t}\n\n\t\tvar stderrConnectorPair *vm.IOConnectorPair\n\t\tif req.Stderr != \"\" {\n\t\t\treq.Stderr = fifoSet.Stderr\n\t\t\tstderrConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stderr),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StderrPort),\n\t\t\t}\n\t\t}\n\n\t\tioConnectorSet = vm.NewIOConnectorProxy(stdinConnectorPair, stdoutConnectorPair, stderrConnectorPair)\n\t}\n\n\tresp, err := ts.taskManager.ExecProcess(requestCtx, req, ts.runcService, ioConnectorSet)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"exec failed\")\n\t\treturn nil, err\n\t}\n\n\tlogger.Debug(\"exec succeeded\")\n\treturn resp, nil\n}", "func (d Dispatcher) ExecExecutionTimeString(id string, hash string) (string, error) {\n\te, err := d.GetBC().FindExec(id, hash)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn time.Unix(e.GetExecutionTime(), 0).String(), nil\n}", "func RunCommand(custom string) (string, error) {\r\n custom = strings.TrimSpace(strings.TrimSuffix(custom, \"$\"))\r\n pieces := strings.Split(custom, \" \")\r\n cmd := exec.Command(pieces[0])\r\n cmd.Args = pieces\r\n cmd.Stdin = os.Stdin\r\n output, oops := cmd.CombinedOutput()\r\n return string(output), oops\r\n}", "func (mr *MockexecuterMockRecorder) Exec(ctx, commandLine interface{}, args ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, commandLine}, args...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Exec\", reflect.TypeOf((*Mockexecuter)(nil).Exec), varargs...)\n}", "func SafeExec(cmd *exec.Cmd) string {\n\toutBytes, err := cmd.CombinedOutput()\n\tout := string(outBytes)\n\tif err != nil {\n\t\tif out != \"\" {\n\t\t\tout += \"\\n\"\n\t\t}\n\t\tout += fmt.Sprintf(\"error: %v\\n\", err)\n\t}\n\treturn out\n}", "func (ui *ReplApp) evalLine(line string) (quit bool) {\n\t// these vars are used in many places below\n\tengine := ui.engine\n\tcmds := ui.commands\n\toutput := ui.output\n\tmeProfileFile := ui.meProfileFile\n\tcontactsFile := ui.contactsFile\n\tprivateKeyFile := ui.privateKeyFile\n\n\t// parse raw line into command struct\n\tcmd := cmds.parse(line)\n\tif cmd.err != nil {\n\t\tif cmd.cmd != \"\" { // ignore blank lines\n\t\t\tlog.Printf(\"Error: %s\\n\", cmd.err)\n\t\t}\n\t\treturn\n\t}\n\n\t// process specific command\n\t// each block could really be in it's own function\n\t// or a function in the command definitions\n\tswitch cmd.cmd {\n\tcase \"exit\":\n\t\treturn true\n\n\tcase \"help\":\n\t\tfmt.Fprintln(output, cmds.help()) // uses commanddefs\n\n\tcase \"ip\":\n\t\tfmt.Fprintln(output, \"getting external ip...\")\n\t\tip, err := GetIP()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprintf(output, \"external IP address:\\t%s\\nlistening on port:\\t%s\\n\", ip, engine.Me.Port)\n\n\tcase \"me\":\n\t\tswitch cmd = *cmd.leaf(); cmd.cmd {\n\t\tcase \"show\":\n\t\t\tfmt.Fprintf(output, \"I am \\\"%s\\\"\\nPubKey: %s\\nPrivKey: %s\\n\",\n\t\t\t\tengine.Me,\n\t\t\t\tbase64.RawStdEncoding.EncodeToString(engine.Me.PublicSigningKey),\n\t\t\t\tbase64.RawStdEncoding.EncodeToString(engine.PrivSignKey))\n\n\t\tcase \"edit\":\n\t\t\tp, err := ParseProfile(cmd.args[0])\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tp.PublicSigningKey = engine.Me.PublicSigningKey // preserve key\n\t\t\terr = WriteProfile(p, meProfileFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tengine.Me = p\n\n\t\t\terr = WritePrivateKey(engine.PrivSignKey, privateKeyFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\tcase \"contacts\":\n\n\t\tswitch cmd = *cmd.leaf(); cmd.cmd {\n\t\tcase \"list\":\n\t\t\tfor i, c := range engine.Contacts {\n\t\t\t\tif c != nil {\n\t\t\t\t\tfmt.Fprintf(output, \"%d\\t%s\\t%s\\n\", i, c,\n\t\t\t\t\t\tbase64.RawStdEncoding.EncodeToString(c.PublicSigningKey))\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"add\":\n\t\t\tvar p *Profile\n\t\t\targ := cmd.args[0]\n\t\t\tn, err := strconv.Atoi(arg)\n\t\t\tif err == nil {\n\t\t\t\tif sess, ok := engine.GetSession(n); ok {\n\t\t\t\t\tp = sess.Other\n\t\t\t\t\tif p == nil {\n\t\t\t\t\t\tlog.Printf(\"session %d had a nil Other\", n)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tp, err = ParseProfile(arg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// overwrite contact if existing Equal() one found\n\t\t\t// TODO: do i really want to overwrite? what about having 2\n\t\t\t// contacts with different names but the same address?\n\t\t\t// i guess the question boils down to the definition of Profile\n\t\t\tif index := engine.FindContact(p); index >= 0 {\n\t\t\t\told := engine.Contacts[index]\n\t\t\t\tengine.Contacts[index] = p\n\t\t\t\tlog.Printf(\"overwrote #%d '%s' with '%s'\\n\", index, old, p)\n\t\t\t} else {\n\t\t\t\tengine.AddContact(p)\n\t\t\t\tlog.Printf(\"added %s\\n\", p)\n\t\t\t}\n\n\t\t\terr = WriteContacts(engine.Contacts, contactsFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tlog.Println(\"did not save changes to disk\")\n\t\t\t}\n\n\t\tcase \"delete\":\n\t\t\targ := cmd.args[0]\n\t\t\tn, err := strconv.Atoi(arg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tremoved := engine.Contacts[n]\n\t\t\tif engine.RemoveContact(n) {\n\t\t\t\tlog.Printf(\"deleted %s\\n\", removed)\n\n\t\t\t\terr = WriteContacts(engine.Contacts, contactsFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tlog.Println(\"did not save changes to disk\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\t}\n\t\t}\n\n\tcase \"requests\":\n\t\tswitch cmd = *cmd.leaf(); cmd.cmd {\n\t\tcase \"list\":\n\t\t\tfor i, r := range engine.Requests {\n\t\t\t\tif r != nil {\n\t\t\t\t\tfmt.Fprintf(output, \"%d\\t%s at %s (%s ago)\\n\", i,\n\t\t\t\t\t\tr.Profile,\n\t\t\t\t\t\tr.Time().Format(time.Kitchen),\n\t\t\t\t\t\ttime.Since(r.Time()))\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"accept\":\n\t\t\targ := cmd.args[0]\n\t\t\tn, err := strconv.Atoi(arg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, ok := engine.GetRequest(n); !ok {\n\t\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = engine.AcceptRequest(engine.Requests[n])\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Println(\"request accepted\")\n\n\t\tcase \"reject\":\n\t\t\targ := cmd.args[0]\n\t\t\tn, err := strconv.Atoi(arg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif engine.RemoveRequest(n) {\n\t\t\t\tlog.Println(\"removed request\")\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\t}\n\t\t}\n\n\tcase \"sessions\":\n\t\tswitch cmd = *cmd.leaf(); cmd.cmd {\n\t\tcase \"list\":\n\t\t\tfor i, s := range engine.Sessions {\n\t\t\t\tif s != nil {\n\t\t\t\t\tfmt.Fprintf(output, \"%d\\t%s\\n\", i, s)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"start\":\n\t\t\tvar p *Profile\n\t\t\targ := cmd.args[0]\n\t\t\tn, err := strconv.Atoi(arg)\n\t\t\tif err == nil {\n\t\t\t\tif p, _ = engine.GetContact(n); p == nil {\n\t\t\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp, err = ParseProfile(arg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif i := engine.FindContact(p); i >= 0 {\n\t\t\t\t\tp = engine.Contacts[i] // use profile from contacts if available\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\terr = engine.SendRequest(p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Println(\"request sent\")\n\n\t\tcase \"drop\":\n\t\t\targ := cmd.args[0]\n\t\t\tn, err := strconv.Atoi(arg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif engine.RemoveSession(n) {\n\t\t\t\tlog.Println(\"dropped session\")\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\t}\n\t\t}\n\n\tcase \"msg\":\n\t\tn, err := strconv.Atoi(cmd.args[0])\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tif _, ok := engine.GetSession(n); !ok {\n\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\treturn\n\t\t}\n\n\t\terr = engine.Sessions[n].SendText(cmd.args[1])\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"sent\")\n\n\tcase \"show\":\n\t\tn, err := strconv.Atoi(cmd.args[0])\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\ts, ok := engine.GetSession(n)\n\t\tif !ok {\n\t\t\tlog.Printf(\"%d not found\\n\", n)\n\t\t\treturn\n\t\t}\n\n\t\tconst num = 5\n\t\tstart := len(s.Msgs) - num\n\t\tif start < 0 {\n\t\t\tstart = 0\n\t\t} // clamp\n\t\tshow := s.Msgs[start:]\n\t\tfor i, t := range show {\n\t\t\tfmt.Fprintf(output, \"%d %s\\t| %s > %s\\n\", i,\n\t\t\t\tt.From().Name,\n\t\t\t\tt.TimeStamp.Time().Format(time.Kitchen),\n\t\t\t\tt.Message)\n\t\t}\n\n\t}\n\n\treturn\n}", "func Executor(s string) {\n\ts = strings.TrimSpace(s)\n\tcmdStrings := strings.Split(s, \" \")\n\tif s == \"\" {\n\t\treturn\n\t} else if s == \"quit\" || s == \"exit\" {\n\t\tfmt.Println(\"Bye!\")\n\t\tos.Exit(0)\n\t\treturn\n\t}\n\tswitch cmdStrings[0] {\n\tcase \"install-px\":\n\t\tinstallPX()\n\tcase \"deploy\":\n\t\tif len(cmdStrings) < 2 {\n\t\t\tfmt.Println(\"deploy requires an application name\")\n\t\t\treturn\n\t\t}\n\t\tdeploy(\"default\", cmdStrings[1])\n\tcase \"benchmark\":\n\t\tswitch cmdStrings[1] {\n\t\tcase \"postgres\":\n\t\t\tpodExec(\"default\", \"app=postgres\", \"/usr/bin/psql -c 'create database pxdemo;'\")\n\t\t\tpodExec(\"default\", \"app=postgres\", \"/usr/bin/pgbench -n -i -s 50 pxdemo;\")\n\t\t\tpodExec(\"default\", \"app=postgres\", \"/usr/bin/psql pxdemo -c 'select count(*) from pgbench_accounts;'\")\n\t\tdefault:\n\t\t\tfmt.Printf(\"%s benchmark not supported\\n\", cmdStrings[1])\n\t\t}\n\tcase \"px\":\n\t\tif len(cmdStrings) < 2 {\n\t\t\tfmt.Println(\"deploy requires an application name\")\n\t\t\treturn\n\t\t}\n\t\tswitch cmdStrings[1] {\n\t\tcase \"connect\":\n\t\t\tpxInit()\n\t\tcase \"snap\":\n\t\t\tif len(cmdStrings) < 3 {\n\t\t\t\tfmt.Println(\"px snap requires an application name\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpxSnap(cmdStrings[2])\n\t\tcase \"backup\":\n\t\t\tif len(cmdStrings) < 3 {\n\t\t\t\tfmt.Println(\"px backup requires an PVC name\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpxBackup(cmdStrings[2])\n\t\tcase \"backup-status\":\n\t\t\tif len(cmdStrings) < 3 {\n\t\t\t\tfmt.Println(\"px backup-status requires a PVC name\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpxBackupStatus(cmdStrings[2])\n\t\tdefault:\n\t\t\tfmt.Printf(\"px %s is not a valid command\\n\", cmdStrings[1])\n\t\t}\n\tcase \"pre-flight-check\":\n\t\tpreflight()\n\tdefault:\n\t\tfmt.Printf(\"%s is not a supported option\", s)\n\t}\n\treturn\n}", "func (p *Qlang) SafeExec(code []byte, fname string) (err error) {\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tswitch v := e.(type) {\n\t\t\tcase string:\n\t\t\t\terr = errors.New(v)\n\t\t\tcase error:\n\t\t\t\terr = v\n\t\t\tdefault:\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = p.Exec(code, fname)\n\treturn\n}", "func (ne *NSEnter) Exec(cmd string, args []string) exec.Cmd {\n\thostProcMountNsPath := filepath.Join(ne.hostRootFsPath, mountNsPath)\n\tfullArgs := append([]string{fmt.Sprintf(\"--mount=%s\", hostProcMountNsPath), \"--\"},\n\t\tappend([]string{ne.AbsHostPath(cmd)}, args...)...)\n\tklog.V(5).Infof(\"Running nsenter command: %v %v\", nsenterPath, fullArgs)\n\treturn ne.executor.Command(nsenterPath, fullArgs...)\n}", "func TestCmdExec(t *testing.T) {\n\tname := os.Args[0]\n\targs := []string{\"-test.run=TestHelperProcess\", \"--\", \"echo\"}\n\n\tc := &Cmd{}\n\tc.Exec(name, args...)\n\n\tassert.Equal(t, name, c.name)\n\tassert.Equal(t, args, c.args)\n\tassert.Equal(t, \"*exec.Cmd\", reflect.TypeOf(c.cmd).String())\n}", "func StreamedExec(pipe ProcessStream, name string, args ...string) (string, string) {\n\tcmd := ExecCommand(name, args...)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tcmd.Stdout = io.MultiWriter(pipe, &stdoutBuf)\n\tcmd.Stderr = io.MultiWriter(&stderrBuf)\n\tcmd.Run()\n\toutStr, errStr := string(stdoutBuf.Bytes()), string(stderrBuf.Bytes())\n\n\treturn outStr, errStr\n}", "func ExecCommand(args ...string) ([]byte, error) {\n\te := New()\n\tcmd := e.ExecCommand(NoSandbox, false, args[0], args[1:]...)\n\treturn cmd.CombinedOutput()\n}", "func Execute(args []string) {\n\tif len(args) <= 1 {\n\t\tos.Exit(1)\n\t}\n\n\tcmd := args[1]\n\n\tfile, err := os.Open(h.GetYolofile())\n\tif err != nil {\n\t panic(err)\n\t}\n\tdefer file.Close()\n\n\tvar cKey string\n\tmaps := make(map[string][]string)\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\n\t\tmethod, _ := regexp.MatchString(\"^(.*):\", line)\n\t\tif method {\n\t\t\tcKey = strings.Replace(line, \":\", \"\", -1)\n\t\t\tmaps[cKey] = []string{}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tmaps[cKey] = append(maps[cKey], strings.TrimSpace(line) + \";\")\n\t}\n\n\tif _, isKeyPresent := maps[cmd]; !isKeyPresent {\n\t\tfmt.Println(\"*command not found in Yolofile\")\n\t\tos.Exit(1)\n }\n\n\texe := exec.Command(\"/bin/sh\", \"-c\", strings.Join(maps[cmd][:], \" \"))\n\n\tvar stdout, stderr bytes.Buffer\n exe.Stdout = &stdout\n exe.Stderr = &stderr\n\n\tif err := exe.Run(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(string(stdout.Bytes()))\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func (self *Build) exec(moduleLabel core.Label, fileType core.FileType) error {\n\tthread := createThread(self, moduleLabel, fileType)\n\n\tsourceData, err := self.sourceFileReader(moduleLabel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to execute %v: read failed: %v\", moduleLabel, err)\n\t}\n\n\t_, err = starlark.ExecFile(thread, moduleLabel.String(), sourceData,\n\t\tbuiltins.InitialGlobals(fileType))\n\treturn err\n}", "func (r *Client) ExecuteAndReturn(s ...string) string {\n\n\tcmd := exec.Command(RhythmboxClient, s...) //s[0], s[1]) //\"--enqueue\", \"file:///home/ae/Music/Doolittle%20%5BMFSL%5D/Pixies%20-%20Doolittle%20(MFSL)%20-%2002%20-%20Tame.flac\")\n\tout, err := cmd.Output()\n\t// fmt.Println(s)\n\t// fmt.Println(out)\n\tif err != nil {\n\t\treturn string(err.Error())\n\t}\n\n\treturn string(out)\n}", "func Exec(args ...string) error {\n\tcmd := buildCommand(args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"exec: failed to pipe RunnableCmd: %v\", cmd.Args)\n\t}\n\tbuf := new(bytes.Buffer)\n\terr = errors.\n\t\tDo(cmd.Start).\n\t\tDo(func() error {\n\t\t\t_, err := buf.ReadFrom(stdout)\n\t\t\treturn err\n\t\t}).\n\t\tDo(cmd.Wait).\n\t\tErr()\n\tfmt.Println(buf.String())\n\treturn errors.WithMessagef(err, \"exec: failed to execute RunnableCmd: %v\", cmd.Args)\n}", "func NewExec(binaryPath string, args ...string) (PostRenderer, error) {\n\tfullPath, err := getFullPath(binaryPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &execRender{fullPath, args}, nil\n}", "func Exec(name string, args ...string) (io.ReadWriteCloser, error) {\n\tconn, err := net.Dial(\"unix\", SocketFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif name == \"\" {\n\t\treturn nil, errEmptyName\n\t}\n\tif err = writeString(conn, name); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, arg := range args {\n\t\tif arg == \"\" {\n\t\t\treturn nil, errEmptyArg\n\t\t}\n\t\tif err = writeString(conn, arg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\twriteString(conn, \"\")\n\treturn conn, nil\n}", "func (p *Program) exec(c ExecCommand, fn ExecCallback) {\n\tif err := p.ReleaseTerminal(); err != nil {\n\t\t// If we can't release input, abort.\n\t\tif fn != nil {\n\t\t\tgo p.Send(fn(err))\n\t\t}\n\t\treturn\n\t}\n\n\tc.SetStdin(p.input)\n\tc.SetStdout(p.output)\n\tc.SetStderr(os.Stderr)\n\n\t// Execute system command.\n\tif err := c.Run(); err != nil {\n\t\t_ = p.RestoreTerminal() // also try to restore the terminal.\n\t\tif fn != nil {\n\t\t\tgo p.Send(fn(err))\n\t\t}\n\t\treturn\n\t}\n\n\t// Have the program re-capture input.\n\terr := p.RestoreTerminal()\n\tif fn != nil {\n\t\tgo p.Send(fn(err))\n\t}\n}", "func Run(dir string, commandLine string) ([]byte, error) {\n\n\t// Split commandLine into an array separated by whitespace\n\targs := strings.Fields(commandLine)\n\tcmd := exec.Command(args[0], args[1:]...)\n\tcmd.Dir = dir\n\tvar buf bytes.Buffer\n\tcmd.Stdout = &buf\n\tcmd.Stderr = &buf\n\terr := cmd.Run()\n\tout := buf.Bytes()\n\tif err != nil {\n\t\treturn out, err\n\t}\n\treturn out, nil\n}", "func SimpleExecInPath(dir, cmdName string, arguments ...string) {\n\tcmd := exec.Command(cmdName, arguments...) // nolint: gosec\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Dir = dir\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (pm *Manager) Exec(desc, cmdName string, args ...string) (string, string, error) {\n\treturn pm.ExecDir(-1, \"\", desc, cmdName, args...)\n}", "func ExecuteShell(ctx context.Context) interface{} {\n\treturn func(line string) (io.Reader, error) {\n\t\tc := exec.Command(\"sh\", \"-\")\n\n\t\tcopyDone := make(chan error)\n\t\ttimeout := time.After(ContextGetTimeout(ctx))\n\n\t\toutput := new(bytes.Buffer)\n\t\tif stdout, err := c.StdoutPipe(); err == nil {\n\t\t\tfanout := io.MultiWriter(os.Stdout, output)\n\t\t\tgo func() {\n\t\t\t\t_, err := io.Copy(fanout, stdout)\n\t\t\t\tcopyDone <- err\n\t\t\t}()\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif stderr, err := c.StderrPipe(); err == nil {\n\t\t\tgo func() {\n\t\t\t\tio.Copy(os.Stderr, stderr)\n\t\t\t}()\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t\tstdin, err := c.StdinPipe()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := c.Start(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err := stdin.Write([]byte(line)); err != nil {\n\t\t\tstdin.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\tstdin.Close() // finished\n\t\terr = c.Wait()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Waits for the stdout and stderr copy goroutines to complete.\n\t\tselect {\n\t\tcase err = <-copyDone:\n\t\t\tbreak\n\t\tcase <-timeout:\n\t\t\tbreak\n\t\t}\n\t\treturn output, err\n\t}\n}", "func RunExecV(c string) string {\n x := exec.Command(\"bash\", \"-c\", c)\n out, err := x.CombinedOutput()\n if err != nil {\n log.Fatalf(\"Error: %s\\n\", err)\n }\n r := fmt.Sprintf(\"%s\", out)\n z := strings.Replace(r, \"\\n\", \"\", -1)\n return z\n}", "func (ctx *Context) Exec(cmd []string) *ExecResult {\n\treturn ctx.ExecWithParams(ExecParams{Cmd: cmd})\n}", "func SimpleExec(cmdName string, arguments ...string) {\n\tcmd := exec.Command(cmdName, arguments...) // nolint: gosec\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\n\tvar err error\n\tvar auth goph.Auth\n\tvar callback ssh.HostKeyCallback\n\n\tif force {\n\t\tcallback = ssh.InsecureIgnoreHostKey()\n\t} else {\n\t\tif callback, err = DefaultKnownHosts(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif host.Keyfile != \"\" {\n\t\t// Start new ssh connection with private key.\n\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\t// ssh: this private key is passphrase protected\n\t\t\tpwd = common.AskPass(\"Private key passphrase: \")\n\t\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif pwd == \"\" {\n\t\t\tpwd = common.AskPass(\n\t\t\t\tfmt.Sprintf(\"%s@%s's password: \", host.User, host.Addr),\n\t\t\t)\n\t\t}\n\t\tauth = goph.Password(pwd)\n\t}\n\n\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\tfmt.Println(host, pwd, force)\n\t}\n\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: host.User,\n\t\tAddr: host.Addr,\n\t\tPort: host.Port,\n\t\tAuth: auth,\n\t\tTimeout: 5 * time.Second,\n\t\tCallback: callback,\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Defer closing the network connection.\n\tdefer client.Close()\n\n\t// Execute your command.\n\tout, err := client.Run(strings.Join(cmds, \" && \"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get your output as []byte.\n\treturn string(out), nil\n}", "func (e *Echo) Run(cmdStr string) string {\n\treturn exec.Run(e.Eval(cmdStr))\n}", "func (c *Command) Execute(user string, msg string, args []string) {\n}", "func ExecBuiltin(args []string) {\n\tif len(args) <= 0 {\n\t\tPanic(\"No parameters\")\n\t}\n\n\t//TODO: Loadings\n\tswitch args[0] {\n\tcase \"Error\":\n\t\tError(strings.Join(args[1:], \" \"))\n\tcase \"Warn\":\n\t\tWarn(strings.Join(args[1:], \" \"))\n\tcase \"Info\":\n\t\tInfo(strings.Join(args[1:], \" \"))\n\tcase \"Made\":\n\t\tMade(strings.Join(args[1:], \" \"))\n\tcase \"Ask\":\n\t\tif noColor {\n\t\t\tfmt.Print(\"[?] \")\n\t\t} else {\n\t\t\tfmt.Print(\"\\033[38;5;99;01m[?]\\033[00m \")\n\t\t}\n\t\tfmt.Println(strings.Join(args[1:], \" \"))\n\tcase \"AskYN\":\n\t\tif AskYN(strings.Join(args[1:], \" \")) {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tos.Exit(1)\n\tcase \"Read\":\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tfmt.Print(text)\n\tcase \"ReadSecure\":\n\t\tfmt.Print(ReadSecure())\n\tcase \"AskList\":\n\t\tvalues := \"\"\n\t\tdflt := -1\n\n\t\tif len(args) >= 3 {\n\t\t\tvalues = args[2]\n\t\t\tif len(args) >= 4 {\n\t\t\t\tif i, err := strconv.Atoi(args[3]); err == nil {\n\t\t\t\t\tdflt = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tos.Exit(AskList(strings.Split(values, \",\"), dflt, args[1]))\n\tcase \"Bell\":\n\t\tBell()\n\t}\n\tos.Exit(0)\n}" ]
[ "0.6906744", "0.6147474", "0.60744816", "0.60500157", "0.5863146", "0.58578545", "0.5813975", "0.5777007", "0.5759011", "0.5743766", "0.5711614", "0.5693573", "0.56703174", "0.56509113", "0.5646578", "0.5635001", "0.5626724", "0.5615617", "0.55758286", "0.5570272", "0.5558317", "0.5553162", "0.5528124", "0.5485141", "0.54798293", "0.54765713", "0.54761225", "0.54510874", "0.54352313", "0.54304135", "0.5421417", "0.54087985", "0.5406896", "0.5403255", "0.5392832", "0.5356753", "0.5356508", "0.5355068", "0.53527975", "0.53433454", "0.53239137", "0.5317961", "0.53012615", "0.52926797", "0.52880925", "0.5285033", "0.52812165", "0.52707744", "0.52345526", "0.52292746", "0.5228947", "0.5222655", "0.521348", "0.5211066", "0.5195383", "0.5192933", "0.5192783", "0.51913065", "0.5189269", "0.5185395", "0.51839036", "0.5182636", "0.5172785", "0.5170879", "0.51699877", "0.5159173", "0.5155436", "0.51460046", "0.5136873", "0.5117621", "0.51159126", "0.51053077", "0.5097169", "0.5091077", "0.50818765", "0.5081229", "0.5075297", "0.50680965", "0.50657165", "0.5061586", "0.50596637", "0.50579107", "0.5051221", "0.5047278", "0.50425416", "0.5042321", "0.50081784", "0.5005001", "0.50046897", "0.500391", "0.49998885", "0.499259", "0.49921843", "0.49895343", "0.4989202", "0.49890965", "0.49870715", "0.49856296", "0.49840823", "0.498281" ]
0.7586125
0
ShellExec exec command by shell cmdLine. eg: "ls al"
Выполняет команду exec через shell cmdLine. Например: "ls al"
func ShellExec(cmdLine string, shells ...string) (string, error) { // shell := "/bin/sh" shell := "sh" if len(shells) > 0 { shell = shells[0] } var out bytes.Buffer cmd := exec.Command(shell, "-c", cmdLine) cmd.Stdout = &out if err := cmd.Run(); err != nil { return "", err } return out.String(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ExecuteShell(ctx context.Context) interface{} {\n\treturn func(line string) (io.Reader, error) {\n\t\tc := exec.Command(\"sh\", \"-\")\n\n\t\tcopyDone := make(chan error)\n\t\ttimeout := time.After(ContextGetTimeout(ctx))\n\n\t\toutput := new(bytes.Buffer)\n\t\tif stdout, err := c.StdoutPipe(); err == nil {\n\t\t\tfanout := io.MultiWriter(os.Stdout, output)\n\t\t\tgo func() {\n\t\t\t\t_, err := io.Copy(fanout, stdout)\n\t\t\t\tcopyDone <- err\n\t\t\t}()\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif stderr, err := c.StderrPipe(); err == nil {\n\t\t\tgo func() {\n\t\t\t\tio.Copy(os.Stderr, stderr)\n\t\t\t}()\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t\tstdin, err := c.StdinPipe()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := c.Start(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err := stdin.Write([]byte(line)); err != nil {\n\t\t\tstdin.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\tstdin.Close() // finished\n\t\terr = c.Wait()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Waits for the stdout and stderr copy goroutines to complete.\n\t\tselect {\n\t\tcase err = <-copyDone:\n\t\t\tbreak\n\t\tcase <-timeout:\n\t\t\tbreak\n\t\t}\n\t\treturn output, err\n\t}\n}", "func ExecLine(cmdLine string, workDir ...string) (string, error) {\n\tp := cmdline.NewParser(cmdLine)\n\n\t// create a new Cmd instance\n\tcmd := p.NewExecCmd()\n\tif len(workDir) > 0 {\n\t\tcmd.Dir = workDir[0]\n\t}\n\n\tbs, err := cmd.Output()\n\treturn string(bs), err\n}", "func Shell(command []string, r bool) []byte {\n\tif command[2] == \"cd\" {\n\t\tvar dir string\n\t\tvar p string\n\t\tif strings.HasPrefix(command[3], \"..\") {\n\t\t\tpathBack := strings.Repeat(\"/../\", strings.Count(command[3], \"../\"))\n\t\t\tdir = filepath.Dir(cwd + pathBack)\n\t\t} else {\n\t\t\tdir = command[3]\n\t\t}\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tp = filepath.FromSlash(strings.TrimSuffix(dir, \"\\r\"))\n\t\t\tif _, err := os.Stat(p); os.IsNotExist(err) {\n\t\t\t\tif filepath.VolumeName(cwd) == \"\" {\n\t\t\t\t\tdriveLetter, err := filepath.Abs(p)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tErrHandling(err.Error())\n\t\t\t\t\t\tAllOutput.Mutex.Lock()\n\t\t\t\t\t\tJobCount++\n\t\t\t\t\t\tAllOutput.List[JobCount] = &agentscommon.JobOutput{\"error\", err.Error()}\n\t\t\t\t\t\tAllOutput.Mutex.Unlock()\n\t\t\t\t\t}\n\t\t\t\t\tp = filepath.VolumeName(driveLetter) + cwd + command[3]\n\t\t\t\t} else {\n\t\t\t\t\tp = cwd + \"\\\\\" + command[3]\n\t\t\t\t}\n\t\t\t}\n\t\t} else if runtime.GOOS == \"linux\" || runtime.GOOS == \"darwin\" {\n\t\t\tp = filepath.ToSlash(strings.TrimSuffix(dir, \"\\r\"))\n\t\t}\n\t\tcwd = strings.TrimSuffix(p, \"\\r\")\n\t}\n\t//Check to see if any data was sent in command[3]\n\tif len(strings.TrimSpace(command[2])) == 0 {\n\t\tresult := []byte(\"No command arguments where passed\")\n\t\tif r {\n\t\t\treturn result\n\t\t} else {\n\t\t\tAllOutput.Mutex.Lock()\n\t\t\tJobCount++\n\t\t\tAllOutput.List[JobCount] = &agentscommon.JobOutput{\"error\", string(result)}\n\t\t\tAllOutput.Mutex.Unlock()\n\t\t\treturn nil\n\t\t}\n\n\t} else {\n\t\t//Executing shell and the arguments that follow\n\t\tresult := shellexec.ShellExecute(command, cwd)\n\n\t\tif r {\n\t\t\treturn result\n\t\t} else {\n\t\t\tAllOutput.Mutex.Lock()\n\t\t\tJobCount++\n\t\t\tAllOutput.List[JobCount] = &agentscommon.JobOutput{\"shell\", string(result)}\n\t\t\tAllOutput.Mutex.Unlock()\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func main() {\n\n // Go requires an absolute path to the binary we want to execute, so we’ll use exec.LookPath to find it (probably /bin/ls).\n // Exec requires arguments in slice form (as apposed to one big string).\n binary, lookErr := exec.LookPath(\"ls\")\n if lookErr != nil {\n panic(lookErr)\n }\n\n args := []string{\"ls\", \"-a\", \"-l\", \"-h\"} //Exec requires arguments in slice form (as apposed to one big string). first argument should be the program name\n\n //Exec also needs a set of environment variables to use. Here we just provide our current environment.\n env := os.Environ()\n\n execErr := syscall.Exec(binary, args, env) //Here’s the actual syscall.Exec call.\n //If this call is successful, the execution of our process will end here and be replaced by the /bin/ls -a -l -h process.\n if execErr != nil {// If there is an error we’ll get a return value.\n panic(execErr)\n }\n}", "func CmdExec(usercommand string) []string {\n\tcmd := exec.Command(\"sh\", \"-c\", usercommand)\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\tlog.Fatalf(\"cmd.Run() failed with %s\\n\", err)\n\t}\n\t//using \"\\n\" will append an empty line to the end of the resArray\n\tresArray := strings.Split(string(out), \"\\n\")\n\t//delete the last and empty element\n\tresArray = resArray[:len(resArray)-1]\n\treturn resArray\n}", "func executeShell(ctx context.Context, context ActionExecutionContext) error {\n\t//log.Printf(\"Exec: %s\", context.Action.Shell)\n\t//cmdAndArgs := strings.Split(s.Shell, \" \")\n\t//cmd := cmdAndArgs[0]\n\t//args := cmdAndArgs[1:]\n\tshuttlePath, _ := filepath.Abs(filepath.Dir(os.Args[0]))\n\n\tcmdOptions := go_cmd.Options{\n\t\tBuffered: false,\n\t\tStreaming: true,\n\t}\n\n\texecCmd := go_cmd.NewCmdOptions(cmdOptions, \"sh\", \"-c\", \"cd '\"+context.ScriptContext.Project.ProjectPath+\"'; \"+context.Action.Shell)\n\n\t//execCmd := exec.Command(\"sh\", \"-c\", context.Action.Shell)\n\texecCmd.Env = os.Environ()\n\tfor name, value := range context.ScriptContext.Args {\n\t\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"%s=%s\", name, value))\n\t}\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"plan=%s\", context.ScriptContext.Project.LocalPlanPath))\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"tmp=%s\", context.ScriptContext.Project.TempDirectoryPath))\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"project=%s\", context.ScriptContext.Project.ProjectPath))\n\t// TODO: Add project path as a shuttle specific ENV\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"PATH=%s\", shuttlePath+string(os.PathListSeparator)+os.Getenv(\"PATH\")))\n\texecCmd.Env = append(execCmd.Env, fmt.Sprintf(\"SHUTTLE_PLANS_ALREADY_VALIDATED=%s\", context.ScriptContext.Project.LocalPlanPath))\n\n\tdoneChan := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneChan)\n\t\tfor execCmd.Stdout != nil || execCmd.Stderr != nil {\n\t\t\tselect {\n\t\t\tcase line, open := <-execCmd.Stdout:\n\t\t\t\tif !open {\n\t\t\t\t\texecCmd.Stdout = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcontext.ScriptContext.Project.UI.Infoln(\"%s\", line)\n\t\t\tcase line, open := <-execCmd.Stderr:\n\t\t\t\tif !open {\n\t\t\t\t\texecCmd.Stderr = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcontext.ScriptContext.Project.UI.Errorln(\"%s\", line)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Run and wait for Cmd to return, discard Status\n\tcontext.ScriptContext.Project.UI.Titleln(\"shell: %s\", context.Action.Shell)\n\n\t// stop cmd if context is cancelled\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\terr := execCmd.Stop()\n\t\t\tif err != nil {\n\t\t\t\tcontext.ScriptContext.Project.UI.Errorln(\"Failed to stop script '%s': %v\", context.Action.Shell, err)\n\t\t\t}\n\t\tcase <-doneChan:\n\t\t}\n\t}()\n\n\tselect {\n\tcase status := <-execCmd.Start():\n\t\t<-doneChan\n\t\tif status.Exit > 0 {\n\t\t\treturn errors.NewExitCode(4, \"Failed executing script `%s`: shell script `%s`\\nExit code: %v\", context.ScriptContext.ScriptName, context.Action.Shell, status.Exit)\n\t\t}\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func ExecCommand(commandLine string) (*exec.Cmd, error) {\n\n\tvar args, err = shellquote.Split(commandLine)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exec.Command(args[0], args[1:]...), nil // #nosec\n\n}", "func WrapExec(cmd string, args []String, nArg uint32) (status syscall.Status){\n\n\n\tpath := \"/programs/\"+cmd\n\n\tif nArg == 0 {\n\n\t\tstatus = altEthos.Exec(path)\n\n\t} else if nArg == 1 {\n\n\t\tstatus = altEthos.Exec(path, &args[0])\n\n\t} else if nArg == 2 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1])\n\n\t} else if nArg == 3 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1], &args[2])\n\n\t} else if nArg == 4 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1], &args[2], &args[3])\n\n\t}\n\n\treturn\n\n}", "func Shell(shellStdin string) (stdout, stderr string, err error) {\n\treturn Exec(\"sh\", \"\", shellStdin)\n}", "func Shell(cmd string, arg ...string) error {\n\tfmt.Println(cmd, strings.Join(arg, \" \"))\n\texe := exec.Command(cmd, arg...)\n\texe.Env = os.Environ()\n\texe.Stderr = os.Stderr\n\texe.Stdout = os.Stdout\n\texe.Stdin = os.Stdin\n\n\tif err := exe.Run(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func processLine(cmdLine string) {\n\tcmdLine = strings.TrimSpace(cmdLine)\n\n\tcommandList := make([]exec.Cmd, 0)\n\n\tif len(cmdLine) == 0 {\n\t\treturn\n\t}\n\n\tpipeStages := strings.Split(cmdLine, pipeChar)\n\n\terr := createPipeStages(&commandList, pipeStages)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v: %v.\\n\", shellName, err)\n\t\treturn\n\t}\n\n\terr = connectPipeline(commandList)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v: Error with pipes: %v.\\n\", shellName, err)\n\t\treturn\n\t}\n\n\terr = executePipeline(commandList)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v: Error during execution: %v\\n\", shellName, err)\n\t\treturn\n\t}\n}", "func Shell(t *testing.T, name string, arg ...string) {\n\tt.Helper()\n\n\tbin, err := exec.LookPath(name)\n\tif err != nil {\n\t\tt.Skipf(\"skipping, binary %q not found: %v\", name, err)\n\t}\n\n\tt.Logf(\"$ %s %v\", bin, arg)\n\n\tcmd := exec.Command(bin, arg...)\n\tif err := cmd.Start(); err != nil {\n\t\tt.Fatalf(\"failed to start command %q: %v\", name, err)\n\t}\n\n\tif err := cmd.Wait(); err != nil {\n\t\t// Shell operations in these tests require elevated privileges.\n\t\tif cmd.ProcessState.ExitCode() == 1 /* unix.EPERM */ {\n\t\t\tt.Skipf(\"skipping, permission denied: %v\", err)\n\t\t}\n\n\t\tt.Fatalf(\"failed to wait for command %q: %v\", name, err)\n\t}\n}", "func execShCmd(strCmd string) ([]byte, error) {\n\tlog.Debug(\"Executing %+v\", strCmd)\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", strCmd)\n\n\tstdoutpipe, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Error(\"Error stdout: %s. for command: %s\", err, strCmd)\n\t\treturn nil, err\n\t}\n\tstderrpipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tlog.Error(\"Error stderr: %s. for command: %s\", err, strCmd)\n\t\treturn nil, err\n\t}\n\terr = cmd.Start()\n\tif err != nil {\n\t\tlog.Error(\"Error: %s. for command: %s\", err, strCmd)\n\t\treturn nil, err\n\t}\n\tstdout, errstderr := ioutil.ReadAll(stdoutpipe)\n\tstderr, errstdout := ioutil.ReadAll(stderrpipe)\n\n\tcmderr := cmd.Wait()\n\n\tif errstderr != nil {\n\t\tlog.Debug(\"Stdout err: %v\", errstderr)\n\t}\n\tif errstdout != nil {\n\t\tlog.Debug(\"Stderr err: %v\", errstdout)\n\t}\n\tlog.Debug(\"Stdout is: '%s'\\n\", stdout)\n\tlog.Debug(\"Stderr is: '%s'\\n\", stderr)\n\tif cmderr != nil {\n\t\tlog.Error(\"cmderr: %v, %v\", cmderr, string(stderr))\n\t}\n\treturn stdout, cmderr\n}", "func execShCmd(strCmd string) ([]byte, error) {\n\tlog.Debug(\"Executing %+v\", strCmd)\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", strCmd)\n\n\tstdoutpipe, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Error(\"Error stdout: %s. for command: %s\", err, strCmd)\n\t\treturn nil, err\n\t}\n\tstderrpipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tlog.Error(\"Error stderr: %s. for command: %s\", err, strCmd)\n\t\treturn nil, err\n\t}\n\terr = cmd.Start()\n\tif err != nil {\n\t\tlog.Error(\"Error: %s. for command: %s\", err, strCmd)\n\t\treturn nil, err\n\t}\n\tstdout, errstderr := ioutil.ReadAll(stdoutpipe)\n\tstderr, errstdout := ioutil.ReadAll(stderrpipe)\n\n\tcmderr := cmd.Wait()\n\n\tif errstderr != nil {\n\t\tlog.Debug(\"Stdout err: %v\", errstderr)\n\t}\n\tif errstdout != nil {\n\t\tlog.Debug(\"Stderr err: %v\", errstdout)\n\t}\n\tlog.Debug(\"Stdout is: '%s'\\n\", stdout)\n\tlog.Debug(\"Stderr is: '%s'\\n\", stderr)\n\tif cmderr != nil {\n\t\tlog.Error(\"cmderr: %v, %v\", cmderr, string(stderr))\n\t}\n\treturn stdout, cmderr\n}", "func execInSystem(execPath string, params []string, logsBuffer *bytes.Buffer, print bool) error {\n\tvar lock sync.Mutex\n\tvar c string\n\tvar cmdName string\n\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\tc = \"-c\"\n\t\tcmdName = \"sh\"\n\tcase \"windows\":\n\t\tc = \"/c\"\n\t\tcmdName = \"cmd\"\n\tdefault:\n\t\tlog.Panicf(\"System type error, got <%s>, but expect linux/windowns!\", runtime.GOOS)\n\t}\n\n\tcmd := exec.Command(cmdName, append(params, c)...)\n\tcmd.Dir = execPath\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// print log\n\toutReader := bufio.NewReader(stdout)\n\terrReader := bufio.NewReader(stderr)\n\tprintLog := func(reader *bufio.Reader, typex string) {\n\t\tfor {\n\t\t\tline, err := reader.ReadString('\\n')\n\t\t\tif print {\n\t\t\t\tlog.Printf(\"%s: %s\", typex, line)\n\t\t\t}\n\t\t\tif logsBuffer != nil {\n\t\t\t\tlock.Lock()\n\t\t\t\tlogsBuffer.WriteString(line)\n\t\t\t\tlock.Unlock()\n\t\t\t}\n\t\t\tif err != nil || err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tprintLog(outReader, \"Stdout\")\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tprintLog(errReader, \"Stderr\")\n\t}()\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twg.Wait()\n\treturn cmd.Wait()\n}", "func (e *Executor) ExecWithTimeoutShell(target Target, dir string, env []string, timeout time.Duration, showOutput, foreground bool, sandbox SandboxConfig, cmd string) ([]byte, []byte, error) {\n\treturn e.ExecWithTimeoutShellStdStreams(target, dir, env, timeout, showOutput, foreground, sandbox, cmd, false)\n}", "func (c *Cluster) RunShell(cmd string, values interface{}, extraEnv []string) error {\n\terr := c.writeValuesYaml(values)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Collect environment variables\n\tenv := append(os.Environ(), MapToEnv(values, \"VALUE_\")...)\n\tenv = append(env, extraEnv...)\n\tenv = append(env, \"HOME=\"+c.Path)\n\n\topt := exe.Opt{\n\t\tDir: c.Path,\n\t\tEnv: env,\n\t}\n\n\t_, _, err = exe.Run(\"bash\", exe.Args{\"-c\", cmd}, opt, c.log)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func shellExecutor(rootCmd *cobra.Command, printer *Printer, meta *meta) func(s string) {\n\treturn func(s string) {\n\t\targs := strings.Fields(s)\n\n\t\tsentry.AddCommandContext(strings.Join(removeOptions(args), \" \"))\n\n\t\trootCmd.SetArgs(meta.CliConfig.Alias.ResolveAliases(args))\n\n\t\terr := rootCmd.Execute()\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*interactive.InterruptError); ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tprintErr := printer.Print(err, nil)\n\t\t\tif printErr != nil {\n\t\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\t// command is nil if it does not have a Run function\n\t\t// ex: instance -h\n\t\tif meta.command == nil {\n\t\t\treturn\n\t\t}\n\n\t\tautoCompleteCache.Update(meta.command.Namespace)\n\n\t\tprintErr := printer.Print(meta.result, meta.command.getHumanMarshalerOpt())\n\t\tif printErr != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, printErr)\n\t\t}\n\t}\n}", "func RunShellCmd(rb RunningBuild, step *vts.BuildStep, o, e io.Writer) error {\n\tif len(step.Args) > 0 {\n\t\tstep.Args[0] = \"set +h;umask 022;\" + step.Args[0]\n\t}\n\t_, err := rb.ExecBlocking(\"/tmp\", append([]string{\"/bin/bash\", \"-c\"}, step.Args...), o, e)\n\treturn err\n}", "func (r RealExecute) ExecCommand(com string, args ...string) ([]byte, error) {\n\t/* #nosec */\n\tcommand := exec.Command(com, args...)\n\treturn command.CombinedOutput()\n}", "func (pm *Manager) Exec(desc, cmdName string, args ...string) (string, string, error) {\n\treturn pm.ExecDir(-1, \"\", desc, cmdName, args...)\n}", "func ExecuteShell(\n\tcliConfig schema.CliConfiguration,\n\tcommand string,\n\tname string,\n\tdir string,\n\tenv []string,\n\tdryRun bool,\n) error {\n\tu.LogDebug(cliConfig, \"\\nExecuting command:\")\n\tu.LogDebug(cliConfig, command)\n\n\tif dryRun {\n\t\treturn nil\n\t}\n\n\treturn shellRunner(command, name, dir, env, os.Stdout)\n}", "func exec(c *lxc.Container, conf *Config) {\n\tvar output []byte\n\tvar err error\n\t// stdout and stderr are unfornutately concatenated\n\tif output, err = c.Execute(conf.Args.Command...); err != nil {\n\t\tif len(output) != 0 {\n\t\t\tfmt.Printf(\"%s\\n\", output)\n\t\t}\n\t\terrorExit(2, err)\n\t} else {\n\t\tfmt.Printf(\"%s\", output)\n\t}\n}", "func Shell(c *cli.Context) error {\n\treturn subShell(c.String(\"name\"), c.String(\"shell\"), c.String(\"command\"))\n}", "func execTerraformShellCommand(\n\tcliConfig schema.CliConfiguration,\n\tcomponent string,\n\tstack string,\n\tcomponentEnvList []string,\n\tvarFile string,\n\tworkingDir string,\n\tworkspaceName string,\n\tcomponentPath string) error {\n\n\tcomponentEnvList = append(componentEnvList, fmt.Sprintf(\"TF_CLI_ARGS_plan=-var-file=%s\", varFile))\n\tcomponentEnvList = append(componentEnvList, fmt.Sprintf(\"TF_CLI_ARGS_apply=-var-file=%s\", varFile))\n\tcomponentEnvList = append(componentEnvList, fmt.Sprintf(\"TF_CLI_ARGS_refresh=-var-file=%s\", varFile))\n\tcomponentEnvList = append(componentEnvList, fmt.Sprintf(\"TF_CLI_ARGS_import=-var-file=%s\", varFile))\n\tcomponentEnvList = append(componentEnvList, fmt.Sprintf(\"TF_CLI_ARGS_destroy=-var-file=%s\", varFile))\n\tcomponentEnvList = append(componentEnvList, fmt.Sprintf(\"TF_CLI_ARGS_console=-var-file=%s\", varFile))\n\n\tu.LogDebug(cliConfig, \"\\nStarting a new interactive shell where you can execute all native Terraform commands (type 'exit' to go back)\")\n\tu.LogDebug(cliConfig, fmt.Sprintf(\"Component: %s\\n\", component))\n\tu.LogDebug(cliConfig, fmt.Sprintf(\"Stack: %s\\n\", stack))\n\tu.LogDebug(cliConfig, fmt.Sprintf(\"Working directory: %s\\n\", workingDir))\n\tu.LogDebug(cliConfig, fmt.Sprintf(\"Terraform workspace: %s\\n\", workspaceName))\n\tu.LogDebug(cliConfig, \"\\nSetting the ENV vars in the shell:\\n\")\n\tfor _, v := range componentEnvList {\n\t\tu.LogDebug(cliConfig, v)\n\t}\n\n\t// Transfer stdin, stdout, and stderr to the new process and also set the target directory for the shell to start in\n\tpa := os.ProcAttr{\n\t\tFiles: []*os.File{os.Stdin, os.Stdout, os.Stderr},\n\t\tDir: componentPath,\n\t\tEnv: append(os.Environ(), componentEnvList...),\n\t}\n\n\t// Start a new shell\n\tvar shellCommand string\n\n\tif runtime.GOOS == \"windows\" {\n\t\tshellCommand = \"cmd.exe\"\n\t} else {\n\t\t// If 'SHELL' ENV var is not defined, use 'bash' shell\n\t\tshellCommand = os.Getenv(\"SHELL\")\n\t\tif len(shellCommand) == 0 {\n\t\t\tbashPath, err := exec.LookPath(\"bash\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tshellCommand = bashPath\n\t\t}\n\t\tshellCommand = shellCommand + \" -l\"\n\t}\n\n\tu.LogDebug(cliConfig, fmt.Sprintf(\"Starting process: %s\\n\", shellCommand))\n\n\targs := strings.Fields(shellCommand)\n\n\tproc, err := os.StartProcess(args[0], args[1:], &pa)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait until user exits the shell\n\tstate, err := proc.Wait()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.LogDebug(cliConfig, fmt.Sprintf(\"Exited shell: %s\\n\", state.String()))\n\treturn nil\n}", "func (client *ExternalClient) Shell(pty bool, args ...string) error {\n\targs = append(client.BaseArgs, args...)\n\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func (player *Player) ExecAs(commandLine string, callback func(statusCode int)) {\n\tplayer.Exec(fmt.Sprintf(\"execute %v ~ ~ ~ %v\", player.name, commandLine), func(response map[string]interface{}) {\n\t\tcodeInterface, exists := response[\"statusCode\"]\n\t\tif !exists {\n\t\t\tlog.Printf(\"exec as: invalid response JSON\")\n\t\t\treturn\n\t\t}\n\t\tcode, _ := codeInterface.(int)\n\t\tif callback != nil {\n\t\t\tcallback(code)\n\t\t}\n\t})\n}", "func comandoExec(comando string) {\n\tfmt.Println(\"\\nEJECUTANDO: \" + comando)\n\ts := strings.Split(comando, \" -\")\n\tif len(s) == 2 {\n\t\ts2 := strings.Split(s[1], \"->\")\n\t\tif strings.Compare(s2[0], \"path\") == 0 {\n\t\t\t_, err := os.Stat(strings.ReplaceAll(s2[1], \"\\\"\", \"\"))\n\t\t\tif err == nil {\n\t\t\t\ts3 := strings.Split(s2[1], \".\")\n\t\t\t\tif strings.Compare(s3[1], \"mia\") == 0 {\n\t\t\t\t\tfmt.Println(\"RESULTADO: Lectura de archivo\")\n\t\t\t\t\tfmt.Println(\"\")\n\t\t\t\t\tarchivo := leerArchivo(s2[1])\n\t\t\t\t\t//mandar a analizar ese archivo\n\t\t\t\t\tanalizarArchivo(archivo)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"RESULTADO: La extension del archivo debe ser .MIA\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"RESULTADO: No existe el archivo especificado\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"RESULTADO: El parametro PATH es obligatorio\")\n\t\t}\n\t} else if len(s) > 2 {\n\t\tfmt.Println(\"RESULTADO: Demasiados parametros para el comando EXEC\")\n\t} else {\n\t\tfmt.Println(\"RESULTADO: Faltan parametros para el comando EXEC\")\n\t}\n}", "func execute(w io.Writer, commandline string, req io.Reader) error {\n\targv, err := cmd.SplitQuoted(commandline)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We treat a pipe command specially.\n\t// It will be splitted by the pipe binary.\n\tif strings.HasPrefix(commandline, \"pipe \") {\n\t\targv = []string{\"pipe\", commandline[5:]}\n\t}\n\n\tif len(argv) < 1 {\n\t\treturn fmt.Errorf(\"request contains no command\")\n\t}\n\n\t// Get installation directory of editor binary.\n\t// All subcommands must be in the same directory.\n\tvar installDir string\n\tprogname := os.Args[0]\n\tif p, err := filepath.Abs(progname); err != nil {\n\t\treturn fmt.Errorf(\"cannot get editor directory\")\n\t} else {\n\t\tinstallDir = filepath.Dir(p)\n\t}\n\n\tvar buf bytes.Buffer\n\tvar errbuf bytes.Buffer\n\targv[0] = filepath.Join(installDir, argv[0])\n\tctx, cancel := context.WithCancel(context.Background())\n\tc := exec.CommandContext(ctx, argv[0], argv[1:]...)\n\tc.Stdin = req\n\tc.Stdout = &buf\n\tc.Stderr = &errbuf\n\tif err := c.Start(); err != nil {\n\t\treturn err\n\t}\n\tpid := c.Process.Pid\n\tProcessList.Add(pid, argv, cancel)\n\n\terr = c.Wait()\n\tProcessList.Remove(pid)\n\tio.Copy(w, &buf)\n\n\t// Write stderr of commands to the console.\n\tif errbuf.Len() > 0 {\n\t\tif err != nil {\n\t\t\terrmsg, _ := ioutil.ReadAll(&errbuf)\n\t\t\terr = fmt.Errorf(\"%s\\n%s\\n\", err.Error(), string(errmsg))\n\t\t} else {\n\t\t\tio.Copy(os.Stdout, &errbuf)\n\t\t}\n\t}\n\treturn err\n}", "func (s pathRuntime) Exec(args []string) error {\n\truntimeArgs := []string{s.path}\n\tif len(args) > 1 {\n\t\truntimeArgs = append(runtimeArgs, args[1:]...)\n\t}\n\n\treturn s.execRuntime.Exec(runtimeArgs)\n}", "func Exec(cmd string) {\n\n\tfmt.Printf(\"Você digitou: %s \", cmd)\n\n}", "func execCmd(args []string) {\n\tvar (\n\t\tcmd *exec.Cmd\n\t)\n\n\t// Prepare command with arguments\n\tcmd = exec.Command(binary, args...)\n\n\t// redirect stdout/err/in\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdin = os.Stdin\n\n\t// Execute command\n\tcmd.Run()\n}", "func sysExec(args ...OBJ) OBJ {\n\tif len(args) < 1 {\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tvar command string\n\tswitch c := args[0].(type) {\n\tcase *object.String:\n\t\tcommand = c.Value\n\tdefault:\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tif len(command) < 1 {\n\t\treturn NewError(\"`sys.exec` expected string, got invalid argument\")\n\t}\n\t// split the command\n\ttoExec := splitCommand(command)\n\tcmd := exec.Command(toExec[0], toExec[1:]...)\n\n\t// get the result\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout = &outb\n\tcmd.Stderr = &errb\n\terr := cmd.Run()\n\n\t// If the command exits with a non-zero exit-code it\n\t// is regarded as a failure. Here we test for ExitError\n\t// to regard that as a non-failure.\n\tif err != nil && err != err.(*exec.ExitError) {\n\t\tfmt.Printf(\"Failed to run '%s' -> %s\\n\", command, err.Error())\n\t\treturn &object.Error{Message: \"Failed to run command!\"}\n\t}\n\n\t// The result-objects to store in our hash.\n\tstdout := &object.String{Value: outb.String()}\n\tstderr := &object.String{Value: errb.String()}\n\n\treturn NewHash(StringObjectMap{\n\t\t\"stdout\": stdout,\n\t\t\"stderr\": stderr,\n\t})\n}", "func SimpleExecInPath(dir, cmdName string, arguments ...string) {\n\tcmd := exec.Command(cmdName, arguments...) // nolint: gosec\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Dir = dir\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Exec(name string, arg ...string) error {\n\tcmd := exec.Command(name, arg...)\n\tif len(cmdExePath) != 0 {\n\t\tcmd.Dir = cmdExePath\n\t\tcmdExePath = \"\"\n\t}\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Fatal(\"error: \", string(output), err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Run(dir string, commandLine string) ([]byte, error) {\n\n\t// Split commandLine into an array separated by whitespace\n\targs := strings.Fields(commandLine)\n\tcmd := exec.Command(args[0], args[1:]...)\n\tcmd.Dir = dir\n\tvar buf bytes.Buffer\n\tcmd.Stdout = &buf\n\tcmd.Stderr = &buf\n\terr := cmd.Run()\n\tout := buf.Bytes()\n\tif err != nil {\n\t\treturn out, err\n\t}\n\treturn out, nil\n}", "func shellRunner(command string, name string, dir string, env []string, out io.Writer) error {\n\tparser, err := syntax.NewParser().Parse(strings.NewReader(command), name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenviron := append(os.Environ(), env...)\n\tlistEnviron := expand.ListEnviron(environ...)\n\trunner, err := interp.New(\n\t\tinterp.Dir(dir),\n\t\tinterp.Env(listEnviron),\n\t\tinterp.StdIO(os.Stdin, out, os.Stderr),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn runner.Run(context.TODO(), parser)\n}", "func (ne *NSEnter) Exec(cmd string, args []string) exec.Cmd {\n\thostProcMountNsPath := filepath.Join(ne.hostRootFsPath, mountNsPath)\n\tfullArgs := append([]string{fmt.Sprintf(\"--mount=%s\", hostProcMountNsPath), \"--\"},\n\t\tappend([]string{ne.AbsHostPath(cmd)}, args...)...)\n\tklog.V(5).Infof(\"Running nsenter command: %v %v\", nsenterPath, fullArgs)\n\treturn ne.executor.Command(nsenterPath, fullArgs...)\n}", "func (e *editorConfig) execCmd(cmd string) error {\n\t// Multiple commands may be concatenated with '|'\n\t// Split these and run them recursively\n\tcmds := strings.SplitN(cmd, \"|\", 2)\n\tif len(cmds) > 1 {\n\t\tif err := e.execCmd(cmds[0]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn e.execCmd(cmds[1])\n\t}\n\tcmd = strings.TrimSpace(cmds[0])\n\n\targs := strings.Split(cmd, \" \")\n\tcmd, params := args[0], args[1:]\n\n\t// If command is a number: go to that line\n\tif n, err := strconv.Atoi(cmd); err == nil {\n\t\t// First, check for relative numbers, starting with + or -\n\t\tif cmd[0] == '+' || cmd[0] == '-' {\n\t\t\tn = e.cy + n\n\t\t} else {\n\t\t\t// Absolute number, adjust for e.cy starting from 0\n\t\t\t// versus user input starting from 1\n\t\t\tn = n - 1\n\t\t}\n\n\t\t// Check boundaries and set cy\n\t\te.cy = n\n\t\te.safeCursor()\n\t\treturn nil\n\t}\n\n\tswitch cmd {\n\tcase \"$\":\n\t\treturn e.execCmd(strconv.Itoa(len(e.row)))\n\tcase \"delete\", \"d\":\n\t\tif len(params) == 0 {\n\t\t\tparams = []string{\"1\"}\n\t\t}\n\t\tn, err := strconv.Atoi(params[0])\n\t\tif err != nil {\n\t\t\tn = 1\n\t\t}\n\t\te.register.Reset()\n\t\tfor i := 0; i < n; i++ {\n\t\t\te.register.Write(e.row[e.cy].chars)\n\t\t\tif i != n-1 {\n\t\t\t\te.register.Write([]byte(newline))\n\t\t\t}\n\t\t\te.delRow(e.cy)\n\t\t}\n\tcase \"join\":\n\t\te.cx = e.rowLen(e.cy)\n\t\te.delRune()\n\t\tif e.rowLen(e.cy) > e.cx {\n\t\t\te.insertRune(' ')\n\t\t}\n\t\tfor e.rowLen(e.cy) > e.cx && strings.ContainsRune(\" \\t\", rune(e.row[e.cy].chars[e.cx])) {\n\t\t\te.delRune()\n\t\t}\n\t\treturn nil\n\tcase \"put\", \"pu\":\n\t\te.insertRow(e.cy, e.register.Bytes())\n\tcase \"quit\", \"q\":\n\t\tif e.dirty > 0 {\n\t\t\te.setStatusMessage(\"File has unsaved changes!!!\")\n\t\t\treturn nil\n\t\t}\n\t\treturn errQuit\n\tcase \"q!\":\n\t\treturn errQuit\n\tcase \"write\", \"w\":\n\t\tif len(params) > 0 {\n\t\t\tif _, err := os.Stat(params[0]); !os.IsNotExist(err) {\n\t\t\t\treturn errors.New(\"file exists already\")\n\t\t\t}\n\t\t\te.filename = params[0]\n\t\t}\n\t\tn, err := e.fileBuffer.save()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Can't save file: %w\", err)\n\t\t}\n\t\te.setStatusMessage(\"%d bytes written to disk\", n)\n\tcase \"wq\":\n\t\treturn e.execCmd(\"write|quit\")\n\tcase \"yank\", \"ya\":\n\t\tif len(params) == 0 {\n\t\t\tparams = []string{\"1\"}\n\t\t}\n\t\tn, err := strconv.Atoi(params[0])\n\t\tif err != nil {\n\t\t\tn = 1\n\t\t}\n\t\te.register.Reset()\n\t\tfor i := 0; i < n; i++ {\n\t\t\te.register.Write(e.row[e.cy+i].chars)\n\t\t\tif i != n-1 {\n\t\t\t\te.register.Write([]byte(newline))\n\t\t\t}\n\t\t}\n\tdefault:\n\t\te.setStatusMessage(\"Unknown command %q\", cmd)\n\t}\n\treturn nil\n}", "func ExecuteShellAndReturnOutput(\n\tcliConfig schema.CliConfiguration,\n\tcommand string,\n\tname string,\n\tdir string,\n\tenv []string,\n\tdryRun bool,\n) (string, error) {\n\tvar b bytes.Buffer\n\n\tu.LogDebug(cliConfig, \"\\nExecuting command:\")\n\tu.LogDebug(cliConfig, command)\n\n\tif dryRun {\n\t\treturn \"\", nil\n\t}\n\n\terr := shellRunner(command, name, dir, env, &b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn b.String(), nil\n}", "func RemoteShell(remoteHost, remoteShellStdin string) (stdout, stderr string, err error) {\n\treturn Exec(\"ssh\", \"\", remoteShellStdin, remoteHost, \"sh -il\")\n}", "func RunShellCommand(shell string) (string, error) {\n\tvar out, berr bytes.Buffer\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", shell)\n\tcmd.Stdout = &out\n\tcmd.Stderr = &berr\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn out.String(), fmt.Errorf(\"err:%v berr:%v\", err, berr.String())\n\t}\n\n\treturn out.String() + berr.String(), nil\n}", "func execCmd(dir, arg0 string, args ...string) error {\n\tcmd := exec.Command(arg0, args...)\n\tcmd.Env = os.Environ()\n\tcmd.Dir = dir\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func (git *Git) Exec(subcmd string, args ...string) (string, error) {\n\tb, err := git.Command(subcmd, args...).CombinedOutput()\n\n\t// Chop last newline\n\tl := len(b)\n\tif l > 0 && b[l-1] == '\\n' {\n\t\tb = b[:l-1]\n\t}\n\n\t// Make output in oneline in error cases\n\tif err != nil {\n\t\tfor i := range b {\n\t\t\tif b[i] == '\\n' {\n\t\t\t\tb[i] = ' '\n\t\t\t}\n\t\t}\n\t}\n\n\treturn string(b), err\n}", "func (ssh *SSHConfig) Exec(cmdString string) error {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tbash, err := exec.LookPath(\"bash\")\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tvar args []string\n\tif cmdString == \"\" {\n\t\targs = []string{sshCmdString}\n\t} else {\n\t\targs = []string{\"-c\", sshCmdString}\n\t}\n\terr = syscall.Exec(bash, args, nil)\n\tnerr := utils.LazyRemove(keyFile.Name())\n\tif nerr != nil {\n\t}\n\treturn err\n}", "func ExecExternal(dir string,name string, arg ...string) (outStr string, errStr string, err error) {\n\tcmd := exec.Command(name, arg...)\n\tif dir != \"\"{\n\t\tcmd.Dir = dir\n\t}\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr = cmd.Run()\n\n\toutStr, errStr = string(stdout.Bytes()), string(stderr.Bytes())\n\n\treturn outStr, errStr, err\n}", "func Execute() {\n\tcmd := rootCmd\n\trootCmdWithShell := *rootCmd\n\trootCmdWithShell.AddCommand(shellCmd)\n\tfoundCmd, _, err := rootCmdWithShell.Find(os.Args[1:])\n\tif err == nil && foundCmd.Use == \"shell\" {\n\t\tcmd = shellCmd\n\t}\n\tif err := cmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func QuickExec(cmdLine string, workDir ...string) (string, error) {\n\treturn ExecLine(cmdLine, workDir...)\n}", "func (e *Echo) Run(cmdStr string) string {\n\treturn exec.Run(e.Eval(cmdStr))\n}", "func (exec *Executhor) Exec(execArg []string) {\n\tif exec.execBuiltin(execArg) == nil {\n\t\treturn\n\t}\n\tpath, err := exec.getBinaryPath(execArg[0])\n\tif err == nil {\n\t\tpid := C.fork()\n\t\tif pid != 0 {\n\t\t\tvar status C.int\n\t\t\tC.wait(&status)\n\t\t} else {\n\t\t\tsyscall.Exec(path, execArg, exec.env.GetEnv())\n\t\t}\n\t} else {\n\t\tfmt.Println(err)\n\t}\n}", "func (sb *SecretBackend) execCommand(inputPayload string) ([]byte, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), sb.cmdTimeout)\n\tdefer cancel()\n\n\tcmd := exec.CommandContext(ctx, sb.cmd, sb.cmdArgs...)\n\n\tcmd.Stdin = strings.NewReader(inputPayload)\n\n\tstdout := limitBuffer{\n\t\tbuf: &bytes.Buffer{},\n\t\tmax: sb.cmdOutputMaxSize,\n\t}\n\tstderr := limitBuffer{\n\t\tbuf: &bytes.Buffer{},\n\t\tmax: sb.cmdOutputMaxSize,\n\t}\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\tif err := cmd.Run(); err != nil {\n\t\tif errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\treturn nil, fmt.Errorf(\"error while running '%s': command timeout\", sb.cmd)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"error while running '%s': %w\", sb.cmd, err)\n\t}\n\n\treturn stdout.buf.Bytes(), nil\n}", "func SimpleExec(cmdName string, arguments ...string) {\n\tcmd := exec.Command(cmdName, arguments...) // nolint: gosec\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (fs *Fs) ExecCommand(name string, args ...string) ([]byte, error) {\n\treturn exec.Command(name, args...).CombinedOutput() // #nosec G204\n}", "func Exec(container string, cmdLine ...string) (string, error) {\n\tparts := []string{\"exec\", \"-t\", container}\n\tparts = append(parts, cmdLine...)\n\tcmd := exec.Command(\"docker\", parts...)\n\toutput, err := cmd.CombinedOutput()\n\treturn string(output), err\n}", "func TestExecuteCmd(t *testing.T) {\n\tshell := CmdShell{}\n\tif _, err := shell.ExecuteCmd(invalidCmd); err == nil {\n\t\tt.Errorf(\"Cmd didn't error on invalid cmd\")\n\t}\n\n\tif validOutput, err := shell.ExecuteCmd(validCmd); validOutput == nil || err != nil || bytes.Equal(validOutput, []byte(\"hello\")) {\n\t\tt.Errorf(\"Cmd failed, expected %v, got %v\", \"hello\", string(validOutput))\n\t}\n}", "func RunCommand(custom string) (string, error) {\r\n custom = strings.TrimSpace(strings.TrimSuffix(custom, \"$\"))\r\n pieces := strings.Split(custom, \" \")\r\n cmd := exec.Command(pieces[0])\r\n cmd.Args = pieces\r\n cmd.Stdin = os.Stdin\r\n output, oops := cmd.CombinedOutput()\r\n return string(output), oops\r\n}", "func SystemExec(command string, args []string) *BuildahTestSession {\n\tfmt.Printf(\"Running: %s %s\\n\", command, strings.Join(args, \" \"))\n\tc := exec.Command(command, args...)\n\tsession, err := gexec.Start(c, GinkgoWriter, GinkgoWriter)\n\tif err != nil {\n\t\tFail(fmt.Sprintf(\"unable to run command: %s %s\", command, strings.Join(args, \" \")))\n\t}\n\treturn &BuildahTestSession{session}\n}", "func RunShell(ctx context.Context, printer *Printer, meta *meta, rootCmd *cobra.Command, args []string) {\n\tautoCompleteCache = cache.New()\n\tcompleter := NewShellCompleter(ctx)\n\n\tshellCobraCommand := getShellCommand(rootCmd)\n\tshellCobraCommand.InitDefaultHelpFlag()\n\t_ = shellCobraCommand.ParseFlags(args)\n\tif isHelp, _ := shellCobraCommand.Flags().GetBool(\"help\"); isHelp {\n\t\tshellCobraCommand.HelpFunc()(shellCobraCommand, args)\n\t\treturn\n\t}\n\n\t// remove shell command so it cannot be called from shell\n\trootCmd.RemoveCommand(shellCobraCommand)\n\tmeta.Commands.Remove(\"shell\", \"\")\n\n\texecutor := shellExecutor(rootCmd, printer, meta)\n\tp := prompt.New(\n\t\texecutor,\n\t\tcompleter.Complete,\n\t\tprompt.OptionPrefix(\">>> \"),\n\t\tprompt.OptionSuggestionBGColor(prompt.Purple),\n\t\tprompt.OptionSelectedSuggestionBGColor(prompt.Fuchsia),\n\t\tprompt.OptionSelectedSuggestionTextColor(prompt.White),\n\t\tprompt.OptionDescriptionBGColor(prompt.Purple),\n\t\tprompt.OptionSelectedDescriptionBGColor(prompt.Fuchsia),\n\t\tprompt.OptionSelectedDescriptionTextColor(prompt.White),\n\t)\n\tp.Run()\n}", "func (r *streamingRuntime) exec(containerID string, cmd []string, in io.Reader, out, errw io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize, timeout time.Duration) error {\n\tcontainer, err := checkContainerStatus(r.client, containerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.execHandler.ExecInContainer(r.client, container, cmd, in, out, errw, tty, resize, timeout)\n}", "func ExecuteShellCommand(\n\tcliConfig schema.CliConfiguration,\n\tcommand string,\n\targs []string,\n\tdir string,\n\tenv []string,\n\tdryRun bool,\n\tredirectStdError string,\n) error {\n\tcmd := exec.Command(command, args...)\n\tcmd.Env = append(os.Environ(), env...)\n\tcmd.Dir = dir\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\n\tif redirectStdError == \"\" {\n\t\tcmd.Stderr = os.Stderr\n\t} else {\n\t\tf, err := os.OpenFile(redirectStdError, os.O_RDWR|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func(f *os.File) {\n\t\t\terr = f.Close()\n\t\t\tif err != nil {\n\t\t\t\tu.LogWarning(cliConfig, err.Error())\n\t\t\t}\n\t\t}(f)\n\n\t\tcmd.Stderr = f\n\t}\n\n\tu.LogDebug(cliConfig, \"\\nExecuting command:\")\n\tu.LogDebug(cliConfig, cmd.String())\n\n\tif dryRun {\n\t\treturn nil\n\t}\n\n\treturn cmd.Run()\n}", "func Shell(format string, args ...interface{}) (string, error) {\n\treturn sh(format, true, args...)\n}", "func startShell(f resolver,obj interface{}){\n reader := bufio.NewReader(os.Stdin)\n fmt.Println(\"Accepting commands\")\n fmt.Println(\"---------------------\")\n var stop bool = false\n for ;!stop;{\n fmt.Print(\"-> \")\n text, _ := reader.ReadString('\\n')\n text = strings.Replace(text, \"\\n\", \"\", -1)\n args := strings.Split(text,\" \")\n if len(args)>1{\n fmt.Println(f(args[0],args[1:],obj))\n }else if len(args)==1{\n if args[0]==\"close\"{\n stop = true\n }else{\n fmt.Println(f(args[0],nil,obj))\n }\n }\n }\n}", "func ExecSubcommand(commands ...string) (string, error) {\n\tbytes, err := exec.Command(\"VBoxManage\", commands...).Output()\n\treturn strings.TrimSpace(string(bytes)), err\n}", "func (m *Manager) Exec(name string, opt ExecOptions, gOpt operator.Options) error {\n\tif err := clusterutil.ValidateClusterNameOrError(name); err != nil {\n\t\treturn err\n\t}\n\n\tmetadata, err := m.meta(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttopo := metadata.GetTopology()\n\tbase := metadata.GetBaseMeta()\n\n\tfilterRoles := set.NewStringSet(gOpt.Roles...)\n\tfilterNodes := set.NewStringSet(gOpt.Nodes...)\n\n\tvar shellTasks []task.Task\n\tuniqueHosts := map[string]set.StringSet{} // host-sshPort -> {command}\n\ttopo.IterInstance(func(inst spec.Instance) {\n\t\tkey := utils.JoinHostPort(inst.GetManageHost(), inst.GetSSHPort())\n\t\tif _, found := uniqueHosts[key]; !found {\n\t\t\tif len(gOpt.Roles) > 0 && !filterRoles.Exist(inst.Role()) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif len(gOpt.Nodes) > 0 && (!filterNodes.Exist(inst.GetHost()) && !filterNodes.Exist(inst.GetManageHost())) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcmds, err := renderInstanceSpec(opt.Command, inst)\n\t\t\tif err != nil {\n\t\t\t\tm.logger.Debugf(\"error rendering command with spec: %s\", err)\n\t\t\t\treturn // skip\n\t\t\t}\n\t\t\tcmdSet := set.NewStringSet(cmds...)\n\t\t\tif _, ok := uniqueHosts[key]; ok {\n\t\t\t\tuniqueHosts[key].Join(cmdSet)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tuniqueHosts[key] = cmdSet\n\t\t}\n\t})\n\n\tfor hostKey, i := range uniqueHosts {\n\t\thost, _ := utils.ParseHostPort(hostKey)\n\t\tfor _, cmd := range i.Slice() {\n\t\t\tshellTasks = append(shellTasks,\n\t\t\t\ttask.NewBuilder(m.logger).\n\t\t\t\t\tShell(host, cmd, hostKey+cmd, opt.Sudo).\n\t\t\t\t\tBuild())\n\t\t}\n\t}\n\n\tb, err := m.sshTaskBuilder(name, topo, base.User, gOpt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt := b.\n\t\tParallel(false, shellTasks...).\n\t\tBuild()\n\n\texecCtx := ctxt.New(\n\t\tcontext.Background(),\n\t\tgOpt.Concurrency,\n\t\tm.logger,\n\t)\n\tif err := t.Execute(execCtx); err != nil {\n\t\tif errorx.Cast(err) != nil {\n\t\t\t// FIXME: Map possible task errors and give suggestions.\n\t\t\treturn err\n\t\t}\n\t\treturn perrs.Trace(err)\n\t}\n\n\t// print outputs\n\tfor hostKey, i := range uniqueHosts {\n\t\thost, _ := utils.ParseHostPort(hostKey)\n\t\tfor _, cmd := range i.Slice() {\n\t\t\tstdout, stderr, ok := ctxt.GetInner(execCtx).GetOutputs(hostKey + cmd)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tm.logger.Infof(\"Outputs of %s on %s:\",\n\t\t\t\tcolor.CyanString(cmd),\n\t\t\t\tcolor.CyanString(host))\n\t\t\tif len(stdout) > 0 {\n\t\t\t\tm.logger.Infof(\"%s:\\n%s\", color.GreenString(\"stdout\"), stdout)\n\t\t\t}\n\t\t\tif len(stderr) > 0 {\n\t\t\t\tm.logger.Infof(\"%s:\\n%s\", color.RedString(\"stderr\"), stderr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (flower *Flower) Exec(commandName string, capture bool, args []string) (string, error) {\n\tflowerCommandData, err := flower.GetFlowerCommandData(commandName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar command []string\n\tif flowerCommandData.Workdir != \"\" {\n\t\tcommand = append([]string{\"cd\", flowerCommandData.Workdir, \"&&\"})\n\t}\n\n\tcommand = append([]string{flowerCommandData.Bin})\n\tfor _, arg := range args {\n\t\tcommand = append([]string{arg})\n\t}\n\n\tvar dockerExecOptions *DockerExecOptions\n\tswitch flowerCommandData.DockerExecOptions {\n\tcase nil:\n\t\tdockerExecOptions = flowerCommandData.DockerExecOptions\n\tdefault:\n\t\tdockerExecOptions = &DockerExecOptions{}\n\t}\n\n\treturn flower.Container.Exec(command, dockerExecOptions, capture)\n}", "func (l *CustomLambda) Execute(stdin io.Reader, args []string) (string, error) {\n\targsStr := strings.TrimSpace(strings.Join(args, \" \"))\n\tif argsStr != \"\" {\n\t\targsStr = \" \" + argsStr\n\t}\n\n\tcmd := exec.Command(\"bash\", \"-c\", l.command+argsStr)\n\n\t// pass through some stdin goodness\n\tcmd.Stdin = stdin\n\n\t// for those who are about to rock, I salute you.\n\tstdoutStderr, err := cmd.CombinedOutput()\n\n\tif err == nil {\n\t\t// noiiiice!\n\t\tlog.WithFields(log.Fields{\"name\": l.Name(), \"command\": l.command}).Info(\"Lambda Execution\")\n\t\treturn strings.TrimSpace(string(stdoutStderr)), nil\n\t}\n\n\t// *sigh*\n\tlog.WithFields(log.Fields{\"name\": l.Name(), \"command\": l.command}).Error(\"Lambda Execution\")\n\treturn string(stdoutStderr), errors.New(\"Error running command\")\n}", "func (r *streamingRuntime) exec(containerID string, cmd []string, in io.Reader, out, errw io.WriteCloser, tty bool, resize <-chan term.Size, timeout time.Duration) error {\n\tcontainer, err := checkContainerStatus(r.client, containerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.execHandler.ExecInContainer(r.client, container, cmd, in, out, errw, tty, resize, timeout)\n}", "func runShellAs(who, hname, ttype, cmd string, interactive bool, conn *xsnet.Conn, chaffing bool) (exitStatus uint32, err error) {\n\tvar wg sync.WaitGroup\n\tu, err := user.Lookup(who)\n\tif err != nil {\n\t\texitStatus = 1\n\t\treturn\n\t}\n\tvar uid, gid uint32\n\t_, _ = fmt.Sscanf(u.Uid, \"%d\", &uid) // nolint: gosec\n\t_, _ = fmt.Sscanf(u.Gid, \"%d\", &gid) // nolint: gosec\n\tlog.Println(\"uid:\", uid, \"gid:\", gid)\n\n\t// Need to clear server's env and set key vars of the\n\t// target user. This isn't perfect (TERM doesn't seem to\n\t// work 100%; ANSI/xterm colour isn't working even\n\t// if we set \"xterm\" or \"ansi\" here; and line count\n\t// reported by 'stty -a' defaults to 24 regardless\n\t// of client shell window used to run client.\n\t// Investigate -- rlm 2018-01-26)\n\tos.Clearenv()\n\t_ = os.Setenv(\"HOME\", u.HomeDir) // nolint: gosec\n\t_ = os.Setenv(\"TERM\", ttype) // nolint: gosec\n\t_ = os.Setenv(\"XS_SESSION\", \"1\") // nolint: gosec\n\n\tvar c *exec.Cmd\n\tif interactive {\n\t\tif useSysLogin {\n\t\t\t// Use the server's login binary (post-auth\n\t\t\t// which is still done via our own bcrypt file)\n\t\t\t// Things UNIX login does, like print the 'motd',\n\t\t\t// and use the shell specified by /etc/passwd, will be done\n\t\t\t// automagically, at the cost of another external tool\n\t\t\t// dependency.\n\t\t\t//\n\t\t\tc = exec.Command(xs.GetTool(\"login\"), \"-f\", \"-p\", who) // nolint: gosec\n\t\t} else {\n\t\t\tc = exec.Command(xs.GetTool(\"bash\"), \"-i\", \"-l\") // nolint: gosec\n\t\t}\n\t} else {\n\t\tc = exec.Command(xs.GetTool(\"bash\"), \"-c\", cmd) // nolint: gosec\n\t}\n\t//If os.Clearenv() isn't called by server above these will be seen in the\n\t//client's session env.\n\t//c.Env = []string{\"HOME=\" + u.HomeDir, \"SUDO_GID=\", \"SUDO_UID=\", \"SUDO_USER=\", \"SUDO_COMMAND=\", \"MAIL=\", \"LOGNAME=\"+who}\n\tc.Dir = u.HomeDir\n\tc.SysProcAttr = &syscall.SysProcAttr{}\n\tif useSysLogin {\n\t\t// If using server's login binary, drop to user creds\n\t\t// is taken care of by it.\n\t\tc.SysProcAttr.Credential = &syscall.Credential{}\n\t} else {\n\t\tc.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}\n\t}\n\n\t// Start the command with a pty.\n\tptmx, err := pty.Start(c) // returns immediately with ptmx file\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn xsnet.CSEPtyExecFail, err\n\t}\n\t// Make sure to close the pty at the end.\n\t// #gv:s/label=\\\"runShellAs\\$1\\\"/label=\\\"deferPtmxClose\\\"/\n\tdefer func() {\n\t\t//logger.LogDebug(fmt.Sprintf(\"[Exited process was %d]\", c.Process.Pid))\n\t\t_ = ptmx.Close()\n\t}() // nolint: gosec\n\n\t// get pty info for system accounting (who, lastlog)\n\tpts, pe := ptsName(ptmx.Fd())\n\tif pe != nil {\n\t\treturn xsnet.CSEPtyGetNameFail, err\n\t}\n\tutmpx := goutmp.Put_utmp(who, pts, hname)\n\tdefer func() { goutmp.Unput_utmp(utmpx) }()\n\tgoutmp.Put_lastlog_entry(\"xs\", who, pts, hname)\n\n\tlog.Printf(\"[%s]\\n\", cmd)\n\tif err != nil {\n\t\tlog.Printf(\"Command finished with error: %v\", err)\n\t} else {\n\t\t// Watch for term resizes\n\t\t// #gv:s/label=\\\"runShellAs\\$2\\\"/label=\\\"termResizeWatcher\\\"/\n\t\tgo func() {\n\t\t\tfor sz := range conn.WinCh {\n\t\t\t\tlog.Printf(\"[Setting term size to: %v %v]\\n\", sz.Rows, sz.Cols)\n\t\t\t\tpty.Setsize(ptmx, &pty.Winsize{Rows: sz.Rows, Cols: sz.Cols}) // nolint: gosec,errcheck\n\t\t\t}\n\t\t\tlog.Println(\"*** WinCh goroutine done ***\")\n\t\t}()\n\n\t\t// Copy stdin to the pty.. (bgnd goroutine)\n\t\t// #gv:s/label=\\\"runShellAs\\$3\\\"/label=\\\"stdinToPtyWorker\\\"/\n\t\tgo func() {\n\t\t\t_, e := io.Copy(ptmx, conn)\n\t\t\tif e != nil {\n\t\t\t\tlog.Println(\"** stdin->pty ended **:\", e.Error())\n\t\t\t} else {\n\t\t\t\tlog.Println(\"*** stdin->pty goroutine done ***\")\n\t\t\t}\n\t\t}()\n\n\t\tif chaffing {\n\t\t\tconn.EnableChaff()\n\t\t}\n\t\t// #gv:s/label=\\\"runShellAs\\$4\\\"/label=\\\"deferChaffShutdown\\\"/\n\t\tdefer func() {\n\t\t\tconn.DisableChaff()\n\t\t\tconn.ShutdownChaff()\n\t\t}()\n\n\t\t// ..and the pty to stdout.\n\t\t// This may take some time exceeding that of the\n\t\t// actual command's lifetime, so the c.Wait() below\n\t\t// must synchronize with the completion of this goroutine\n\t\t// to ensure all stdout data gets to the client before\n\t\t// connection is closed.\n\t\twg.Add(1)\n\t\t// #gv:s/label=\\\"runShellAs\\$5\\\"/label=\\\"ptyToStdoutWorker\\\"/\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\t_, e := io.Copy(conn, ptmx)\n\t\t\tif e != nil {\n\t\t\t\tlog.Println(\"** pty->stdout ended **:\", e.Error())\n\t\t\t} else {\n\t\t\t\t// The above io.Copy() will exit when the command attached\n\t\t\t\t// to the pty exits\n\t\t\t\tlog.Println(\"*** pty->stdout goroutine done ***\")\n\t\t\t}\n\t\t}()\n\n\t\tif err := c.Wait(); err != nil {\n\t\t\t//fmt.Println(\"*** c.Wait() done ***\")\n\t\t\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\t\t\t// The program has exited with an exit code != 0\n\n\t\t\t\t// This works on both Unix and Windows. Although package\n\t\t\t\t// syscall is generally platform dependent, WaitStatus is\n\t\t\t\t// defined for both Unix and Windows and in both cases has\n\t\t\t\t// an ExitStatus() method with the same signature.\n\t\t\t\tif status, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\t\texitStatus = uint32(status.ExitStatus())\n\t\t\t\t\tlog.Printf(\"Exit Status: %d\", exitStatus)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconn.SetStatus(xsnet.CSOType(exitStatus))\n\t\t} else {\n\t\t\tlogger.LogDebug(\"*** Main proc has exited. ***\")\n\t\t\t// Background jobs still may be running; close the\n\t\t\t// pty anyway, so the client can return before\n\t\t\t// wg.Wait() below completes (Issue #18)\n\t\t\tif interactive {\n\t\t\t\t_ = ptmx.Close()\n\t\t\t}\n\t\t}\n\t\twg.Wait() // Wait on pty->stdout completion to client\n\t}\n\treturn\n}", "func RunBashCmdExec(args []string, workingDir string) (string, error) {\n\texecDir, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer func() {\n\t\t// replace the original working directory when this funciton completes\n\t\terr := os.Chdir(execDir)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n\t// set the working directory\n\tif err := os.Chdir(workingDir); err != nil {\n\t\treturn \"\", err\n\t}\n\tlog.Println(\"executing: \" + args[0])\n\tcommandString := args[0]\n\texecCmd := exec.Command(\"/bin/sh\", \"-c\", commandString)\n\n\toutReader, outWriter, err := os.Pipe()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer func() {\n\t\toutReader.Close()\n\t\toutWriter.Close()\n\t}()\n\texecCmd.Stdout = outWriter\n\texecCmd.Stderr = outWriter\n\toutScanner := bufio.NewScanner(outReader)\n\tvar outBuffer bytes.Buffer\n\tgo func() {\n\t\tfor outScanner.Scan() {\n\t\t\tout := outScanner.Bytes()\n\t\t\toutBuffer.Write(out)\n\t\t\toutBuffer.WriteByte('\\n')\n\t\t\tfmt.Println(string(out))\n\t\t}\n\t}()\n\n\terr = execCmd.Start()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = execCmd.Wait()\n\treturn outBuffer.String(), err\n}", "func (c *VirtLauncherClient) Exec(domainName, command string, args []string, timeoutSeconds int32) (int, string, error) {\n\trequest := &cmdv1.ExecRequest{\n\t\tDomainName: domainName,\n\t\tCommand: command,\n\t\tArgs: args,\n\t\tTimeoutSeconds: int32(timeoutSeconds),\n\t}\n\texitCode := -1\n\tstdOut := \"\"\n\n\tctx, cancel := context.WithTimeout(\n\t\tcontext.Background(),\n\t\t// we give the context a bit more time as the timeout should kick\n\t\t// on the actual execution\n\t\ttime.Duration(timeoutSeconds)*time.Second+shortTimeout,\n\t)\n\tdefer cancel()\n\n\tresp, err := c.v1client.Exec(ctx, request)\n\tif resp == nil {\n\t\treturn exitCode, stdOut, err\n\t}\n\n\texitCode = int(resp.ExitCode)\n\tstdOut = resp.StdOut\n\n\treturn exitCode, stdOut, err\n}", "func ExecShells(sshcfg *ssh.ClientConfig, commands []HostCmd, stdout io.Writer, stderr io.Writer) error {\n\tvar wg sync.WaitGroup\n\toutBuff := make(chan string, 100)\n\terrBuff := make(chan string, 100)\n\t// fork the commands\n\tfor _, cmd := range commands {\n\t\twg.Add(1)\n\t\tgo func(cmd HostCmd) {\n\t\t\t// decrement waitgroup when done\n\t\t\tdefer wg.Done()\n\t\t\t// connect ssh\n\t\t\tcli, err := ssh.Dial(\"tcp4\", fmt.Sprintf(\"%s:%d\", cmd.Host, 22), sshcfg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error connecting to host %s : %s\", cmd.Host, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsesh, err := cli.NewSession()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error obtaining session on host %s : %s\", cmd.Host, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// pipe outputs\n\t\t\tgo func() {\n\t\t\t\tseshOut, err := sesh.StdoutPipe()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error obtaining session stdout on host %s : %s\", cmd.Host, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treadLinesToChan(seshOut, \"\", outBuff)\n\t\t\t}()\n\t\t\tgo func() {\n\t\t\t\tseshOut, err := sesh.StderrPipe()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error obtaining session stderr on host %s : %s\", cmd.Host, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treadLinesToChan(seshOut, fmt.Sprintf(\"%s: \", cmd.Host), errBuff)\n\t\t\t}()\n\t\t\t// issue command with proper env\n\t\t\ttoExec := fmt.Sprintf(\"if [ -f ~/.bashrc ]; then source ~/.bashrc ; fi; %s; exit;\", cmd.Cmd)\n\t\t\terr = sesh.Run(toExec)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error running command %s on host %s\", toExec, cmd.Host)\n\t\t\t}\n\t\t\tsesh.Close()\n\t\t}(cmd)\n\t}\n\toutDone := make(chan bool)\n\terrDone := make(chan bool)\n\tgo func() {\n\t\tout := bufio.NewWriter(stdout)\n\t\tfor line := range outBuff {\n\t\t\tout.WriteString(line)\n\t\t\tout.WriteByte('\\n')\n\t\t}\n\t\tout.Flush()\n\t\toutDone <- true\n\t\tclose(outDone)\n\t}()\n\tgo func() {\n\t\terr := bufio.NewWriter(stderr)\n\t\tfor line := range errBuff {\n\t\t\terr.WriteString(line)\n\t\t\terr.WriteByte('\\n')\n\t\t}\n\t\terr.Flush()\n\t\terrDone <- true\n\t\tclose(errDone)\n\t}()\n\twg.Wait()\n\tclose(outBuff)\n\tclose(errBuff)\n\t<-outDone\n\t<-errDone\n\treturn nil\n}", "func Execute() {\n\tif err := ShellCmd.Execute(); err != nil {\n\t\tlog.Info().Err(err)\n\t\tos.Exit(1)\n\t}\n}", "func Exec(command string, args ...string) (string, error) {\n\tLogger.DebugC(color.Yellow, \"$ %v %v\", command, strings.Join(args, \" \"))\n\tb, err := exec.Command(command, args...).CombinedOutput()\n\tLogger.Debug(\"%s\\n\", b)\n\treturn string(b), err\n}", "func CommandExec() *cobra.Command {\n\n\tvar expandCmd = &cobra.Command{\n\t\tUse: \"exec [flags] <command> <shortcuts...>\",\n\t\tExample: \"$ scmpuff exec git add 1-4\",\n\t\tAliases: []string{\"execute\"},\n\t\tShort: \"Execute cmd with numeric shortcuts\",\n\t\tLong: `Expands numeric shortcuts to their full filepath and executes the command.\n\nTakes a list of digits (1 4 5) or numeric ranges (1-5) or even both.`,\n\t\tRun: func(cmd *cobra.Command, inputArgs []string) {\n\t\t\tif len(inputArgs) < 1 {\n\t\t\t\tcmd.Usage()\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\texpandedArgs := Process(inputArgs)\n\t\t\ta := expandedArgs[1:]\n\t\t\tsubcmd := exec.Command(expandedArgs[0], a...)\n\t\t\tsubcmd.Stdin = os.Stdin\n\t\t\tsubcmd.Stdout = os.Stdout\n\t\t\tsubcmd.Stderr = os.Stderr\n\t\t\terr := subcmd.Run()\n\t\t\tif err == nil {\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\t\tos.Exit(exitError.ExitCode())\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\n\t// --relative\n\texpandCmd.Flags().BoolVarP(\n\t\t&expandRelative,\n\t\t\"relative\",\n\t\t\"r\",\n\t\tfalse,\n\t\t\"make path relative to current working directory\",\n\t)\n\n\treturn expandCmd\n}", "func StreamedExec(pipe ProcessStream, name string, args ...string) (string, string) {\n\tcmd := ExecCommand(name, args...)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tcmd.Stdout = io.MultiWriter(pipe, &stdoutBuf)\n\tcmd.Stderr = io.MultiWriter(&stderrBuf)\n\tcmd.Run()\n\toutStr, errStr := string(stdoutBuf.Bytes()), string(stderrBuf.Bytes())\n\n\treturn outStr, errStr\n}", "func (e ExternalCmd) Call(ec *EvalCtx, argVals []Value) {\n\tif DontSearch(e.Name) {\n\t\tstat, err := os.Stat(e.Name)\n\t\tif err == nil && stat.IsDir() {\n\t\t\t// implicit cd\n\t\t\tcdInner(e.Name, ec)\n\t\t\treturn\n\t\t}\n\t}\n\n\tfiles := make([]uintptr, len(ec.ports))\n\tfor i, port := range ec.ports {\n\t\tif port == nil || port.File == nil {\n\t\t\tfiles[i] = fdNil\n\t\t} else {\n\t\t\tfiles[i] = port.File.Fd()\n\t\t}\n\t}\n\n\targs := make([]string, len(argVals)+1)\n\tfor i, a := range argVals {\n\t\t// NOTE Maybe we should enfore string arguments instead of coercing all\n\t\t// args into string\n\t\targs[i+1] = ToString(a)\n\t}\n\n\tsys := syscall.SysProcAttr{}\n\tattr := syscall.ProcAttr{Env: os.Environ(), Files: files[:], Sys: &sys}\n\n\tpath, err := ec.Search(e.Name)\n\tif err != nil {\n\t\tthrow(errors.New(\"search: \" + err.Error()))\n\t}\n\n\targs[0] = path\n\tpid, err := syscall.ForkExec(path, args, &attr)\n\tif err != nil {\n\t\tthrow(errors.New(\"forkExec: \" + err.Error()))\n\t}\n\n\tvar ws syscall.WaitStatus\n\t_, err = syscall.Wait4(pid, &ws, 0, nil)\n\tif err != nil {\n\t\tthrow(fmt.Errorf(\"wait: %s\", err.Error()))\n\t} else {\n\t\tmaybeThrow(waitStatusToError(ws))\n\t}\n}", "func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (libcontainerdtypes.Process, error) {\n\thcsContainer, err := t.getHCSContainer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger := t.ctr.client.logger.WithFields(log.Fields{\n\t\t\"container\": t.ctr.id,\n\t\t\"exec\": processID,\n\t})\n\n\t// Note we always tell HCS to\n\t// create stdout as it's required regardless of '-i' or '-t' options, so that\n\t// docker can always grab the output through logs. We also tell HCS to always\n\t// create stdin, even if it's not used - it will be closed shortly. Stderr\n\t// is only created if it we're not -t.\n\tcreateProcessParms := &hcsshim.ProcessConfig{\n\t\tCreateStdInPipe: true,\n\t\tCreateStdOutPipe: true,\n\t\tCreateStdErrPipe: !spec.Terminal,\n\t}\n\tif spec.Terminal {\n\t\tcreateProcessParms.EmulateConsole = true\n\t\tif spec.ConsoleSize != nil {\n\t\t\tcreateProcessParms.ConsoleSize[0] = uint(spec.ConsoleSize.Height)\n\t\t\tcreateProcessParms.ConsoleSize[1] = uint(spec.ConsoleSize.Width)\n\t\t}\n\t}\n\n\t// Take working directory from the process to add if it is defined,\n\t// otherwise take from the first process.\n\tif spec.Cwd != \"\" {\n\t\tcreateProcessParms.WorkingDirectory = spec.Cwd\n\t} else {\n\t\tcreateProcessParms.WorkingDirectory = t.ctr.ociSpec.Process.Cwd\n\t}\n\n\t// Configure the environment for the process\n\tcreateProcessParms.Environment = setupEnvironmentVariables(spec.Env)\n\n\t// Configure the CommandLine/CommandArgs\n\tsetCommandLineAndArgs(spec, createProcessParms)\n\tlogger.Debugf(\"exec commandLine: %s\", createProcessParms.CommandLine)\n\n\tcreateProcessParms.User = spec.User.Username\n\n\t// Start the command running in the container.\n\tnewProcess, err := hcsContainer.CreateProcess(createProcessParms)\n\tif err != nil {\n\t\tlogger.WithError(err).Errorf(\"exec's CreateProcess() failed\")\n\t\treturn nil, err\n\t}\n\tpid := newProcess.Pid()\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err := newProcess.Kill(); err != nil {\n\t\t\t\tlogger.WithError(err).Error(\"failed to kill process\")\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tif err := newProcess.Wait(); err != nil {\n\t\t\t\t\tlogger.WithError(err).Error(\"failed to wait for process\")\n\t\t\t\t}\n\t\t\t\tif err := newProcess.Close(); err != nil {\n\t\t\t\t\tlogger.WithError(err).Error(\"failed to clean process resources\")\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}()\n\n\tdio, err := newIOFromProcess(newProcess, spec.Terminal)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"failed to get stdio pipes\")\n\t\treturn nil, err\n\t}\n\t// Tell the engine to attach streams back to the client\n\t_, err = attachStdio(dio)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &process{\n\t\tid: processID,\n\t\tctr: t.ctr,\n\t\thcsProcess: newProcess,\n\t\twaitCh: make(chan struct{}),\n\t}\n\n\t// Spin up a goroutine to notify the backend and clean up resources when\n\t// the process exits. Defer until after the start event is sent so that\n\t// the exit event is not sent out-of-order.\n\tdefer func() { go p.reap() }()\n\n\tt.ctr.client.eventQ.Append(t.ctr.id, func() {\n\t\tei := libcontainerdtypes.EventInfo{\n\t\t\tContainerID: t.ctr.id,\n\t\t\tProcessID: p.id,\n\t\t\tPid: uint32(pid),\n\t\t}\n\t\tt.ctr.client.logger.WithFields(log.Fields{\n\t\t\t\"container\": t.ctr.id,\n\t\t\t\"event\": libcontainerdtypes.EventExecAdded,\n\t\t\t\"event-info\": ei,\n\t\t}).Info(\"sending event\")\n\t\terr := t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecAdded, ei)\n\t\tif err != nil {\n\t\t\tt.ctr.client.logger.WithError(err).WithFields(log.Fields{\n\t\t\t\t\"container\": t.ctr.id,\n\t\t\t\t\"event\": libcontainerdtypes.EventExecAdded,\n\t\t\t\t\"event-info\": ei,\n\t\t\t}).Error(\"failed to process event\")\n\t\t}\n\t\terr = t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecStarted, ei)\n\t\tif err != nil {\n\t\t\tt.ctr.client.logger.WithError(err).WithFields(log.Fields{\n\t\t\t\t\"container\": t.ctr.id,\n\t\t\t\t\"event\": libcontainerdtypes.EventExecStarted,\n\t\t\t\t\"event-info\": ei,\n\t\t\t}).Error(\"failed to process event\")\n\t\t}\n\t})\n\n\treturn p, nil\n}", "func cmdLine() string {\n\treturn \"go run mksyscall_aix_ppc64.go \" + strings.Join(os.Args[1:], \" \")\n}", "func (cl *Client) ExecString(cmd string, args ...interface{}) (string, error) {\n\tvar s string\n\terr := cl.Conn(func(c *Conn) error {\n\t\tvar err error\n\t\ts, err = c.ExecString(cmd, args...)\n\t\treturn err\n\t})\n\treturn s, err\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func (p *Program) exec(c ExecCommand, fn ExecCallback) {\n\tif err := p.ReleaseTerminal(); err != nil {\n\t\t// If we can't release input, abort.\n\t\tif fn != nil {\n\t\t\tgo p.Send(fn(err))\n\t\t}\n\t\treturn\n\t}\n\n\tc.SetStdin(p.input)\n\tc.SetStdout(p.output)\n\tc.SetStderr(os.Stderr)\n\n\t// Execute system command.\n\tif err := c.Run(); err != nil {\n\t\t_ = p.RestoreTerminal() // also try to restore the terminal.\n\t\tif fn != nil {\n\t\t\tgo p.Send(fn(err))\n\t\t}\n\t\treturn\n\t}\n\n\t// Have the program re-capture input.\n\terr := p.RestoreTerminal()\n\tif fn != nil {\n\t\tgo p.Send(fn(err))\n\t}\n}", "func RunCmd(cmdstr string) string {\n\treturn RunAs(cmdstr, \"\")\n}", "func (a Adapter) execTestCmd(testCmd versionsCommon.DevfileCommand, containers []types.Container, show bool) (err error) {\n\tcontainerID := utils.GetContainerIDForAlias(containers, testCmd.Exec.Component)\n\tcompInfo := common.ComponentInfo{ContainerName: containerID}\n\terr = exec.ExecuteDevfileCommandSynchronously(&a.Client, *testCmd.Exec, testCmd.Exec.Id, compInfo, show, a.machineEventLogger, false)\n\treturn\n}", "func executeCmd(path string, args []string, env []string, dir string) ([]byte, error) {\n\t// Create context with timeout\n\tctx, cancel := context.WithTimeout(context.Background(), maxTimeoutMinutes*time.Minute)\n\tdefer cancel()\n\n\t// Create command\n\tcmd := execCommandContext(ctx, path, args...)\n\tcmd.Env = env\n\tcmd.Dir = dir\n\n\t// Execute command\n\treturn cmd.CombinedOutput()\n}", "func ExecuteCmd(cmd string) (string, error) {\n\tvar stdout, stderr bytes.Buffer\n\texe := exec.Command(\"sh\", \"-c\", cmd)\n\texe.Stderr = &stderr\n\texe.Stdout = &stdout\n\terr := exe.Run()\n\terrorResult := string(stderr.Bytes())\n\tif len(errorResult) != 0 && !strings.Contains(errorResult, \"deprecated\") {\n\t\treturn \"\", errors.New(errorResult)\n\t}\n\tif err != nil && !strings.Contains(errorResult, \"deprecated\") {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"failed in executing the azure command: %s\", cmd))\n\t}\n\toutput := string(stdout.Bytes())\n\tif len(output) != 0 {\n\t\treturn output, nil\n\t}\n\treturn \"\", nil\n}", "func runExec(serviceName string, operation string) (string, error) {\n\tbytes, err := exec.Command(Configuration.ExecutorPath, serviceName, operation).CombinedOutput()\n\treturn string(bytes), err\n}", "func execCommand(name string, arg ...string) error {\n\tcmd := exec.Command(name, arg...)\n\t// For locating the GCC runtime library (libgcc_s.so.1):\n\tcmd.Env = append(os.Environ(), \"LD_LIBRARY_PATH=/ro/lib:/ro/lib64\")\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"%v: %v\", cmd.Args, err)\n\t}\n\treturn nil\n}", "func Exec(t testing.TB, cmd *cobra.Command, stdIn io.Reader, args ...string) (string, string, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tt.Cleanup(cancel)\n\n\treturn ExecCtx(ctx, cmd, stdIn, args...)\n}", "func Exec(rootCmd *RootCommand) (err error) {\n\terr = InternalExecFor(rootCmd, os.Args)\n\treturn\n}", "func (client *MockPodExecClient) RunPodExecCommand(ctx context.Context, streamOptions *remotecommand.StreamOptions, baseCmd []string) (string, string, error) {\n\n\tvar mockPodExecReturnContext *MockPodExecReturnContext = &MockPodExecReturnContext{}\n\tvar command string\n\t// This is to prevent the crash in the case where streamOptions.Stdin is anything other than *strings.Reader\n\t// In most of the cases the base command will be /bin/sh but if it is something else, it can be reading from\n\t// a io.Reader pipe. For e.g. tarring a file, writing to a write pipe and then untarring it on the pod by reading\n\t// from the reader pipe.\n\tif baseCmd[0] == \"/bin/sh\" {\n\t\tvar cmdStr string\n\t\tstreamOptionsCmd := streamOptions.Stdin.(*strings.Reader)\n\t\tfor i := 0; i < int(streamOptionsCmd.Size()); i++ {\n\t\t\tcmd, _, _ := streamOptionsCmd.ReadRune()\n\t\t\tcmdStr = cmdStr + string(cmd)\n\t\t}\n\n\t\tmockPodExecReturnContext, command = client.GetMockPodExecReturnContextAndKey(ctx, cmdStr)\n\t\tif mockPodExecReturnContext == nil {\n\t\t\terr := fmt.Errorf(\"mockPodExecReturnContext is nil\")\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t}\n\n\t// check if the command is already added or not in the list of GotCmdList\n\tvar found bool\n\tfor i := range client.GotCmdList {\n\t\tif command == client.GotCmdList[i] {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tclient.GotCmdList = append(client.GotCmdList, command)\n\t}\n\n\treturn mockPodExecReturnContext.StdOut, mockPodExecReturnContext.StdErr, mockPodExecReturnContext.Err\n}", "func startShell(db *database.Database) error {\n\te := exec.NewExecutor()\n\n\tshell := shell.NewShell()\n\tfor {\n\t\tline, err := shell.ReadLine()\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tprogram, err := parser.Parse(line)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"parsing error: %s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\te.Execute(program, db)\n\t}\n}", "func ExecCommand(args ...string) ([]byte, error) {\n\te := New()\n\tcmd := e.ExecCommand(NoSandbox, false, args[0], args[1:]...)\n\treturn cmd.CombinedOutput()\n}", "func (ft *LsTask) Exec(ctx *Context, p *par.Params, out *io.PipeWriter) {\n\tlog.Info(\"LsTask.Execute\")\n\n\tpath, ok := p.Props[\"path\"]\n\n\t// if no passed in path use default\n\tif !ok {\n\t\tpath = ft.path\n\t}\n\n\tif path == \"\" {\n\t\tp.Status = par.StFail\n\t\tp.Response = \"no path specified\"\n\t\treturn\n\t}\n\n\t// this is mandatory node\n\tpath = filepath.Join(ctx.WorkspacePath, path)\n\n\tfiles, _ := ioutil.ReadDir(path)\n\tfor _, f := range files {\n\t\tp.Props[fmt.Sprint(f.Name())] = \"\"\n\t}\n\n\tp.Response = \"list directory done\"\n\tp.Status = par.StSuccess\n\n\treturn\n}", "func (r *RemoteShell) Execute(ctx context.Context, cmd string) ([]byte, error) {\n\tsshCmd, err := r.conn.CommandContext(ctx, cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sshCmd.CombinedOutput()\n}", "func execCommand(log bool, name string, args ...string) (bytes.Buffer, bytes.Buffer, error) {\n\tvar (\n\t\tstdout bytes.Buffer\n\t\tstderr bytes.Buffer\n\t)\n\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr := cmd.Run()\n\tif log {\n\t\tLogf(\"run command '%s %v':\\n out=%s\\n err=%s\\n ret=%v\",\n\t\t\tname, args, strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err)\n\t}\n\n\treturn stdout, stderr, err\n}", "func executeCmd(cmd string, args ...string) error {\n\tcommand := exec.Command(cmd, args...) // #nosec\n\tbytes, err := command.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", err, bytes)\n\t}\n\treturn nil\n}", "func (si *shellInterface) RunCmd(context context.Context, operation string, script, env []string) (string, error) {\n\tfileName, _, err := si.runCmd(context, operation, script, env, false)\n\treturn fileName, err\n}", "func RunExecV(c string) string {\n x := exec.Command(\"bash\", \"-c\", c)\n out, err := x.CombinedOutput()\n if err != nil {\n log.Fatalf(\"Error: %s\\n\", err)\n }\n r := fmt.Sprintf(\"%s\", out)\n z := strings.Replace(r, \"\\n\", \"\", -1)\n return z\n}", "func wrapExecCommand(c *exec.Cmd) ExecCommand {\n\treturn &osExecCommand{Cmd: c}\n}", "func TestExecuteFile(t *testing.T) {\n\ttestfile := tests.Testdir + \"/ex1.sh\"\n\n\tvar out bytes.Buffer\n\tshell, cleanup := newTestShell(t)\n\tdefer cleanup()\n\n\tshell.SetNashdPath(tests.Nashcmd)\n\tshell.SetStdout(&out)\n\tshell.SetStderr(os.Stderr)\n\tshell.SetStdin(os.Stdin)\n\n\terr := shell.ExecuteFile(testfile)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tif string(out.Bytes()) != \"hello world\\n\" {\n\t\tt.Errorf(\"Wrong command output: '%s'\", string(out.Bytes()))\n\t\treturn\n\t}\n}" ]
[ "0.6343495", "0.61270344", "0.5937417", "0.5901834", "0.5735678", "0.5730066", "0.5700993", "0.567958", "0.562397", "0.56186557", "0.56005836", "0.5578034", "0.55685246", "0.55685246", "0.551668", "0.547903", "0.54406506", "0.543145", "0.54090106", "0.5396964", "0.53954333", "0.5393781", "0.536616", "0.53383523", "0.5328432", "0.53050506", "0.52905226", "0.52692825", "0.5264499", "0.52629906", "0.52462757", "0.5243395", "0.52373135", "0.52143687", "0.521003", "0.5187251", "0.5167108", "0.51610184", "0.515674", "0.5156591", "0.5149274", "0.51448876", "0.51443243", "0.512694", "0.51091427", "0.5095179", "0.5086441", "0.5082356", "0.5080105", "0.5077601", "0.5072062", "0.5061703", "0.5061572", "0.5059358", "0.5052012", "0.504573", "0.5043456", "0.50408673", "0.50301945", "0.5024451", "0.5013832", "0.50107396", "0.50081307", "0.50067604", "0.49829656", "0.4968925", "0.49608836", "0.49528262", "0.49483854", "0.49381652", "0.49289042", "0.49226406", "0.49184036", "0.4916918", "0.4914149", "0.49129495", "0.49110243", "0.4908439", "0.49067333", "0.49024412", "0.48989472", "0.489862", "0.48978055", "0.48977435", "0.4896054", "0.4885503", "0.48851648", "0.48718387", "0.4868867", "0.48688632", "0.48668665", "0.48663622", "0.48659384", "0.4864364", "0.4860309", "0.48555073", "0.48551026", "0.48507524", "0.4846796", "0.48439765" ]
0.75436246
0
NewRabbitMQServer returns the new rabbitmq server with the connection and channel
NewRabbitMQServer возвращает новый сервер rabbitmq с соединением и каналом
func NewRabbitMQServer(username string, password string, host string) *Server { return &Server{ RabbitMQUsername: username, RabbitMQPassword: password, RabbitMQHost: host, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewServer(cfg *ServerConfig) (*Server, error) {\n\tvar s = &Server{\n\t\tmux: http.NewServeMux(),\n\t}\n\n\t// register api handlers\n\ts.registerHandlers()\n\tconsole.Info(\"registered handlers\")\n\n\t// http client for authorization\n\ts.hc = &http.Client{}\n\n\t// establish rabbitmq session\n\tmqaddr := fmt.Sprintf(\"%s:%d\", cfg.RabbitMQ.IP, cfg.RabbitMQ.Port)\n\tbaseConfig.User = cfg.RabbitMQ.User\n\tbaseConfig.Password = cfg.RabbitMQ.Password\n\tbaseConfig.Addr = mqaddr\n\tmqSession := mq.NewSession(\"api\", baseConfig)\n\n\t// connecte the session\n\tconsole.Info(\"connect to RabbitMQ...\")\n\tif err := mqSession.TryConnect(40, 3000*time.Millisecond); err != nil {\n\t\treturn nil, fmt.Errorf(\"on NewServer: %v\", err)\n\t}\n\ts.mqss = mqSession\n\tconsole.Info(\"session(%q) established between RabbitMQ\", mqaddr)\n\n\t// create response packet map\n\ts.packetChans = server.NewChannelMap()\n\n\t// start to listen from RabbitMQ\n\terr := s.mqss.Consume(server.MGDB, server.DB2API, s.onDBResponse, 2)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"on NewServer: %v\", err)\n\t}\n\n\t// addlitionaly send logs to RabbitMQ.\n\tconsole.AddLogHandler(\n\t\tfunc(l console.Level, format string, v ...interface{}) bool {\n\t\t\tpacket := server.PacketLog{\n\t\t\t\tTimestamp: time.Now(),\n\t\t\t\tLogLevel: l,\n\t\t\t\tMsg: fmt.Sprintf(format, v...),\n\t\t\t}\n\n\t\t\tif err := s.mqss.Publish(\n\t\t\t\tserver.MGLogs,\n\t\t\t\t\"\",\n\t\t\t\tserver.API,\n\t\t\t\t&packet,\n\t\t\t); err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t},\n\t)\n\n\treturn s, nil\n}", "func initialize() *RabbitServer {\n\n\trabbitURL := utilities.GetRabbitInfo()\n\tserver := MakeRabbitServer(rabbitURL)\n\tserver.Connect()\n\n\treturn server\n\n}", "func New(uri string) *RabbitMQ {\n\n\tctx, cancel := context.WithCancel(context.Background())\n\trmq := &RabbitMQ{URI: uri, ConnectionContext: ctx, connectionCancelFunc: cancel, reconnected: false}\n\n\trmq.connect(uri)\n\n\t//launch a goroutine that will listen for messages on ErrorChan and try to reconnect in case of errors\n\tgo rmq.reconnector()\n\n\treturn rmq\n}", "func NewServer(\n\tconnection *Connection,\n\tqueue string,\n\tconcurrency uint32,\n\ttimeout time.Duration,\n\trequestParser RequestParser,\n\treplyParser ReplyParser,\n) (Server, error) {\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsenderCache, err := NewSenderCache(connection)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &rpcServer{\n\t\tconnection: connection,\n\t\tsession: session,\n\t\tqueue: queue,\n\t\tconcurrency: concurrency,\n\t\ttimeout: timeout,\n\t\trequestParser: requestParser,\n\t\treplyParser: replyParser,\n\t\tsenderCache: senderCache,\n\t\tdone: make(chan bool),\n\t}, nil\n}", "func New(config *config.Config) (MsgBroker, error) {\n\n\t//create connection\n\tlog.Printf(\"Connecting to broker %s\", config.Broker)\n\tconn, err := amqp.Dial(config.Broker)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch, err := conn.Channel()\n\t//create channel\n\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := &amqpBroker{*conn, *ch, make(chan *amqp.Error), config}\n\tlog.Println(\"Returning broker\")\n\treturn b, nil\n}", "func createRabbitConnection(cr *Credentials) (*Rabbit, error) {\n\tconnectionStr := fmt.Sprintf(\"amqp://%v:%v@%v:%v/\", cr.Username, cr.Password, cr.Host, cr.Port)\n\tconn, err := amqp.Dial(connectionStr)\n\tfailOnError(err, \"Failed to connect to RabbitMQ; Connection string:\"+connectionStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to open a channel\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Rabbit{\n\t\tConnection: conn,\n\t\tChannel: ch,\n\t\tCredentials: cr,\n\t}, nil\n}", "func buildChannel() (rChan *RabbitChanWriter) {\n connection, err := amqp.Dial(*uri)\n if err != nil {\n log.Printf(\"Dial: %s\", err)\n return nil\n }\n\n channel, err := connection.Channel()\n if err != nil {\n log.Printf(\"Channel: %s\", err)\n return nil\n }\n\n // build the exchange\n if err := channel.ExchangeDeclare(\n *exchange, // name\n *exchangeType, // type\n true, // durable\n false, // auto-deleted\n false, // internal\n false, // noWait\n nil, // arguments\n ); err != nil {\n log.Fatalf(\"Exchange Declare: %s\", err)\n }\n\n // create a queue with the routing key and bind to it\n if _, err := channel.QueueDeclare(\n *routingKey, // name\n true, // durable\n false, // autoDelete\n false, // exclusive\n false, // noWait\n nil, // args\n ); err != nil {\n log.Fatalf(\"Queue Declare: %s\", err)\n }\n\n if err := channel.QueueBind(\n *routingKey, // name\n *routingKey, // key\n *exchange, // exchange\n false, // noWait\n nil, // args\n ); err != nil {\n log.Fatalf(\"Queue Bind: %s\", err)\n }\n\n\n rChan = &RabbitChanWriter{channel, connection}\n return\n}", "func NewServer() *Server {}", "func channel(conn *amqp.Connection, msgtype string) (*amqp.Channel, error) {\n\t// Open a channel to communicate with the server\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Declare the exchange to use when publishing\n\tif err := channel.ExchangeDeclare(\n\t\tmsgtype,\n\t\t\"direct\",\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tnil,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Declare the queue to use when publishing\n\tchannel.QueueDeclare(\n\t\tmsgtype,\n\t\tfalse,\n\t\ttrue,\n\t\tfalse,\n\t\tfalse,\n\t\tnil,\n\t)\n\n\t// Bind the queue to the exchange\n\tchannel.QueueBind(\n\t\tmsgtype,\n\t\t\"\",\n\t\tmsgtype,\n\t\tfalse,\n\t\tnil,\n\t)\n\n\treturn channel, nil\n}", "func NewConsumer(amqpURI, exchange, queue, routingKey, tag string, prefetch int) *RabbitMQ {\n\tconn, err := amqp.Dial(amqpURI)\n\tif err != nil {\n\t\tlog.Fatalf(\"writer failed to connect to Rabbit: %s\", err)\n\t\treturn nil\n\t}\n\n\tgo func() {\n\t\tlog.Printf(\"writer closing: %s\", <-conn.NotifyClose(make(chan *amqp.Error)))\n\t\tlog.Printf(\"writer blocked by rabbit: %v\", <-conn.NotifyBlocked(make(chan amqp.Blocking)))\n\t}()\n\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\tlog.Fatalf(\"writer failed to get a channel from Rabbit: %s\", err)\n\t\treturn nil\n\t}\n\n\tq, err := channel.QueueDeclarePassive(\n\t\tqueue, // name of the queue\n\t\ttrue, // durable\n\t\tfalse, // delete when usused\n\t\tfalse, // exclusive\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Queue Declare: %s\", err)\n\t}\n\tif q.Messages == 0 {\n\t\tlog.Fatalf(\"No messages in RabbitMQ Queue: %s\", q.Name)\n\t}\n\n\tr := &RabbitMQ{\n\t\tconn: conn,\n\t\tchannel: channel,\n\t\texchange: exchange,\n\t\tcontentType: \"application/json\",\n\t\tcontentEncoding: \"UTF-8\",\n\t}\n\tlog.Print(\"RabbitMQ connected: \", amqpURI)\n\tlog.Printf(\"Bind to Exchange: %q and Queue: %q, Messaging waiting: %d\", exchange, queue, q.Messages)\n\n\treturn r\n}", "func (r Rabbit) NewCh() (*amqp.Channel, error) {\n\treturn r.conn.Channel()\n}", "func NewMqttServer(sqz int, url string, retain bool, qos int) *Server {\n\treturn &Server{\n\t\tsessionQueueSize: sqz,\n\t\turl: url,\n\t\ttree: topic.NewTree(),\n\t\tretain: retain,\n\t\tqos: qos,\n\t}\n}", "func NewRabbitMQConnection(config *Configuration) (RabbitMQ, error) {\n\tconn, err := amqp.Dial(config.RabbitURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rabbitMQConnection{configuration: config, channel: ch}, nil\n}", "func NewRabbitConnection(URI string) (Connection, error) {\n\tamqpNativeConn, err := amqp.Dial(URI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RabbitConnection{amqpNativeConn}, nil\n}", "func NewRabbitMQ() *RabbitMQ {\n\treturn &RabbitMQ{}\n}", "func NewServer(buildBroker BrokerBuilder, options ...serverOption) (*Server, error) {\n\tif buildBroker == nil {\n\t\treturn nil, errors.New(\"chat.NewServer: required chat.BrokerBuilder is nil\")\n\t}\n\tinbox := make(chan broker.MessageEvent)\n\tjoin := make(chan broker.JoinEvent)\n\tpart := make(chan broker.PartEvent)\n\tb, err := buildBroker(inbox, join, part)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"chat.NewServer: can't build broker: %v\", err)\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Server{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\twg: &sync.WaitGroup{},\n\t\tbroker: b,\n\t\tinbox: inbox,\n\t\tjoin: join,\n\t\tpart: part,\n\t}\n\tif err := setup(s, options...); err != nil {\n\t\treturn nil, err\n\t}\n\ts.handleEvents()\n\treturn s, nil\n}", "func CreateConnection(host string, port int) *RabbitmqConnection {\n\trc := &RabbitmqConnection{Host: host, Port: port}\n\trc.connectToRabbitMQ()\n\treturn rc\n}", "func NewServer(ctx context.Context) (*Server, error) {\n\tcmds := make(chan *mc.Command)\n\n\tserver := &Server{\n\t\tcommands: cmds,\n\t\tticker: time.NewTicker(TickDuration),\n\t}\n\n\tctx = context.WithValue(ctx, mc.ServerCommands, cmds)\n\tserver.Runner = runner.NewRunner(ctx, server)\n\n\tif isatty.IsTerminal(os.Stdin.Fd()) {\n\t\twriter := &utils.LineWriter{\n\t\t\tWriter: log.StandardLogger().WriterLevel(log.InfoLevel),\n\t\t}\n\n\t\tif cons, err := console.NewConsole(server.Context, \"Console\", os.Stdin, writer); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tserver.console = cons\n\t\t}\n\t}\n\n\tif mcServer, err := NewMCServer(server.Context, mc.Properties().ServerAddr()); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tserver.mc = mcServer\n\t}\n\n\trconAddr := mc.Properties().RCONAddr()\n\trconPass := mc.Properties().RCON.Password\n\n\tif rconAddr != \"\" && rconPass != \"\" {\n\t\tif rcon, err := NewRCONServer(server.Context, rconAddr); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tserver.rcon = rcon\n\t\t}\n\t}\n\n\treturn server, nil\n}", "func NewServer(pattern string) *Server {\n\tmessages := GetMessages()\n\tclients := make(map[string]*Client)\n\tgroups := make(map[string]*Group)\n\taddCh := make(chan *Client)\n\tdelCh := make(chan *Client)\n\tsendAllCh := make(chan *Message)\n\tdoneCh := make(chan bool)\n\terrCh := make(chan error)\n\n\treturn &Server{\n\t\tpattern,\n\t\tmessages,\n\t\tclients,\n\t\tgroups,\n\t\taddCh,\n\t\tdelCh,\n\t\tsendAllCh,\n\t\tdoneCh,\n\t\terrCh,\n\t}\n}", "func NewServer(port string, newClients chan<- *Client, clientInput chan<- *ClientInputMessage) *Server {\n\tid := NewID(\"server\")\n\tlog := NewLogger(id)\n\treturn &Server{id, newClients, clientInput, port, nil, log}\n}", "func GetConnectionRabbit(rabbitURL string) (ConnectionRabbitMQ, error) {\n\tconn, err := amqp.Dial(rabbitURL)\n\tif err != nil {\n\t\treturn ConnectionRabbitMQ{}, err\n\t}\n\n\tch, err := conn.Channel()\n\treturn ConnectionRabbitMQ{\n\t\tChannel: ch,\n\t\tConn: conn,\n\t}, err\n}", "func CreateServer(url string, queue string, requestParser RequestParser) (Server, error) {\n\tconn, err := CreateConnection(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch := conn.Channel\n\terr = ch.Qos(\n\t\t1, // prefetchCount\n\t\t0, // prefetchSize\n\t\tfalse, // global\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq, err := ch.QueueDeclare(\n\t\tqueue, // name\n\t\ttrue, // durable\n\t\tfalse, // auto-delete\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmessages, err := ch.Consume(\n\t\tq.Name,\n\t\t\"\", // consumer\n\t\tfalse, // auto-ack\n\t\tfalse, // exclusive\n\t\tfalse, // no-local\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\n\treturn &rpcServer{\n\t\tconnection: conn,\n\t\tmessages: messages,\n\t\tdone: make(chan bool),\n\t\trequestParser: requestParser,\n\t}, nil\n}", "func NewService(mqConfig *commonCfg.MQConfig) (*AMQPService, func(), error) {\n\tconn, ch, err := rabbitmq.Dial(mqConfig.Username, mqConfig.Password, mqConfig.Host, mqConfig.Port)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tchannelWrapper := rabbitmq.AMQPChannel{ch}\n\tAMQPService := AMQPService{\n\t\tChannel: &channelWrapper,\n\t}\n\n\treturn &AMQPService, func() {\n\t\tconn.Close()\n\t\tch.Close()\n\t}, nil\n}", "func NewServer(name string, logger termlog.Logger) *Server {\n\tbroadcast := make(chan string, 50)\n\ts := &Server{\n\t\tname: name,\n\t\tbroadcast: broadcast,\n\t\tconnections: make(map[*websocket.Conn]bool),\n\t\tlogger: logger,\n\t}\n\tgo s.run(broadcast)\n\treturn s\n}", "func NewConsumer(amqpURI, exchange, exchangeType, queueName, key, ctag string) (*Consumer, error) {\n\tc := &Consumer{\n\t\tconn: nil,\n\t\tchannel: nil,\n\t\ttag: ctag,\n\t\tdone: make(chan error),\n\t}\n\n\tvar err error\n\n\tlog.Printf(\"dialing %q\", amqpURI)\n\tc.conn, err = amqp.Dial(amqpURI)\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Dial: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Dial: %s\", err)\n\t}\n\n\tgo func() {\n\t\tlog.Printf(\"closing: %s\", <-c.conn.NotifyClose(make(chan *amqp.Error)))\n\t}()\n\n\tlog.Printf(\"got Connection, getting Channel\")\n\tc.channel, err = c.conn.Channel()\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Channel: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Channel: %s\", err)\n\t}\n\n\tlog.Printf(\"got Channel, declaring Exchange (%q)\", exchange)\n\tif err = c.channel.ExchangeDeclare(\n\t\texchange, // name of the exchange\n\t\texchangeType, // type\n\t\ttrue, // durable\n\t\tfalse, // delete when complete\n\t\tfalse, // internal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t); err != nil {\n\t\tlog.Printf(\"RMQERR Exchange Declare: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Exchange Declare: %s\", err)\n\t}\n\n\tlog.Printf(\"declared Exchange, declaring Queue %q\", queueName)\n\tqueue, err := c.channel.QueueDeclare(\n\t\tqueueName, // name of the queue\n\t\ttrue, // durable\n\t\tfalse, // delete when usused\n\t\tfalse, // exclusive\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Queue Declare: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Queue Declare: %s\", err)\n\t}\n\n\tlog.Printf(\"declared Queue (%q %d messages, %d consumers), binding to Exchange (key %q)\",\n\t\tqueue.Name, queue.Messages, queue.Consumers, key)\n\n\tif err = c.channel.QueueBind(\n\t\tqueue.Name, // name of the queue\n\t\tkey, // bindingKey\n\t\texchange, // sourceExchange\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t); err != nil {\n\t\tlog.Printf(\"RMQERR Queue Bind: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Queue Bind: %s\", err)\n\t}\n\n\tlog.Printf(\"Queue bound to Exchange, starting Consume (consumer tag %q)\", c.tag)\n\tdeliveries, err := c.channel.Consume(\n\t\tqueue.Name, // name\n\t\tc.tag, // consumerTag,\n\t\tfalse, // noAck\n\t\tfalse, // exclusive\n\t\tfalse, // noLocal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Queue Consume: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Queue Consume: %s\", err)\n\t}\n\tgo handle(deliveries, c.done)\n\n\treturn c, nil\n}", "func ConnectToRabbitMQ() error {\n\ttime.Sleep(50 * time.Second)\n\tcfg := RabbitMqEnv{}\n\tif err := env.Parse(&cfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse env: %v\", err)\n\t}\n\n\tfmt.Printf(\"%+v\", cfg)\n\n\tconn, err := amqp.Dial(fmt.Sprintf(\"amqp://%s:%s@%s:%s/\",\n\t\tcfg.RabbitMqPass,\n\t\tcfg.RabbitMqUser,\n\t\tcfg.RabbitMqHost,\n\t\tcfg.RabbitMqPort,\n\t))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to connect to RabbitMQ: %v\", err)\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open a channel: %v\", err)\n\t}\n\n\tq, err := ch.QueueDeclare(\n\t\t\"hello\", // name\n\t\tfalse, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to declare a queue: %v\", err)\n\t}\n\n\tRabbitMQChan = ch\n\tRabbitMQQueue = q\n\n\treturn nil\n}", "func newServer(sc *ServerConfig, b backends.Backend, l log.Logger) (*server, error) {\n\tserver := &server{\n\t\tclientPool: NewPool(sc.MaxClients),\n\t\tclosedListener: make(chan bool, 1),\n\t\tlistenInterface: sc.ListenInterface,\n\t\tstate: ServerStateNew,\n\t\tenvelopePool: mail.NewPool(sc.MaxClients),\n\t}\n\tserver.logStore.Store(l)\n\tserver.backendStore.Store(b)\n\tlogFile := sc.LogFile\n\tif logFile == \"\" {\n\t\t// none set, use the same log file as mainlog\n\t\tlogFile = server.mainlog().GetLogDest()\n\t}\n\t// set level to same level as mainlog level\n\tmainlog, logOpenError := log.GetLogger(logFile, server.mainlog().GetLevel())\n\tserver.mainlogStore.Store(mainlog)\n\tif logOpenError != nil {\n\t\tserver.log().WithError(logOpenError).Errorf(\"Failed creating a logger for server [%s]\", sc.ListenInterface)\n\t}\n\n\tserver.setConfig(sc)\n\tserver.setTimeout(sc.Timeout)\n\tif err := server.configureSSL(); err != nil {\n\t\treturn server, err\n\t}\n\treturn server, nil\n}", "func NewServer(connectionString string, opts ...ServerOption) (*Server, error) {\n\ts := &Server{\n\t\tsubscribe: make(chan *subscription),\n\t\tredactions: make(FieldRedactions),\n\n\t\tctx: context.Background(),\n\t\tlistenerPingInterval: defaultPingInterval,\n\t}\n\tfor _, o := range opts {\n\t\to(s)\n\t}\n\tif s.logger == nil {\n\t\ts.logger = logrus.StandardLogger()\n\t}\n\tdb, err := sql.Open(\"postgres\", connectionString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"ping\")\n\t}\n\ts.l = pq.NewListener(connectionString, minReconnectInterval, maxReconnectInterval, func(ev pq.ListenerEventType, err error) {\n\t\ts.logger.WithField(\"listener-event\", ev).Debugln(\"got listener event\")\n\t\tif err != nil {\n\t\t\ts.logger.WithField(\"listener-event\", ev).WithError(err).Errorln(\"got listener event error\")\n\t\t}\n\t})\n\tif err := s.l.Listen(channel); err != nil {\n\t\treturn nil, errors.Wrap(err, \"listen\")\n\t}\n\tif err := s.l.Listen(channel + \"-ctl\"); err != nil {\n\t\treturn nil, errors.Wrap(err, \"listen\")\n\t}\n\ts.db = db\n\treturn s, nil\n}", "func NewServer(ctx context.Context, factory dependency.Factory) (*Server, error) {\n\tctx1, cancel := context.WithCancel(ctx)\n\n\ts := &Server{\n\t\tctx: ctx1,\n\t\tcancel: cancel,\n\t\tquerynode: qn.NewQueryNode(ctx, factory),\n\t\tgrpcErrChan: make(chan error),\n\t}\n\treturn s, nil\n}", "func NewServer() *Server {\n\tserver := &Server{\n\t\tmessages: make(chan []byte, 1),\n\t\tclients: make(map[chan []byte]bool),\n\t\tregister: make(chan chan []byte),\n\t\tunregister: make(chan chan []byte),\n\t}\n\tgo server.listen()\n\treturn server\n}", "func connectRabbitMQ() {\n\n\t// Start connection.\n\tconn, err := amqp.Dial(config.Client.Uri)\n\tutility.InitErrorHandler(\"Failed to connect to RabbitMQ\", err)\n\tdefer conn.Close()\n\n\tch, err := conn.Channel()\n\tutility.InitErrorHandler(\"Failed to open a channel\", err)\n\tdefer ch.Close()\n\n\t// Declare queue.\n\t_, err = ch.QueueDeclare(\n\t\tconfig.QueueName,\n\t\tconfig.Client.Queue.Durable,\n\t\tconfig.Client.Queue.AutoDelete,\n\t\tconfig.Client.Queue.Exclusive,\n\t\tconfig.Client.Queue.NoWait,\n\t\tnil,\n\t)\n\tutility.InitErrorHandler(\"Failed to declare a queue\", err)\n\n\terr = ch.Qos(\n\t\tconfig.Client.Prefetch.Count,\n\t\tconfig.Client.Prefetch.Size,\n\t\tconfig.Client.Prefetch.Global,\n\t)\n\tutility.InitErrorHandler(\"Failed to set QoS\", err)\n\n\tmsgs, err := ch.Consume(\n\t\tconfig.QueueName,\n\t\tconfig.Consumer,\n\t\tconfig.Client.Consume.AutoAck,\n\t\tconfig.Client.Consume.Exclusive,\n\t\tconfig.Client.Consume.NoLocal,\n\t\tconfig.Client.Consume.NoWait,\n\t\tnil,\n\t)\n\tutility.InitErrorHandler(\"Failed to register a consumer\", err)\n\n\tforever := make(chan bool)\n\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\t// Process queue items.\n\t\t\tprocessQueueItem(d)\n\t\t}\n\t}()\n\n\tfmt.Println(\" [*] Waiting for messages. To exit press CTRL+C\")\n\t<-forever\n}", "func NewServer(driver Driver, addr chan string) *GrpcServer {\n\treturn &GrpcServer{\n\t\tdriver: driver,\n\t\taddress: addr,\n\t}\n}", "func (p *LightningPool) new(ctx context.Context) (*amqp.Channel, error) {\n\treturn p.conn.Channel(ctx)\n}", "func NewServer() *Server {\n\ts := &Server{quit: make(chan bool)}\n\treturn s\n}", "func NewServer(host string, port int, packetQueue chan PacketQueue) (*Server, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Info(\"Starting server...\", addr.String())\n\n\treturn &Server{\n\t\tpacketQueue: packetQueue,\n\t\taddr: addr,\n\t\tsocket: nil,\n\t\tconnections: make(map[*Connection]struct{}),\n\t\tsignal: make(chan os.Signal, 1),\n\t\tmutex: new(sync.Mutex),\n\t}, nil\n}", "func NewRabbitMQConnection(conn *amqp.Connection) *RabbitMQConnection {\n\treturn &RabbitMQConnection{*conn}\n}", "func NewServer(conf Config, chatHander http.HandlerFunc, logs *logger.Logger) (*Server, error) {\n\tgabbleServer := new(Server)\n\n\tif logs != nil {\n\t\tgabbleServer.logs = logs\n\t}\n\n\tgabbleServer.addr = conf.GetHost() + \":\" + conf.GetPort()\n\n\tserv := new(http.Server)\n\tserv.Addr = gabbleServer.addr\n\tserv.Handler = chatHander\n\n\tgabbleServer.httpServer = serv\n\n\treturn gabbleServer, nil\n}", "func NewServerFactory(ctx context.Context, rcmd *channels.Remote, s string, l *logrus.Logger, wg *sync.WaitGroup) *Server {\n\treturn &Server{\n\t\tlogger: l,\n\t\tunixSocket: s,\n\t\trcmd: rcmd,\n\t\tctx: ctx,\n\t\twg: wg,\n\t}\n}", "func NewServer(ports []uint, hosts []string, pipelineFactory *PipelineFactory) *Server {\n\ts := new(Server)\n\ts.ports = ports\n\ts.hosts = hosts\n\ts.pipelineFactory = pipelineFactory\n\ts.eventHandlers = make([]ServerEventHandler, 0)\n\tcurrentServerState = make(chan server_state)\n\n\treturn s\n}", "func newServer(ctx common.Context, self *replica, listener net.Listener, workers int) (net.Server, error) {\n\tserver := &rpcServer{ctx: ctx, logger: ctx.Logger(), self: self}\n\treturn net.NewServer(ctx, listener, serverInitHandler(server), workers)\n}", "func (c *Consumer) init() (err error) {\n\tc.connection, err = amqp.Dial(c.config.URI)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() connect to RabbitMQ (%s) error: %v\", c.config.URI, err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t// close established connection in case of error\n\t\t\tcloseErr := c.connection.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\terr = fmt.Errorf(\"%v: Consumer.Init() close connection to RabbitMQ error: %v\", err, closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\tc.channel, err = c.connection.Channel()\n\tif err != nil {\n\t\terrString := \"Consumer.Init() create channel to RabbitMQ (%s) error: %v\"\n\t\treturn fmt.Errorf(errString, c.config.URI, err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t// close established channel in case of error\n\t\t\tcloseErr := c.channel.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\terr = fmt.Errorf(\"%v: Consumer.Init() close channel error: %v\", err, closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = c.channel.Qos(c.config.PrefetchCount, c.config.PrefetchSize, c.config.PrefetchGlobal)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() declare prefetch policy error: %v\", err)\n\t}\n\n\tc.deliveryChannel, err = c.channel.Consume(\n\t\tc.config.Queue, // queue\n\t\tc.config.Name, // consumer\n\t\tc.config.AutoAck, // autoAck\n\t\tc.config.Exclusive, // exclusive\n\t\tc.config.NoLocal, // noLocal\n\t\tc.config.NoWait, // noWait\n\t\tnil, // TODO: may be I should add support for args\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() create delivery channel error: %v\", err)\n\t}\n\n\t// channels for event listeners (connection)\n\tconnCloseChannel := make(chan *amqp.Error)\n\tc.connCloseChannel = c.connection.NotifyClose(connCloseChannel)\n\n\t// channels for event listeners (channel)\n\tchanCancelChannel := make(chan string)\n\tc.chanCancelChannel = c.channel.NotifyCancel(chanCancelChannel)\n\n\tchanCloseChannel := make(chan *amqp.Error)\n\tc.chanCloseChannel = c.channel.NotifyClose(chanCloseChannel)\n\n\treturn nil\n}", "func NewServer(rpc *cosmos.RPC, eventPublisher *publisher.EventPublisher, tokenToRunnerHash *sync.Map, logger tmlog.Logger) *Server {\n\treturn &Server{\n\t\trpc: rpc,\n\t\teventPublisher: eventPublisher,\n\t\ttokenToRunnerHash: tokenToRunnerHash,\n\t\texecInProgress: &sync.Map{},\n\t\tlogger: logger,\n\t}\n}", "func NewServer(config Config, shutdownChan chan bool) *server {\n\tif config.ReadTimeout == 0 {\n\t\tconfig.ReadTimeout = 10 * time.Second\n\t}\n\n\tif config.WriteTimeout == 0 {\n\t\tconfig.WriteTimeout = 10 * time.Second\n\t}\n\n\tconfig.nextCommandTimeout = 5 * time.Minute\n\n\treturn &server{\n\t\tconfig: config,\n\t\tshutdownChan: shutdownChan,\n\t}\n}", "func main(){\n\t//Connect to local host server\n\tport, err := amqp.Dial(\"amqp://guest:guest@rabbitmq:5672/\")\n\tfailError(err, \"Failed to connect to RabbitMQ.\")\n\tdefer port.Close()\n\n\t//Create a channel on port\n\tch, err := port.Channel()\n\tfailError(err, \"Failed to open a channel on port.\")\n\tdefer ch.Close()\n\n\t//Declare a callback queue\n\tqueue, err := ch.QueueDeclare(\n\t\t\"rpc_queue\", // name\n\t\tfalse, // durable flag\n\t\tfalse, // auto delete flag\n\t\tfalse, // exclusive flat\n\t\tfalse, // no-wait flag\n\t\tnil, // extra arguments\n\t)\n\tfailError(err, \"Failed to create a queue for channel.\")\n\n\t//Set QoS\n\terr = ch.Qos(\n\t\t1,\n\t\t0,\n\t\tfalse,\n\t\t)\n\tfailError(err, \"Failed to set channel QoS.\")\n\n\t//Register a client\n\tmsgs, err := ch.Consume(\n\t\tqueue.Name, // queue\n\t\t\"\", // consumer\n\t\tfalse, // auto-ack\n\t\tfalse, // exclusive\n\t\tfalse, // no-local\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\tfailError(err, \"Failed to register a consumer\")\n\n\t//Channel repeats receiving to keep server running\n\tloop := make(chan bool)\n\n\t//Process message and reply\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\t//Receive a message from client\n\t\t\tphrase := string(d.Body)\n\n\t\t\t//Convert phrase into fields\n\t\t\tphraseArr := strings.Fields(phrase)\n\n\t\t\t//Extract array elements\n\t\t\ta, _ := strconv.Atoi(phraseArr[1])\n\t\t\tb, _ := strconv.Atoi(phraseArr[2])\n\t\t\tc, _ := strconv.Atoi(phraseArr[3])\n\n\t\t\tvar response string\n\n\t\t\t//Perform an image processing function based on input\n\t\t\tswitch{\n\t\t\tcase a == 1:\n\t\t\t\tlog.Printf(\"Scaling %s\\n\", phraseArr[0])\n\t\t\t\tresponse = scaleImg(phraseArr[0], b)\n\t\t\tcase a == 2:\n\t\t\t\tlog.Printf(\"Copying %s\\n\", phraseArr[0])\n\t\t\t\tresponse = copyImg(phraseArr[0], b, c)\n\n\t\t\tcase a == 3:\n\t\t\t\tlog.Printf(\"Recursing %s\\n\", phraseArr[0])\n\t\t\t\tresponse = recurseImg(phraseArr[0])\n\t\t\t}\n\n\n\t\t\terr = ch.Publish(\n\t\t\t\t\"\", // exchange\n\t\t\t\td.ReplyTo, // routing key\n\t\t\t\tfalse, // mandatory\n\t\t\t\tfalse, // immediate\n\t\t\t\tamqp.Publishing{\n\t\t\t\t\tContentType: \"text/plain\",\n\t\t\t\t\tCorrelationId: d.CorrelationId,\n\t\t\t\t\tBody: []byte(response),\n\t\t\t\t})\n\t\t\tfailError(err, \"Failed to publish a reply.\")\n\n\t\t\td.Ack(false)\n\t\t}\n\t}()\n\n\t//Waiting on messages\n\tlog.Printf(\"Waiting on RPC Message\")\n\t<-loop\n}", "func New() *Aggregator {\n\tmq, _ := messaging.Connect(\"amqp://guest:guest@localhost:5672/\")\n\treturn &Aggregator{\n\t\tservers: make(map[URL]*serverStats),\n\t\twindowSize: 120,\n\t\tmq: mq,\n\t\tlogger: log.New(os.Stdout, \"aggregator: \", log.LstdFlags),\n\t}\n}", "func newBroker(config []byte) (*broker, error) {\n\tvar b broker\n\tvar c Config\n\tif err := json.Unmarshal(config, &c); err != nil {\n\t\treturn &b, errors.Wrap(err, \"unable to parse AMQP config\")\n\t}\n\tif err := c.validate(); err != nil {\n\t\treturn &b, errors.Wrap(err, \"could not validate config\")\n\t}\n\tb.Config = c\n\tb.closed = make(chan *amqp.Error)\n\tclose(b.closed)\n\treturn &b, nil\n}", "func Server(l net.Listener) {\n\tcont := electron.NewContainer(\"server\")\n\tc, err := cont.Accept(l)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tl.Close() // This server only accepts one connection\n\t// Process incoming endpoints till we get a Receiver link\n\tvar r electron.Receiver\n\tfor r == nil {\n\t\tin := <-c.Incoming()\n\t\tswitch in := in.(type) {\n\t\tcase *electron.IncomingSession, *electron.IncomingConnection:\n\t\t\tin.Accept() // Accept the incoming connection and session for the receiver\n\t\tcase *electron.IncomingReceiver:\n\t\t\tin.SetCapacity(10)\n\t\t\tin.SetPrefetch(true) // Automatic flow control for a buffer of 10 messages.\n\t\t\tr = in.Accept().(electron.Receiver)\n\t\tcase nil:\n\t\t\treturn // Connection is closed\n\t\tdefault:\n\t\t\tin.Reject(amqp.Errorf(\"example-server\", \"unexpected endpoint %v\", in))\n\t\t}\n\t}\n\tgo func() { // Reject any further incoming endpoints\n\t\tfor in := range c.Incoming() {\n\t\t\tin.Reject(amqp.Errorf(\"example-server\", \"unexpected endpoint %v\", in))\n\t\t}\n\t}()\n\t// Receive messages till the Receiver closes\n\trm, err := r.Receive()\n\tfor ; err == nil; rm, err = r.Receive() {\n\t\tfmt.Printf(\"server received: %q\\n\", rm.Message.Body())\n\t\trm.Accept() // Signal to the client that the message was accepted\n\t}\n\tfmt.Printf(\"server receiver closed: %v\\n\", err)\n}", "func NewServer(config *Config, logger kitlog.Logger) *Server {\n\tdb := postgres.NewDB(&postgres.Config{\n\t\tConnStr: config.ConnStr,\n\t\tEncryptionPassword: config.EncryptionPassword,\n\t}, logger)\n\n\tds := datastore.NewDatastoreProtobufClient(\n\t\tconfig.DatastoreAddr,\n\t\t&http.Client{\n\t\t\tTimeout: time.Second * 10,\n\t\t},\n\t)\n\n\tmv := pipeline.NewMovingAverager(config.Verbose, clock.New(), logger)\n\n\tprocessor := pipeline.NewProcessor(ds, mv, config.Verbose, logger)\n\n\tmqttClient := mqtt.NewClient(logger, config.Verbose)\n\n\tenc := rpc.NewEncoder(&rpc.Config{\n\t\tDB: db,\n\t\tMQTTClient: mqttClient,\n\t\tProcessor: processor,\n\t\tVerbose: config.Verbose,\n\t\tBrokerAddr: config.BrokerAddr,\n\t\tBrokerUsername: config.BrokerUsername,\n\t}, logger)\n\n\thooks := twrpprom.NewServerHooks(registry.DefaultRegisterer)\n\n\tbuildInfo.WithLabelValues(version.BinaryName, version.Version, version.BuildDate)\n\n\tlogger = kitlog.With(logger, \"module\", \"server\")\n\tlogger.Log(\n\t\t\"msg\", \"creating server\",\n\t\t\"datastore\", config.DatastoreAddr,\n\t\t\"mqttBroker\", config.BrokerAddr,\n\t\t\"listenAddr\", config.ListenAddr,\n\t\t\"mqttUsername\", config.BrokerAddr,\n\t)\n\n\ttwirpHandler := encoder.NewEncoderServer(enc, hooks)\n\n\t// multiplex twirp handler into a mux with our other handlers\n\tmux := goji.NewMux()\n\n\tmux.Handle(pat.Post(encoder.EncoderPathPrefix+\"*\"), twirpHandler)\n\tmux.Handle(pat.Get(\"/pulse\"), PulseHandler(db))\n\tmux.Handle(pat.Get(\"/metrics\"), promhttp.Handler())\n\n\tmux.Use(middleware.RequestIDMiddleware)\n\n\tmetricsMiddleware := middleware.MetricsMiddleware(\"decode\", \"encoder\", registry.DefaultRegisterer)\n\tmux.Use(metricsMiddleware)\n\n\t// create our http.Server instance\n\tsrv := &http.Server{\n\t\tAddr: config.ListenAddr,\n\t\tHandler: mux,\n\t}\n\n\t// return the instantiated server\n\treturn &Server{\n\t\tsrv: srv,\n\t\tencoder: enc,\n\t\tdb: db,\n\t\tmqtt: mqttClient,\n\t\tlogger: kitlog.With(logger, \"module\", \"server\"),\n\t\tdomains: config.Domains,\n\t}\n}", "func NewRabbitMQScaler(config *ScalerConfig) (Scaler, error) {\n\thttpClient := kedautil.CreateHTTPClient(config.GlobalHTTPTimeout)\n\tmeta, err := parseRabbitMQMetadata(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing rabbitmq metadata: %s\", err)\n\t}\n\n\tif meta.protocol == httpProtocol {\n\t\treturn &rabbitMQScaler{\n\t\t\tmetadata: meta,\n\t\t\thttpClient: httpClient,\n\t\t}, nil\n\t}\n\n\t// Override vhost if requested.\n\thost := meta.host\n\tif meta.vhostName != nil {\n\t\thostURI, err := amqp.ParseURI(host)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing rabbitmq connection string: %s\", err)\n\t\t}\n\t\thostURI.Vhost = *meta.vhostName\n\t\thost = hostURI.String()\n\t}\n\n\tconn, ch, err := getConnectionAndChannel(host)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error establishing rabbitmq connection: %s\", err)\n\t}\n\n\treturn &rabbitMQScaler{\n\t\tmetadata: meta,\n\t\tconnection: conn,\n\t\tchannel: ch,\n\t\thttpClient: httpClient,\n\t}, nil\n}", "func NewDefaultChannel() amqp.Channel {\n\tconn, err := amqp.Dial(\"amqp://guest:guest@localhost:5672/\")\n\tfailOnError(err, \"Failed to connect to RabbitMQ\")\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tfailOnError(err, \"Failed to open channel\")\n\t}\n\treturn *ch\n}", "func newServer() *negroni.Negroni {\n\tn := negroni.Classic()\n\tn.UseHandler(router())\n\treturn n\n}", "func Publisher(\n\tconStr string, // sample: \"amqp://guest:guest@127.0.0.1:5672/\"\n\tqueueName string,\n\tmsg []byte) bool {\n\tret := false\n\n\t//============================================\n\t// Connect to Server\n\t//============================================\n\tconn, err := amqp.Dial(conStr)\n\tif err != nil {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to connect to RabbitMQ\", err)\n\n\t\tdefer conn.Close()\n\t\treturn ret\n\t}\n\n\t//============================================\n\t// Create Channel\n\t//============================================\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to open a channel\", err)\n\n\t\tdefer ch.Close()\n\t\tdefer conn.Close()\n\t\treturn ret\n\t}\n\n\t//============================================\n\t// Create Queue\n\t//============================================\n\tq, err := ch.QueueDeclare(\n\t\tqueueName, // name\n\t\ttrue, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // arguments\n\t)\n\n\tif err != nil {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to declare a queue\", err)\n\n\t\tdefer ch.Close()\n\t\tdefer conn.Close()\n\t\treturn ret\n\t}\n\n\t//============================================\n\t// Send Message\n\t//============================================\n\tbody := msg\n\terr = ch.Publish(\n\t\t\"\", // exchange\n\t\tq.Name, // routing key\n\t\tfalse, // mandatory\n\t\tfalse, // immediate\n\t\tamqp.Publishing{\n\t\t\tContentType: \"text/plain\",\n\t\t\tBody: body,\n\t\t\tDeliveryMode: amqp.Persistent, // 1=Transient(non-persistent), 2=Persistent\n\t\t})\n\n\tif err == nil {\n\t\tret = true\n\t} else {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to publish a message\", err)\n\t}\n\n\t//============================================\n\t// Close\n\t//============================================\n\tdefer ch.Close()\n\tdefer conn.Close()\n\n\t//============================================\n\t// Return\n\t//============================================\n\treturn ret\n}", "func NewServer(db db, queue queue, logger logging.Logger, apiToken string, enableAPI, enableJobs bool) (*Server, error) {\n\treturn &Server{\n\t\tlogger: logger,\n\t\tqueue: queue,\n\t\tdb: db,\n\t\tapiToken: apiToken,\n\t\tenableAPI: enableAPI,\n\t\tenableJobs: enableJobs,\n\t}, nil\n}", "func NewRabbitMQClient(configurations config.RabbitMQConfigurations) (MessageClient, error) {\n\tconnection, channel, queue, err := setupRabbitMQ(configurations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewClient := &RabbitMQClient{\n\t\texchangeName: configurations.ExchangeName,\n\t\tqueueName: configurations.QueueName,\n\t\turl: configurations.URL,\n\t\tconnection: connection,\n\t\tchannel: channel,\n\t\tqueue: queue,\n\t}\n\n\treturn newClient, nil\n}", "func NewServer(t *testing.T, dbc *sql.DB) (*server.Server, string) {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tjtest.RequireNil(t, err)\n\n\tgrpcServer := grpc.NewServer(\n\t\tgrpc.UnaryInterceptor(interceptors.UnaryServerInterceptor),\n\t\tgrpc.StreamInterceptor(interceptors.StreamServerInterceptor))\n\n\tsrv := server.New(dbc, dbc)\n\n\tpb.RegisterGokuServer(grpcServer, srv)\n\n\tgo func() {\n\t\terr := grpcServer.Serve(l)\n\t\tjtest.RequireNil(t, err)\n\t}()\n\n\treturn srv, l.Addr().String()\n}", "func (mq *MessageQueue) NewChannel() (*amqp.Channel, error) {\n\tch, err := mq.Connection.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch.Qos(mq.Prefetch, 0, false)\n\treturn ch, nil\n}", "func NewServer() *Server {\n return &Server{\n Addr: DefaultAddr,\n }\n}", "func NewServer(options ...Option) *Server {\n\ts := &Server{\n\t\tsubscriptions: make(map[string]map[string]struct{}),\n\t}\n\ts.BaseService = *service.NewBaseService(nil, \"PubSub\", s)\n\n\tfor _, option := range options {\n\t\toption(s)\n\t}\n\n\t// if BufferCapacity option was not set, the channel is unbuffered\n\ts.cmds = make(chan cmd, s.cmdsCap)\n\n\treturn s\n}", "func New(cfg *Config) (*Handler, error) {\n\thandler := new(Handler)\n\turi := fmt.Sprintf(`amqp://%s`, cfg.Username)\n\turi += fmt.Sprintf(`:%s`, cfg.Password)\n\turi += fmt.Sprintf(`@%s:5672`, cfg.Host)\n\tif cfg.Vhost != \"/\" {\n\t\turi += fmt.Sprintf(`/%s`, cfg.Vhost)\n\t}\n\n\tconn, err := amqp.Dial(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thandler.conn = conn\n\treturn handler, nil\n\n}", "func (s *Server) newServer(spec *loads.Document, tcpPort int) *healthApi.Server {\n\tapi := restapi.NewCiliumHealthAPI(spec)\n\tapi.Logger = log.Printf\n\n\t// /hello\n\tapi.GetHelloHandler = NewGetHelloHandler(s)\n\n\tif enableAPI(s.Config.Admin, tcpPort) {\n\t\tapi.GetHealthzHandler = NewGetHealthzHandler(s)\n\t\tapi.ConnectivityGetStatusHandler = NewGetStatusHandler(s)\n\t\tapi.ConnectivityPutStatusProbeHandler = NewPutStatusProbeHandler(s)\n\t}\n\n\tsrv := healthApi.NewServer(api)\n\tif tcpPort == 0 {\n\t\tsrv.EnabledListeners = []string{\"unix\"}\n\t\tsrv.SocketPath = flags.Filename(defaults.SockPath)\n\t} else {\n\t\tsrv.EnabledListeners = []string{\"http\"}\n\t\tsrv.Port = tcpPort\n\t\tsrv.Host = \"\" // FIXME: Allow binding to specific IPs\n\t}\n\tsrv.ConfigureAPI()\n\n\treturn srv\n}", "func NewServer(mqttEndpoint string) Server {\n\treturn &server{\n\t\tdbPath: GetRandomDBName(),\n\t\tmqttEndpoint: mqttEndpoint,\n\t}\n}", "func newConfigServer() *ConfigServer {\n\treturn &ConfigServer{}\n}", "func main() {\n\n\tconn, err := amqp.Dial(\"amqp://guest:guest@localhost:5672/\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\n\tdefer conn.Close()\n\n\tfmt.Println(\"Successfully connected to our RabbitMQ\")\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\tdefer ch.Close()\n\n\tq, err := ch.QueueDeclare(\"Test Queue\", false, false, false, false, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(q)\n\n\tfor i := 0; i < 1000; i++ {\n\n\t\terr = ch.Publish(\"\", \"Test Queue\", false, false, amqp.Publishing{\n\t\t\tContentType: \"test/plain\",\n\t\t\tBody: []byte(\"Hello world!\"),\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"Successfully published Message to Queue\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tfmt.Println(q)\n}", "func NewServer(config *Config, cmFilter types.ClusterManagerFilter, clMng types.ClusterManager) Server {\n\tif config != nil {\n\t\t//graceful timeout setting\n\t\tif config.GracefulTimeout != 0 {\n\t\t\tGracefulTimeout = config.GracefulTimeout\n\t\t}\n\n\t\tnetwork.UseNetpollMode = config.UseNetpollMode\n\t\tif config.UseNetpollMode {\n\t\t\tlog.DefaultLogger.Infof(\"[server] [reconfigure] [new server] Netpoll mode enabled.\")\n\t\t}\n\t}\n\n\tkeeper.OnProcessShutDown(log.CloseAll)\n\n\tserver := &server{\n\t\tserverName: config.ServerName,\n\t\tstopChan: make(chan struct{}),\n\t\thandler: NewHandler(cmFilter, clMng),\n\t}\n\n\tinitListenerAdapterInstance(server.serverName, server.handler)\n\n\tservers = append(servers, server)\n\n\treturn server\n}", "func NewServer() *server {\n\treturn &server{}\n}", "func PrepareRabbitMQ(\n\tc config.Config,\n) (*amqp.Connection, *amqp.Queue, *amqp.Channel, error) {\n\t// connect to rabbit\n\tconn, err := amqp.Dial(c.MQURI)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tq, err := ch.QueueDeclare(\n\t\t\"notifications\", // name\n\t\ttrue, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusion\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn conn, &q, ch, nil\n}", "func NewServer(config *Config) *Server {\n\treturn &Server{\n\t\tconfig: config,\n\t\trouter: chi.NewRouter(),\n\t}\n}", "func NewServer(config config.Provider, service *service.Service, dbMysql *gorp.DbMap, dbPostgre *gorp.DbMap, cachePool *redis.Pool, logger *log.Logger) IServer {\n\treturn &server{\n\t\tconfig: config,\n\t\tservice: service,\n\t\tdbMysql: dbMysql,\n\t\tdbPostgre: dbPostgre,\n\t\tcachePool: cachePool,\n\t\tlogger: logger,\n\t}\n}", "func NewConsumer(cfg Config) *Consumer {\n\tconsumer := &Consumer{\n\t\tconfig: cfg,\n\t\tpubDeliveryChannel: make(chan amqp.Delivery, 100), // TODO: buffer size to config\n\t\treconnectMutex: make(chan struct{}, 1),\n\t\tfatalChannel: make(chan struct{}, 1),\n\t\tinvalidationChannel: make(chan struct{}, 1),\n\t\twg: sync.WaitGroup{},\n\t}\n\treturn consumer\n}", "func NewServer(appSender common.AppSender) *Server {\n\treturn &Server{appSender: appSender}\n}", "func initAmqp() (*amqp.Connection, *amqp.Channel) {\n\tconn, err := amqp.Dial(*amqpURI)\n\tfailOnError(err, \"Failed to connect to RabbitMQ\")\n\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to open a channel\")\n\n\terr = ch.ExchangeDeclare(\n\t\t\"test-exchange\", // name\n\t\t\"direct\", // type\n\t\ttrue, // durable\n\t\tfalse, // auto-deleted\n\t\tfalse, // internal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tfailOnError(err, \"Failed to declare the Exchange\")\n\treturn conn, ch\n}", "func NewServer(logger log.Logger, options ...Option) *Server {\n\ts := &Server{logger: logger}\n\n\ts.BaseService = *service.NewBaseService(logger, \"PubSub\", s)\n\tfor _, opt := range options {\n\t\topt(s)\n\t}\n\n\t// The queue receives items to be published.\n\ts.queue = make(chan item, s.queueCap)\n\n\t// The index tracks subscriptions by ID and query terms.\n\ts.subs.index = newSubIndex()\n\n\treturn s\n}", "func NewServer(options ...Option) *Server {\n\ts := &Server{\n\t\tsubscriptions: make(map[string]map[string]Query),\n\t}\n\ts.BaseService = *cmn.NewBaseService(nil, \"PubSub\", s)\n\n\tfor _, option := range options {\n\t\toption(s)\n\t}\n\n\t// if BufferCapacity option was not set, the channel is unbuffered\n\ts.cmds = make(chan cmd, s.cmdsCap)\n\n\treturn s\n}", "func RabbitMQConnect(addr string) (*RmqConnection, error) {\n\tvar c RmqConnection\n\tvar err error\n\tif c.conn, err = amqp.Dial(addr); err != nil {\n\t\treturn nil, err\n\t}\n\tif c.ch, err = c.conn.Channel(); err != nil {\n\t\tc.conn.Close()\n\t\treturn nil, err\n\t}\n\tc.stop = make(chan struct{})\n\tc.wg = &sync.WaitGroup{}\n\treturn &c, nil\n}", "func NewServer(credentials *RegistryCredentials, registryURL string) api.PublishRequestServer {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\ts := &publisherServer{Clientset: clientset, Credentials: credentials, RegistryURL: registryURL}\n\treturn s\n}", "func New(ctx context.Context, cfg models.Config) (*Queue, error) {\n\tconn, err := connect(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to connect to RabbitMQ \")\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to open a channel \")\n\t}\n\n\t_, err = ch.QueueDeclare(\"ItemQueue\", false, false, false, false, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to declare a queue \")\n\t}\n\n\treturn &Queue{ch, conn}, nil\n}", "func (r *RabbitMQ) Init(metadata bindings.Metadata) error {\n\tmeta, err := r.getRabbitMQMetadata(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.metadata = meta\n\n\tconn, err := amqp.Dial(meta.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.connection = conn\n\tr.channel = ch\n\treturn nil\n}", "func NewServer(conf config.Config) *Server {\n\tlog := logrus.New()\n\tif conf.Debug {\n\t\tlog.SetLevel(logrus.DebugLevel)\n\t}\n\tserver := &Server{\n\t\tconf: conf,\n\t\trouter: chi.NewRouter(),\n\t\troomManager: rooms.NewManager(log),\n\t\tlog: log,\n\t}\n\n\tr := server.router\n\t// A good base middleware stack\n\tr.Use(middleware.RequestID)\n\tr.Use(middleware.RealIP)\n\tr.Use(middleware.Logger)\n\tr.Use(middleware.Recoverer)\n\n\tr.Handle(\"/metrics\", promhttp.Handler())\n\tr.Get(\"/rooms/{roomName}/websocket\", server.websocketHandler)\n\tr.Group(func(r chi.Router) {\n\t\t// set timeout for non classic http calls\n\t\tr.Use(middleware.Timeout(60 * time.Second))\n\t\tserver.mountRestRoutes(r)\n\t\tserver.mountFileRoutes(r)\n\n\t})\n\n\treturn server\n}", "func NewServer(binding string, nodeMgr NodeManagerInterface) GRPCServer {\n\ts := grpc.NewServer()\n\tmyServer := &server{\n\t\tbinding: binding,\n\t\ts: s,\n\t\tnodeMgr: nodeMgr,\n\t}\n\tpb.RegisterCloudProviderVsphereServer(s, myServer)\n\treflection.Register(s)\n\treturn myServer\n}", "func NewConnection(d string) (*amqp.Connection, error) {\n\treturn amqp.Dial(d)\n}", "func NewServer(chatCmd chat.CommandService, chatQuery chat.QueryService, chatHub chat.Hub, login chat.LoginService, conf *Config) *Server {\n\tif conf == nil {\n\t\tconf = &DefaultConfig\n\t}\n\n\te := echo.New()\n\te.HideBanner = true\n\n\ts := &Server{\n\t\techo: e,\n\t\tloginHandler: NewLoginHandler(login),\n\t\trestHandler: NewRESTHandler(chatCmd, chatQuery),\n\t\tchatHub: chatHub,\n\t\tconf: *conf,\n\t}\n\ts.wsServer = ws.NewServerFunc(s.handleWsConn)\n\n\t// initilize router\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\t// set login handler\n\te.Use(s.loginHandler.Middleware())\n\te.POST(\"/login\", s.loginHandler.Login).\n\t\tName = \"doLogin\"\n\te.GET(\"/login\", s.loginHandler.GetLoginState).\n\t\tName = \"getLoginInfo\"\n\te.POST(\"/logout\", s.loginHandler.Logout).\n\t\tName = \"doLogout\"\n\n\tchatPath := path.Join(s.conf.ChatAPIPrefix, \"/chat\")\n\tchatGroup := e.Group(chatPath, s.loginHandler.Filter())\n\n\t// set restHandler\n\tchatGroup.POST(\"/rooms\", s.restHandler.CreateRoom).\n\t\tName = \"chat.createRoom\"\n\tchatGroup.DELETE(\"/rooms/:room_id\", s.restHandler.DeleteRoom).\n\t\tName = \"chat.deleteRoom\"\n\tchatGroup.GET(\"/rooms/:room_id\", s.restHandler.GetRoomInfo).\n\t\tName = \"chat.getRoomInfo\"\n\tchatGroup.POST(\"/rooms/:room_id/members\", s.restHandler.AddRoomMember).\n\t\tName = \"chat.addRoomMember\"\n\tchatGroup.DELETE(\"/rooms/:room_id/members\", s.restHandler.RemoveRoomMember).\n\t\tName = \"chat.removeRoomMember\"\n\n\tchatGroup.GET(\"/users/:user_id\", s.restHandler.GetUserInfo).\n\t\tName = \"chat.getUserInfo\"\n\n\tchatGroup.POST(\"/rooms/:room_id/messages\", s.restHandler.PostRoomMessage).\n\t\tName = \"chat.postRoomMessage\"\n\tchatGroup.GET(\"/rooms/:room_id/messages\", s.restHandler.GetRoomMessages).\n\t\tName = \"chat.getRoomMessages\"\n\tchatGroup.POST(\"/rooms/:room_id/messages/read\", s.restHandler.ReadRoomMessages).\n\t\tName = \"chat.readRoomMessages\"\n\tchatGroup.GET(\"/rooms/:room_id/messages/unread\", s.restHandler.GetUnreadRoomMessages).\n\t\tName = \"chat.getUnreadRoomMessages\"\n\n\t// set websocket handler\n\tchatGroup.GET(\"/ws\", s.serveChatWebsocket).\n\t\tName = \"chat.connentWebsocket\"\n\n\t// serve static content\n\tif s.conf.EnableServeStaticFile {\n\t\troute := path.Join(s.conf.StaticHandlerPrefix, \"/\")\n\t\te.Static(route, s.conf.StaticFileDir).Name = \"staticContents\"\n\t}\n\treturn s\n}", "func NewServer(be Backend) *Server {\n\treturn &Server{\n\t\t// Doubled maximum line length per RFC 5321 (Section 4.5.3.1.6)\n\t\tMaxLineLength: 2000,\n\n\t\tBackend: be,\n\t\tdone: make(chan struct{}, 1),\n\t\tErrorLog: log.New(os.Stderr, \"smtp/server \", log.LstdFlags),\n\t\tcaps: []string{\"PIPELINING\", \"8BITMIME\", \"ENHANCEDSTATUSCODES\", \"CHUNKING\"},\n\t\tauths: map[string]SaslServerFactory{\n\t\t\tsasl.Plain: func(conn *Conn) sasl.Server {\n\t\t\t\treturn sasl.NewPlainServer(func(identity, username, password string) error {\n\t\t\t\t\tif identity != \"\" && identity != username {\n\t\t\t\t\t\treturn errors.New(\"identities not supported\")\n\t\t\t\t\t}\n\n\t\t\t\t\tsess := conn.Session()\n\t\t\t\t\tif sess == nil {\n\t\t\t\t\t\tpanic(\"No session when AUTH is called\")\n\t\t\t\t\t}\n\n\t\t\t\t\treturn sess.AuthPlain(username, password)\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\tconns: make(map[*Conn]struct{}),\n\t}\n}", "func NewServer(configFilename string, config *Config) *Server {\n\tcasefoldedName, err := Casefold(config.Server.Name)\n\tif err != nil {\n\t\tlog.Println(fmt.Sprintf(\"Server name isn't valid: [%s]\", config.Server.Name), err.Error())\n\t\treturn nil\n\t}\n\n\t// startup check that we have HELP entries for every command\n\tfor name := range Commands {\n\t\t_, exists := Help[strings.ToLower(name)]\n\t\tif !exists {\n\t\t\tlog.Fatal(\"Help entry does not exist for \", name)\n\t\t}\n\t}\n\n\tif config.AuthenticationEnabled {\n\t\tSupportedCapabilities[SASL] = true\n\t}\n\n\tif config.Limits.LineLen.Tags > 512 || config.Limits.LineLen.Rest > 512 {\n\t\tSupportedCapabilities[MaxLine] = true\n\t\tCapValues[MaxLine] = fmt.Sprintf(\"%d,%d\", config.Limits.LineLen.Tags, config.Limits.LineLen.Rest)\n\t}\n\n\toperClasses, err := config.OperatorClasses()\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading oper classes:\", err.Error())\n\t}\n\topers, err := config.Operators(operClasses)\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading operators:\", err.Error())\n\t}\n\n\tconnectionLimits, err := NewConnectionLimits(config.Server.ConnectionLimits)\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading connection limits:\", err.Error())\n\t}\n\tconnectionThrottle, err := NewConnectionThrottle(config.Server.ConnectionThrottle)\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading connection throttler:\", err.Error())\n\t}\n\n\tserver := &Server{\n\t\taccounts: make(map[string]*ClientAccount),\n\t\tauthenticationEnabled: config.AuthenticationEnabled,\n\t\tchannels: make(ChannelNameMap),\n\t\tclients: NewClientLookupSet(),\n\t\tcommands: make(chan Command),\n\t\tconfigFilename: configFilename,\n\t\tconnectionLimits: connectionLimits,\n\t\tconnectionThrottle: connectionThrottle,\n\t\tctime: time.Now(),\n\t\tcurrentOpers: make(map[*Client]bool),\n\t\tidle: make(chan *Client),\n\t\tlimits: Limits{\n\t\t\tAwayLen: int(config.Limits.AwayLen),\n\t\t\tChannelLen: int(config.Limits.ChannelLen),\n\t\t\tKickLen: int(config.Limits.KickLen),\n\t\t\tMonitorEntries: int(config.Limits.MonitorEntries),\n\t\t\tNickLen: int(config.Limits.NickLen),\n\t\t\tTopicLen: int(config.Limits.TopicLen),\n\t\t\tChanListModes: int(config.Limits.ChanListModes),\n\t\t\tLineLen: LineLenLimits{\n\t\t\t\tTags: config.Limits.LineLen.Tags,\n\t\t\t\tRest: config.Limits.LineLen.Rest,\n\t\t\t},\n\t\t},\n\t\tlisteners: make(map[string]ListenerInterface),\n\t\tmonitoring: make(map[string][]Client),\n\t\tname: config.Server.Name,\n\t\tnameCasefolded: casefoldedName,\n\t\tnetworkName: config.Network.Name,\n\t\tnewConns: make(chan clientConn),\n\t\toperclasses: *operClasses,\n\t\toperators: opers,\n\t\tsignals: make(chan os.Signal, len(ServerExitSignals)),\n\t\trehashSignal: make(chan os.Signal, 1),\n\t\trestAPI: &config.Server.RestAPI,\n\t\twhoWas: NewWhoWasList(config.Limits.WhowasEntries),\n\t\tcheckIdent: config.Server.CheckIdent,\n\t}\n\n\t// open data store\n\tdb, err := buntdb.Open(config.Datastore.Path)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Failed to open datastore: %s\", err.Error()))\n\t}\n\tserver.store = db\n\n\t// check db version\n\terr = server.store.View(func(tx *buntdb.Tx) error {\n\t\tversion, _ := tx.Get(keySchemaVersion)\n\t\tif version != latestDbSchema {\n\t\t\tlog.Println(fmt.Sprintf(\"Database must be updated. Expected schema v%s, got v%s.\", latestDbSchema, version))\n\t\t\treturn errDbOutOfDate\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\t// close the db\n\t\tdb.Close()\n\t\treturn nil\n\t}\n\n\t// load *lines\n\tserver.loadDLines()\n\tserver.loadKLines()\n\n\t// load password manager\n\terr = server.store.View(func(tx *buntdb.Tx) error {\n\t\tsaltString, err := tx.Get(keySalt)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Could not retrieve salt string: %s\", err.Error())\n\t\t}\n\n\t\tsalt, err := base64.StdEncoding.DecodeString(saltString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpwm := NewPasswordManager(salt)\n\t\tserver.passwords = &pwm\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Could not load salt: %s\", err.Error()))\n\t}\n\n\tif config.Server.MOTD != \"\" {\n\t\tfile, err := os.Open(config.Server.MOTD)\n\t\tif err == nil {\n\t\t\tdefer file.Close()\n\n\t\t\treader := bufio.NewReader(file)\n\t\t\tfor {\n\t\t\t\tline, err := reader.ReadString('\\n')\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tline = strings.TrimRight(line, \"\\r\\n\")\n\t\t\t\t// \"- \" is the required prefix for MOTD, we just add it here to make\n\t\t\t\t// bursting it out to clients easier\n\t\t\t\tline = fmt.Sprintf(\"- %s\", line)\n\n\t\t\t\tserver.motdLines = append(server.motdLines, line)\n\t\t\t}\n\t\t}\n\t}\n\n\tif config.Server.Password != \"\" {\n\t\tserver.password = config.Server.PasswordBytes()\n\t}\n\n\tfor _, addr := range config.Server.Listen {\n\t\tserver.createListener(addr, config.TLSListeners())\n\t}\n\n\tif config.Server.Wslisten != \"\" {\n\t\tserver.wslisten(config.Server.Wslisten, config.Server.TLSListeners)\n\t}\n\n\t// registration\n\taccountReg := NewAccountRegistration(config.Registration.Accounts)\n\tserver.accountRegistration = &accountReg\n\n\t// Attempt to clean up when receiving these signals.\n\tsignal.Notify(server.signals, ServerExitSignals...)\n\tsignal.Notify(server.rehashSignal, syscall.SIGHUP)\n\n\tserver.setISupport()\n\n\t// start API if enabled\n\tif server.restAPI.Enabled {\n\t\tLog.info.Printf(\"%s rest API started on %s .\", server.name, server.restAPI.Listen)\n\t\tserver.startRestAPI()\n\t}\n\n\treturn server\n}", "func InitializeRabbitConnection(credentials *Credentials) {\n\tRabbitConnection, _ = createRabbitConnection(credentials)\n\t/*\n\t\tconfig.Config.Rabbit.Host,\n\t\t\tconfig.Config.Rabbit.Port,\n\t\t\tconfig.Config.Rabbit.Username,\n\t\t\tconfig.Config.Rabbit.Password,\n\t\t)*/\n}", "func RabbitMQAMQP(server, vHost string) Option {\n\treturn func(c *config) {\n\t\tc.serverURL = server\n\t\tc.vHost = vHost\n\t}\n}", "func newServer(handler connHandler, logger *zap.Logger) *server {\n\ts := &server{\n\t\thandler: handler,\n\t\tlogger: logger.With(zap.String(\"sector\", \"server\")),\n\t}\n\treturn s\n}", "func NewServer(c *Config) (*Server, error) {\n\t// validate config\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid config: %v\", err)\n\t}\n\n\t// create root context\n\tctx, cancel := context.WithCancel(context.Background())\n\n\t// register handlers\n\tmux := runtime.NewServeMux()\n\topts := []grpc.DialOption{grpc.WithInsecure()}\n\terr := proto.RegisterTodosHandlerFromEndpoint(ctx, mux, c.Endpoint, opts)\n\tif err != nil {\n\t\tdefer cancel()\n\t\treturn nil, fmt.Errorf(\"unable to register gateway handler: %v\", err)\n\t}\n\n\ts := Server{\n\t\tcancel: cancel,\n\t\tlog: c.Log,\n\t\tmux: mux,\n\t\tport: c.Port,\n\t}\n\treturn &s, nil\n}", "func NewSignalingServer(callQueue CallQueue) *SignalingServer {\n\treturn &SignalingServer{callQueue: callQueue}\n}", "func NewAMQPConsumer(config AMQPConfig, rk string) (*AMQPConsumer, error) {\n\ta, err := NewAMQP(config.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tDebug(\"amqp: setting channel QoS to\", config.Qos)\n\tif err := a.Channel.Qos(config.Qos, 0, false); err != nil {\n\t\treturn nil, err\n\t}\n\n\te := config.Exchange\n\tif err := a.Channel.ExchangeDeclare(\n\t\te.Name,\n\t\te.Kind,\n\t\te.Durable,\n\t\te.AutoDelete,\n\t\te.Internal,\n\t\te.NoWait,\n\t\tnil,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tq := config.Queue\n\tqueue, err := a.Channel.QueueDeclare(\n\t\tq.Name,\n\t\tq.Durable,\n\t\tq.AutoDelete,\n\t\tq.Exclusive,\n\t\tq.NoWait,\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, exch := range config.Queue.Bind {\n\t\tif err := a.Channel.QueueBind(queue.Name, rk, exch, q.NoWait, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tDebugf(\"amqp: binded queue %s to exchange %s with routing key %s\", queue.Name, exch, rk)\n\t}\n\n\treturn &AMQPConsumer{\n\t\tAMQP: a,\n\t\tConfig: config,\n\t\tQueue: queue,\n\t}, nil\n}", "func NewServer(cfg *Config) *Server {\n\treturn &Server{cfg}\n}", "func NewServer() *Server {\n\tlog.Println(\"Creating new instance of chat server...\")\n\treturn &Server{\n\t\trooms: make(map[string]*client.Room),\n\t\tcommands: make(chan client.Command),\n\t}\n}", "func NewServer() (Server, error) {\n\tconfig, err := config.GetConfig()\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\tlogFormatter := &logrus.TextFormatter{\n\t\tFullTimestamp: true,\n\t\tTimestampFormat: \"2006-01-02 15:04:05-0700\",\n\t}\n\tlogger := logrus.New()\n\tlogger.Formatter = logFormatter\n\n\tdatabaseConnection, err := db.NewDatabaseConnection(logger)\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\terr = databaseConnection.Connect()\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\t_, err = setup(databaseConnection)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tupstreamChannel := make(chan firebasexmpp.UpstreamMessage)\n\tsendChannel := make(chan firebasexmpp.DownstreamPayload)\n\tsupervisor := NewXMPPSupervisor(upstreamChannel, sendChannel, logger)\n\n\tlistenAddress := config.Web.GetListenAddress()\n\twebserver, err := web.NewWebserver(listenAddress, databaseConnection, sendChannel, logger)\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\treturn Server{\n\t\tdatabaseConnection: databaseConnection,\n\t\tlogger: logger,\n\t\tupstreamChannel: upstreamChannel,\n\t\tsendChannel: sendChannel,\n\t\tsupervisor: supervisor,\n\t\twebserver: webserver,\n\t}, nil\n}", "func NewServer(upstreams []*Upstream, cfg Config) *Server {\n\tdialer := cfg.Dialer\n\tif dialer == nil {\n\t\tdialer = &net.Dialer{}\n\t}\n\tlogger := cfg.Logger\n\tif logger == nil {\n\t\tlogger = log.DefaultLogger()\n\t}\n\n\ts := &Server{\n\t\tServer: well.Server{\n\t\t\tShutdownTimeout: cfg.ShutdownTimeout,\n\t\t},\n\n\t\tupstreams: upstreams,\n\t\tlogger: logger,\n\t\tdialer: dialer,\n\t\tpool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tbuf := make([]byte, copyBufferSize)\n\t\t\t\treturn &buf\n\t\t\t},\n\t\t},\n\t}\n\ts.Server.Handler = s.handleConnection\n\n\treturn s\n}", "func NewServer(config domain.ServerConfig) *Server {\n\tdebugger := logger.New(log.New(ioutil.Discard, \"\", 0))\n\tif config.Debug {\n\t\tdebugger = logger.New(log.New(os.Stderr, \"[debug] \", log.Flags()|log.Lshortfile))\n\t}\n\n\tdb, err := bolt.Open(config.BoltPath, 0644, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to start bolt db\")\n\t}\n\tdefer db.Close()\n\n\ts := &Server{\n\t\tConfig: config,\n\t\ti: uc.NewInteractor(\n\t\t\tconfig,\n\t\t\tcookies.New(config.CookieAge),\n\t\t\tdebugger,\n\t\t\tresources.New(encoder.New()),\n\t\t\thttpCaller.New(),\n\t\t\tmail.New(domain.EmailConfig{}),\n\t\t\tpathInfo.New(config),\n\t\t\tencoder.New(),\n\t\t\tsparql.New(),\n\t\t\tpages.New(config.DataRoot),\n\t\t\ttokenStorer.New(db),\n\t\t\tdomain.URIHandler{},\n\t\t\tuuid.New(),\n\t\t\tauthentication.New(httpCaller.New()),\n\t\t\tspkac.New(),\n\t\t),\n\t\tlogger: debugger,\n\t\tcookieManager: cookies.New(config.CookieAge),\n\t\tpathInformer: pathInfo.New(config),\n\t\turiManipulator: domain.URIHandler{},\n\t}\n\n\tmime.AddRDFExtension(s.Config.ACLSuffix)\n\tmime.AddRDFExtension(s.Config.MetaSuffix)\n\n\ts.logger.Debug(\"---- starting server ----\")\n\ts.logger.Debug(\"config: %#v\\n\", s.Config)\n\treturn s\n}", "func NewServer(db *sql.DB, numShards int) (*Server, error) {\n\tif numShards < 1 {\n\t\tnumShards = 1\n\t}\n\n\tqueue, err := NewEventQueue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Server{\n\t\tdb: db,\n\t\tqueue: queue,\n\t\tLoadAllMembers: true,\n\t\treadyShards: make([]bool, numShards),\n\t\treadyGuilds: make(map[int64]bool),\n\t\tloadedUsers: make(map[string]bool),\n\t}, nil\n}", "func NewServer(conf *Config, be *backend.Backend) (*Server, error) {\n\tauthInterceptor := interceptors.NewAuthInterceptor(be.Config.AuthWebhookURL)\n\tdefaultInterceptor := interceptors.NewDefaultInterceptor()\n\n\topts := []grpc.ServerOption{\n\t\tgrpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer(\n\t\t\tauthInterceptor.Unary(),\n\t\t\tdefaultInterceptor.Unary(),\n\t\t\tgrpcprometheus.UnaryServerInterceptor,\n\t\t)),\n\t\tgrpc.StreamInterceptor(grpcmiddleware.ChainStreamServer(\n\t\t\tauthInterceptor.Stream(),\n\t\t\tdefaultInterceptor.Stream(),\n\t\t\tgrpcprometheus.StreamServerInterceptor,\n\t\t)),\n\t}\n\n\tif conf.CertFile != \"\" && conf.KeyFile != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(conf.CertFile, conf.KeyFile)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t}\n\n\topts = append(opts, grpc.MaxConcurrentStreams(math.MaxUint32))\n\n\tyorkieServiceCtx, yorkieServiceCancel := context.WithCancel(context.Background())\n\n\tgrpcServer := grpc.NewServer(opts...)\n\thealthpb.RegisterHealthServer(grpcServer, health.NewServer())\n\tapi.RegisterYorkieServer(grpcServer, newYorkieServer(yorkieServiceCtx, be))\n\tapi.RegisterClusterServer(grpcServer, newClusterServer(be))\n\tgrpcprometheus.Register(grpcServer)\n\n\treturn &Server{\n\t\tconf: conf,\n\t\tgrpcServer: grpcServer,\n\t\tyorkieServiceCancel: yorkieServiceCancel,\n\t}, nil\n}", "func NewServer() *Server {\n\treturn &Server{name: \"\", handlers: nil}\n}", "func (service *QueueService) CreateChannel() (*amqp.Channel, error) {\n\treturn service.amqp.Channel()\n}", "func NewServer(configGetter core.KubernetesConfigGetter, kubeappsCluster string, stopCh <-chan struct{}, pluginConfigPath string) (*Server, error) {\n\tlog.Infof(\"+fluxv2 NewServer(kubeappsCluster: [%v], pluginConfigPath: [%s]\",\n\t\tkubeappsCluster, pluginConfigPath)\n\n\trepositoriesGvr := schema.GroupVersionResource{\n\t\tGroup: fluxGroup,\n\t\tVersion: fluxVersion,\n\t\tResource: fluxHelmRepositories,\n\t}\n\n\tif redisCli, err := common.NewRedisClientFromEnv(); err != nil {\n\t\treturn nil, err\n\t} else if chartCache, err := cache.NewChartCache(\"chartCache\", redisCli, stopCh); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\t// If no config is provided, we default to the existing values for backwards\n\t\t// compatibility.\n\t\tversionsInSummary := pkgutils.GetDefaultVersionsInSummary()\n\t\ttimeoutSecs := int32(-1)\n\t\tif pluginConfigPath != \"\" {\n\t\t\tversionsInSummary, timeoutSecs, err = parsePluginConfig(pluginConfigPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"%s\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"+fluxv2 using custom packages config with %v\\n\", versionsInSummary)\n\t\t} else {\n\t\t\tlog.Infof(\"+fluxv2 using default config since pluginConfigPath is empty\")\n\t\t}\n\n\t\ts := repoEventSink{\n\t\t\tclientGetter: clientgetter.NewBackgroundClientGetter(),\n\t\t\tchartCache: chartCache,\n\t\t}\n\t\trepoCacheConfig := cache.NamespacedResourceWatcherCacheConfig{\n\t\t\tGvr: repositoriesGvr,\n\t\t\tClientGetter: s.clientGetter,\n\t\t\tOnAddFunc: s.onAddRepo,\n\t\t\tOnModifyFunc: s.onModifyRepo,\n\t\t\tOnGetFunc: s.onGetRepo,\n\t\t\tOnDeleteFunc: s.onDeleteRepo,\n\t\t\tOnResyncFunc: s.onResync,\n\t\t}\n\t\tif repoCache, err := cache.NewNamespacedResourceWatcherCache(\n\t\t\t\"repoCache\", repoCacheConfig, redisCli, stopCh); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\treturn &Server{\n\t\t\t\tclientGetter: clientgetter.NewClientGetterWithApiExt(configGetter, kubeappsCluster),\n\t\t\t\tactionConfigGetter: clientgetter.NewHelmActionConfigGetter(configGetter, kubeappsCluster),\n\t\t\t\trepoCache: repoCache,\n\t\t\t\tchartCache: chartCache,\n\t\t\t\tkubeappsCluster: kubeappsCluster,\n\t\t\t\tversionsInSummary: versionsInSummary,\n\t\t\t\ttimeoutSeconds: timeoutSecs,\n\t\t\t}, nil\n\t\t}\n\t}\n}", "func main() {\n\tvar user string\n\tvar pwd string\n\tfmt.Print(\"RabbitMQ username: \")\n\tfmt.Scanln(&user)\n\tfmt.Print(\"RabbitMQ password: \")\n\tfmt.Scanln(&pwd)\n\n\tconn, err := amqp.Dial(fmt.Sprintf(\"amqp://%s:%s@159.65.220.217:5672\", user, pwd))\n\tfailOnError(err, \"Failed to connect\")\n\tdefer conn.Close()\n\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to create a channel\")\n\tdefer ch.Close()\n\n\tqueue, err := ch.QueueDeclare(\"hello-queue\", false, false, false, false, nil)\n\tfailOnError(err, \"Failed to create a queue\")\n\n\tmsgs, err := ch.Consume(queue.Name, \"\", false, false, false, false, nil)\n\tfailOnError(err, \"Failed to consume queue messages \")\n\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\tlog.Printf(\"Received message: %s\\n\", d.Body)\n\t\t\td.Ack(true)\n\t\t}\n\t}()\n\tlog.Printf(\"[*] Waiting for messages, please exit the program to stop\")\n\tforever := make(chan bool)\n\t<-forever\n}" ]
[ "0.7595138", "0.66407835", "0.6526455", "0.6236298", "0.6043651", "0.6040377", "0.6027341", "0.58490276", "0.58328205", "0.5806928", "0.5803156", "0.57954323", "0.5707904", "0.5688219", "0.5674982", "0.55992335", "0.55966425", "0.5593839", "0.5593327", "0.558049", "0.55695677", "0.55499446", "0.55499446", "0.5537921", "0.55231905", "0.54996526", "0.5492996", "0.5491618", "0.5485729", "0.54804355", "0.54778963", "0.54568166", "0.54401225", "0.543051", "0.54296714", "0.54131776", "0.5410793", "0.540596", "0.5405145", "0.5386939", "0.53737783", "0.5369777", "0.53676283", "0.5365264", "0.5355587", "0.53481364", "0.5344726", "0.5339063", "0.53306013", "0.53280693", "0.5325408", "0.5325091", "0.5322869", "0.5318536", "0.53139", "0.5307811", "0.5304836", "0.5297936", "0.52971905", "0.5293392", "0.52900714", "0.5289437", "0.5288942", "0.5285103", "0.5271811", "0.5259187", "0.52541184", "0.5253991", "0.5251747", "0.52432084", "0.5239343", "0.5236953", "0.5230357", "0.5230025", "0.5222238", "0.5221857", "0.5214534", "0.52099174", "0.52013636", "0.51973", "0.51900226", "0.51876235", "0.5184247", "0.5179556", "0.51789755", "0.5178107", "0.5174009", "0.5172696", "0.5171808", "0.5171337", "0.51582843", "0.51581097", "0.5149867", "0.5146988", "0.5142353", "0.51403415", "0.5138293", "0.5137628", "0.51342165", "0.5133087" ]
0.7509787
1
Defang Takes an IOC and defangs it using the standard defangReplacements
Defang принимает IOC и «дезактивирует» его с использованием стандартных defangReplacements
func (ioc *IOC) Defang() *IOC { copy := *ioc ioc = &copy // Just do a string replace on each if replacements, ok := defangReplacements[ioc.Type]; ok { for _, fangPair := range replacements { ioc.IOC = strings.ReplaceAll(ioc.IOC, fangPair.fanged, fangPair.defanged) } } return ioc }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ioc *IOC) Fang() *IOC {\n\tcopy := *ioc\n\tioc = &copy\n\n\t// String replace all defangs in our standard set\n\tif replacements, ok := defangReplacements[ioc.Type]; ok {\n\t\tfor _, fangPair := range replacements {\n\t\t\tioc.IOC = strings.ReplaceAll(ioc.IOC, fangPair.defanged, fangPair.fanged)\n\t\t}\n\t}\n\n\t// Regex replace everything from the fang replacements\n\tif replacements, ok := fangReplacements[ioc.Type]; ok {\n\t\tfor _, regexReplacement := range replacements {\n\t\t\t// Offset is incase we shrink the string and need to offset locations\n\t\t\toffset := 0\n\n\t\t\t// Get indexes of replacements and replace them\n\t\t\ttoReplace := regexReplacement.pattern.FindAllStringIndex(ioc.IOC, -1)\n\t\t\tfor _, location := range toReplace {\n\t\t\t\t// Update this found string\n\t\t\t\tstartSize := len(ioc.IOC)\n\t\t\t\tioc.IOC = ioc.IOC[0:location[0]-offset] + regexReplacement.replace + ioc.IOC[location[1]-offset:len(ioc.IOC)]\n\t\t\t\t// Update offset with how much the string shrunk (or grew)\n\t\t\t\toffset += startSize - len(ioc.IOC)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ioc\n}", "func goConvInvoc(a ClientArg) string {\n\tjsonConvTmpl := `\nvar {{.GoArg}} {{.GoType}}\nif {{.FlagArg}} != nil && len(*{{.FlagArg}}) > 0 {\n\terr = json.Unmarshal([]byte(*{{.FlagArg}}), &{{.GoArg}})\n\tif err != nil {\n\t\tpanic(errors.Wrapf(err, \"unmarshalling {{.GoArg}} from %v:\", {{.FlagArg}}))\n\t}\n}\n`\n\tif a.Repeated || !a.IsBaseType {\n\t\tcode, err := applyTemplate(\"UnmarshalCliArgs\", jsonConvTmpl, a, nil)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Couldn't apply template: %v\", err))\n\t\t}\n\t\treturn code\n\t}\n\treturn fmt.Sprintf(`%s := %s`, a.GoArg, flagTypeConversion(a))\n}", "func Defun(opname string, funcBody Mapper, quoter Mapper, env *Environment) {\n\topsym := GlobalEnvironment.Intern(opname, false)\n\topsym.Value = Atomize(&internalOp{sym: opsym, caller: funcBody, quoter: quoter})\n\tT().Debugf(\"new interal op %s = %v\", opsym.Name, opsym.Value)\n}", "func render(template string, def definition, params map[string]interface{}) (string, error) {\n\tctx := plush.NewContext()\n\tctx.Set(\"camelize_down\", camelizeDown)\n\tctx.Set(\"def\", def)\n\tctx.Set(\"params\", params)\n\ts, err := plush.Render(string(template), ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn s, nil\n}", "func (h *Handler) sidecarInjection(del bool, version, ns string) error {\n\texe, err := h.getExecutable(version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinjectCmd := \"add\"\n\tif del {\n\t\tinjectCmd = \"remove\"\n\t}\n\n\tcmd := &exec.Cmd{\n\t\tPath: exe,\n\t\tArgs: []string{\n\t\t\texe,\n\t\t\t\"namespace\",\n\t\t\tinjectCmd,\n\t\t\tns,\n\t\t},\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stdout,\n\t}\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn ErrRunExecutable(err)\n\t}\n\n\treturn nil\n}", "func (e Environment) Overridef(name string, format string, a ...interface{}) {\n\te[fmt.Sprintf(\"%s.override\", name)] = fmt.Sprintf(format, a...)\n}", "func setupSubst(objType string, search string, replace string) {\n\tif !globalType[objType] {\n\t\tabort.Msg(\"Unknown type %s\", objType)\n\t}\n\taddSubst := func(objType, search, replace string) {\n\t\tsubMap, ok := subst[objType]\n\t\tif !ok {\n\t\t\tsubMap = make(map[string]string)\n\t\t\tsubst[objType] = subMap\n\t\t}\n\t\tsubMap[search] = replace\n\t}\n\n\taddSubst(objType, search, replace)\n\n\tfor _, other := range aliases[objType] {\n\t\taddSubst(other, search, replace)\n\t}\n}", "func doBind(sc *Collection, originalInvokeF *provider, originalInitF *provider, real bool) error {\n\t// Split up the collection into LITERAL, STATIC, RUN, and FINAL groups. Add\n\t// init and invoke as faked providers. Flatten into one ordered list.\n\tvar invokeIndex int\n\tvar invokeF *provider\n\tvar initF *provider\n\tvar debuggingProvider **provider\n\tfuncs := make([]*provider, 0, len(sc.contents)+3)\n\t{\n\t\tvar err error\n\t\tinvokeF, err = characterizeInitInvoke(originalInvokeF, charContext{inputsAreStatic: false})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif invokeF.flows == nil {\n\t\t\treturn fmt.Errorf(\"internal error #4: no flows for invoke\")\n\t\t}\n\t\tnonStaticTypes := make(map[typeCode]bool)\n\t\tfor _, tc := range invokeF.flows[outputParams] {\n\t\t\tnonStaticTypes[tc] = true\n\t\t}\n\n\t\tbeforeInvoke, afterInvoke, err := sc.characterizeAndFlatten(nonStaticTypes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Add debugging provider\n\t\t{\n\t\t\td := newProvider(func() *Debugging { return nil }, -1, \"Debugging\")\n\t\t\td.cacheable = true\n\t\t\td.mustCache = true\n\t\t\td, err = characterizeFunc(d, charContext{inputsAreStatic: true})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"internal error #29: problem with debugging injectors: %s\", err)\n\t\t\t}\n\t\t\td.isSynthetic = true\n\t\t\tdebuggingProvider = &d\n\t\t\tfuncs = append(funcs, d)\n\t\t}\n\n\t\t// Add init\n\t\tif originalInitF != nil {\n\t\t\tinitF, err = characterizeInitInvoke(originalInitF, charContext{inputsAreStatic: true})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif initF.flows == nil {\n\t\t\t\treturn fmt.Errorf(\"internal error #5: no flows for initF\")\n\t\t\t}\n\t\t\tfuncs = append(funcs, initF)\n\t\t}\n\n\t\tfuncs = append(funcs, beforeInvoke...)\n\t\tinvokeIndex = len(funcs)\n\t\tfuncs = append(funcs, invokeF)\n\t\tfuncs = append(funcs, afterInvoke...)\n\n\t\tfor i, fm := range funcs {\n\t\t\tfm.chainPosition = i\n\t\t\tif fm.required {\n\t\t\t\tfm.include = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Figure out which providers must be included in the final chain. To do this,\n\t// first we figure out where each provider will get its inputs from when going\n\t// down the chain and where its inputs can be consumed when going up the chain.\n\t// Each of these linkages will be recorded as a dependency. Any dependency that\n\t// cannot be met will result in that provider being marked as impossible to\n\t// include.\n\t//\n\t// After all the dependencies are mapped, then we mark which providers will be\n\t// included in the final chain.\n\t//\n\t// The parameter list for the init function is complicated: both the inputs\n\t// and outputs are associated with downVmap, but they happen at different times:\n\t// some of the bookkeeping related to init happens in sequence with its position\n\t// in the function list, and some of it happens just before handling the invoke\n\t// function.\n\t//\n\t//\n\t// When that is finished, we can compute the upVmap and the downVmap.\n\n\t// Compute dependencies: set fm.downRmap, fm.upRmap, fm.cannotInclude,\n\t// fm.whyIncluded, fm.include\n\terr := computeDependenciesAndInclusion(funcs, initF)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Build the lists of parameters that are included in the value collections.\n\t// These are maps from types to position in the value collection.\n\t//\n\t// Also: calculate bypass zero for static chain. If there is a fallible injector\n\t// in the static chain, then part of the static chain my not run. Fallible\n\t// injectors need to know know which types need to be zeroed if the remaining\n\t// static injectors are skipped.\n\t//\n\t// Also: calculate the skipped-inner() zero for the run chain. If a wrapper\n\t// does not call the remainder of the chain, then the values returned by the remainder\n\t// of the chain must be zero'ed.\n\tdownVmap := make(map[typeCode]int)\n\tdownCount := 0\n\tupVmap := make(map[typeCode]int)\n\tupCount := 0\n\tfor _, fm := range funcs {\n\t\tif !fm.include {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, flow := range fm.flows {\n\t\t\tfor _, tc := range flow {\n\t\t\t\tupVmap[tc] = -1\n\t\t\t\tdownVmap[tc] = -1\n\t\t\t}\n\t\t}\n\t}\n\t// calculate for the static set\n\tfor i := invokeIndex - 1; i >= 0; i-- {\n\t\tfm := funcs[i]\n\t\tfm.mustZeroIfRemainderSkipped = vmapMapped(downVmap)\n\t\taddToVmap(fm, outputParams, downVmap, fm.downRmap, &downCount)\n\t}\n\tif initF != nil {\n\t\tfor _, tc := range initF.flows[bypassParams] {\n\t\t\tif rm, found := initF.downRmap[tc]; found {\n\t\t\t\ttc = rm\n\t\t\t}\n\t\t\tif downVmap[tc] == -1 {\n\t\t\t\treturn fmt.Errorf(\"Type required by init func, %s, not provided by any static group injectors\", tc)\n\t\t\t}\n\t\t}\n\t}\n\t// calculate for the run set\n\tfor i := len(funcs) - 1; i >= invokeIndex; i-- {\n\t\tfm := funcs[i]\n\t\tfm.downVmapCount = downCount\n\t\taddToVmap(fm, inputParams, downVmap, fm.downRmap, &downCount)\n\t\tfm.upVmapCount = upCount\n\t\taddToVmap(fm, returnParams, upVmap, fm.upRmap, &upCount)\n\t\tfm.mustZeroIfInnerNotCalled = vmapMapped(upVmap)\n\t}\n\n\t// Fill in debugging (if used)\n\tif (*debuggingProvider).include {\n\t\t(*debuggingProvider).fn = func() *Debugging {\n\t\t\tincluded := make([]string, 0, len(funcs)+3)\n\t\t\tfor _, fm := range funcs {\n\t\t\t\tif fm.include {\n\t\t\t\t\tincluded = append(included, fmt.Sprintf(\"%s %s\", fm.group, fm))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnamesIncluded := make([]string, 0, len(funcs)+3)\n\t\t\tfor _, fm := range funcs {\n\t\t\t\tif fm.include {\n\t\t\t\t\tif fm.index >= 0 {\n\t\t\t\t\t\tnamesIncluded = append(namesIncluded, fmt.Sprintf(\"%s(%d)\", fm.origin, fm.index))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnamesIncluded = append(namesIncluded, fm.origin)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tincludeExclude := make([]string, 0, len(funcs)+3)\n\t\t\tfor _, fm := range funcs {\n\t\t\t\tif fm.include {\n\t\t\t\t\tincludeExclude = append(includeExclude, fmt.Sprintf(\"INCLUDED: %s %s BECAUSE %s\", fm.group, fm, fm.whyIncluded))\n\t\t\t\t} else {\n\t\t\t\t\tincludeExclude = append(includeExclude, fmt.Sprintf(\"EXCLUDED: %s %s BECAUSE %s\", fm.group, fm, fm.cannotInclude))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar trace string\n\t\t\tif debugEnabled() {\n\t\t\t\ttrace = \"debugging already in progress\"\n\t\t\t} else {\n\t\t\t\ttrace = captureDoBindDebugging(sc, originalInvokeF, originalInitF)\n\t\t\t}\n\n\t\t\treproduce := generateReproduce(funcs, invokeF, initF)\n\n\t\t\treturn &Debugging{\n\t\t\t\tIncluded: included,\n\t\t\t\tNamesIncluded: namesIncluded,\n\t\t\t\tIncludeExclude: includeExclude,\n\t\t\t\tTrace: trace,\n\t\t\t\tReproduce: reproduce,\n\t\t\t}\n\t\t}\n\t}\n\tif debugEnabled() {\n\t\tfor _, fm := range funcs {\n\t\t\tdumpF(\"funclist\", fm)\n\t\t}\n\t}\n\n\t// Generate wrappers and split the handlers into groups (static, middleware, final)\n\tcollections := make(map[groupType][]*provider)\n\tfor _, fm := range funcs {\n\t\tif !fm.include {\n\t\t\tcontinue\n\t\t}\n\t\terr := generateWrappers(fm, downVmap, upVmap, upCount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcollections[fm.group] = append(collections[fm.group], fm)\n\t}\n\tif len(collections[finalGroup]) != 1 {\n\t\treturn fmt.Errorf(\"internal error #1: no final func provided\")\n\t}\n\n\t// Over the course of the following loop, f will be redefined\n\t// over and over so that at the end of the loop it will be a\n\t// function that executes the entire RUN chain.\n\tf := collections[finalGroup][0].wrapEndpoint\n\tfor i := len(collections[runGroup]) - 1; i >= 0; i-- {\n\t\tn := collections[runGroup][i]\n\n\t\tswitch n.class {\n\t\tcase wrapperFunc:\n\t\t\tinner := f\n\t\t\tw := n.wrapWrapper\n\t\t\tf = func(v valueCollection) valueCollection {\n\t\t\t\treturn w(v, inner)\n\t\t\t}\n\t\tcase injectorFunc, fallibleInjectorFunc:\n\t\t\tj := i - 1\n\t\tInjectors:\n\t\t\tfor j >= 0 {\n\t\t\t\tswitch collections[runGroup][j].class {\n\t\t\t\tdefault:\n\t\t\t\t\tbreak Injectors\n\t\t\t\tcase injectorFunc, fallibleInjectorFunc: //okay\n\t\t\t\t}\n\t\t\t\tj--\n\t\t\t}\n\t\t\tj++\n\t\t\tnext := f\n\t\t\tinjectors := make([]func(valueCollection) (bool, valueCollection), 0, i-j+1)\n\t\t\tfor k := j; k <= i; k++ {\n\t\t\t\tinjectors = append(injectors, collections[runGroup][k].wrapFallibleInjector)\n\t\t\t}\n\t\t\tf = func(v valueCollection) valueCollection {\n\t\t\t\tfor _, injector := range injectors {\n\t\t\t\t\terrored, upV := injector(v)\n\t\t\t\t\tif errored {\n\t\t\t\t\t\treturn upV\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn next(v)\n\t\t\t}\n\t\t\ti = j\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"internal error #2: should not be here: %s\", n.class)\n\t\t}\n\t}\n\n\t// Initialize the value collection. When invoke is called the baseValues\n\t// collection will be copied.\n\tbaseValues := make(valueCollection, downCount)\n\tfor _, lit := range collections[literalGroup] {\n\t\ti := downVmap[lit.flows[outputParams][0]]\n\t\tif i >= 0 {\n\t\t\tbaseValues[i] = reflect.ValueOf(lit.fn)\n\t\t}\n\t}\n\n\t// Generate static chain function\n\trunStaticChain := func() error {\n\t\tdebugf(\"STATIC CHAIN LENGTH: %d\", len(collections[staticGroup]))\n\t\tfor _, inj := range collections[staticGroup] {\n\t\t\tdebugf(\"STATIC CHAIN CALLING %s\", inj)\n\n\t\t\terr := inj.wrapStaticInjector(baseValues)\n\t\t\tif err != nil {\n\t\t\t\tdebugf(\"STATIC CHAIN RETURNING EARLY DUE TO ERROR %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tfor _, inj := range collections[staticGroup] {\n\t\tif inj.wrapStaticInjector == nil {\n\t\t\treturn inj.errorf(\"internal error #3: missing static injector wrapping\")\n\t\t}\n\t}\n\n\t// Generate and bind init func.\n\tinitFunc := func() {}\n\tvar initOnce sync.Once\n\tif initF != nil {\n\t\toutMap, err := generateOutputMapper(initF, 0, outputParams, downVmap, \"init inputs\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinMap, err := generateInputMapper(initF, 0, bypassParams, initF.bypassRmap, downVmap, \"init results\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdebugln(\"SET INIT FUNC\")\n\t\tif real {\n\t\t\treflect.ValueOf(initF.fn).Elem().Set(\n\t\t\t\treflect.MakeFunc(reflect.ValueOf(initF.fn).Type().Elem(),\n\t\t\t\t\tfunc(inputs []reflect.Value) []reflect.Value {\n\t\t\t\t\t\tdebugln(\"INSIDE INIT\")\n\t\t\t\t\t\t// if initDone panic, return error, or ignore?\n\t\t\t\t\t\tinitOnce.Do(func() {\n\t\t\t\t\t\t\toutMap(baseValues, inputs)\n\t\t\t\t\t\t\tdebugln(\"RUN STATIC CHAIN\")\n\t\t\t\t\t\t\t_ = runStaticChain()\n\t\t\t\t\t\t})\n\t\t\t\t\t\tdumpValueArray(baseValues, \"base values before init return\", downVmap)\n\t\t\t\t\t\tout := inMap(baseValues)\n\t\t\t\t\t\tdebugln(\"DONE INIT\")\n\t\t\t\t\t\tdumpValueArray(out, \"init return\", nil)\n\t\t\t\t\t\tdumpF(\"init\", initF)\n\n\t\t\t\t\t\treturn out\n\t\t\t\t\t}))\n\t\t}\n\t\tdebugln(\"SET INIT FUNC - DONE\")\n\n\t} else {\n\t\tinitFunc = func() {\n\t\t\tinitOnce.Do(func() {\n\t\t\t\t_ = runStaticChain()\n\t\t\t})\n\t\t}\n\t}\n\n\t// Generate and bind invoke func\n\t{\n\t\toutMap, err := generateOutputMapper(invokeF, 0, outputParams, downVmap, \"invoke inputs\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinMap, err := generateInputMapper(invokeF, 0, returnedParams, invokeF.upRmap, upVmap, \"invoke results\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdebugln(\"SET INVOKE FUNC\")\n\t\tif real {\n\t\t\treflect.ValueOf(invokeF.fn).Elem().Set(\n\t\t\t\treflect.MakeFunc(reflect.ValueOf(invokeF.fn).Type().Elem(),\n\t\t\t\t\tfunc(inputs []reflect.Value) []reflect.Value {\n\t\t\t\t\t\tinitFunc()\n\t\t\t\t\t\tvalues := baseValues.Copy()\n\t\t\t\t\t\tdumpValueArray(values, \"invoke - before input copy\", downVmap)\n\t\t\t\t\t\toutMap(values, inputs)\n\t\t\t\t\t\tdumpValueArray(values, \"invoke - after input copy\", downVmap)\n\t\t\t\t\t\tret := f(values)\n\t\t\t\t\t\treturn inMap(ret)\n\t\t\t\t\t}))\n\t\t}\n\t\tdebugln(\"SET INVOKE FUNC - DONE\")\n\t}\n\n\treturn nil\n}", "func istioUninject(args []string, opts *options.Options) error {\n\tglooNS := opts.Metadata.Namespace\n\n\tclient := helpers.MustKubeClient()\n\t_, err := client.CoreV1().Namespaces().Get(opts.Top.Ctx, glooNS, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remove gateway_proxy_sds cluster from the gateway-proxy configmap\n\tconfigMaps, err := client.CoreV1().ConfigMaps(glooNS).List(opts.Top.Ctx, metav1.ListOptions{})\n\tfor _, configMap := range configMaps.Items {\n\t\tif configMap.Name == gatewayProxyConfigMap {\n\t\t\t// Make sure we don't already have the gateway_proxy_sds cluster set up\n\t\t\terr := removeSdsCluster(&configMap)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = client.CoreV1().ConfigMaps(glooNS).Update(opts.Top.Ctx, &configMap, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tdeployments, err := client.AppsV1().Deployments(glooNS).List(opts.Top.Ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, deployment := range deployments.Items {\n\t\tif deployment.Name == \"gateway-proxy\" {\n\t\t\tcontainers := deployment.Spec.Template.Spec.Containers\n\n\t\t\t// Remove Sidecars\n\t\t\tsdsPresent := false\n\t\t\tistioPresent := false\n\t\t\tif len(containers) > 1 {\n\t\t\t\tfor i := len(containers) - 1; i >= 0; i-- {\n\t\t\t\t\tcontainer := containers[i]\n\t\t\t\t\tif container.Name == \"sds\" {\n\t\t\t\t\t\tsdsPresent = true\n\t\t\t\t\t\tcopy(containers[i:], containers[i+1:])\n\t\t\t\t\t\tcontainers = containers[:len(containers)-1]\n\t\t\t\t\t}\n\t\t\t\t\tif container.Name == \"istio-proxy\" {\n\t\t\t\t\t\tistioPresent = true\n\n\t\t\t\t\t\tcopy(containers[i:], containers[i+1:])\n\t\t\t\t\t\tcontainers = containers[:len(containers)-1]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !sdsPresent || !istioPresent {\n\t\t\t\treturn ErrMissingSidecars\n\t\t\t}\n\n\t\t\tdeployment.Spec.Template.Spec.Containers = containers\n\n\t\t\tremoveIstioVolumes(&deployment)\n\t\t\t_, err = client.AppsV1().Deployments(glooNS).Update(opts.Top.Ctx, &deployment, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn nil\n}", "func revertInitialisms(s string) string {\n\tfor i := 0; i < len(commonInitialisms); i++ {\n\t\ts = strings.ReplaceAll(s, commonInitialisms[i][0], commonInitialisms[i][1])\n\t}\n\treturn s\n}", "func preprocessString(alias *Alias, str string) (string, error) {\n\t// Load Remote/Local alias definitions\n\tif externalDefinitionErr := alias.loadExternalAlias(); externalDefinitionErr != nil {\n\t\treturn \"\", externalDefinitionErr\n\t}\n\n\talias.loadGlobalAlias()\n\n\t// Validate alias definitions\n\tif improperFormatErr := alias.resolveMapAndValidate(); improperFormatErr != nil {\n\t\treturn \"\", improperFormatErr\n\t}\n\n\tvar out strings.Builder\n\tvar command strings.Builder\n\tongoingCmd := false\n\n\t// Search and replace all strings with the directive\n\t// (sam) we add a placeholder space at the end of the string below\n\t// to force the state machine to END. We remove it before returning\n\t// the result to user\n\tfor _, char := range str + \" \" {\n\t\tif ongoingCmd {\n\t\t\tif char == alias.directive && command.Len() == 0 { // Escape Character Triggered\n\t\t\t\tout.WriteRune(alias.directive)\n\t\t\t\tongoingCmd = false\n\t\t\t} else if !isAlphanumeric(char) { // Delineates the end of an alias\n\t\t\t\tresolvedCommand, commandPresent := alias.AliasMap[command.String()]\n\t\t\t\t// If command is not found we assume this to be the expect item itself.\n\t\t\t\tif !commandPresent {\n\t\t\t\t\tout.WriteString(string(alias.directive) + command.String() + string(char))\n\t\t\t\t\tongoingCmd = false\n\t\t\t\t\tcommand.Reset()\n\t\t\t\t} else {\n\t\t\t\t\tout.WriteString(resolvedCommand)\n\t\t\t\t\tif char != alias.directive {\n\t\t\t\t\t\tongoingCmd = false\n\t\t\t\t\t\tout.WriteRune(char)\n\t\t\t\t\t}\n\t\t\t\t\tcommand.Reset()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcommand.WriteRune(char)\n\t\t\t}\n\t\t} else if char == alias.directive {\n\t\t\tongoingCmd = true\n\t\t} else {\n\t\t\tout.WriteRune(char)\n\t\t}\n\t}\n\n\treturn strings.TrimSuffix(out.String(), \" \"), nil\n}", "func newServiceNameReplacer() *strings.Replacer {\n\tvar mapping [256]byte\n\t// we start with everything being replaces with underscore, and later fix some safe characters\n\tfor i := range mapping {\n\t\tmapping[i] = '_'\n\t}\n\t// digits are safe\n\tfor i := '0'; i <= '9'; i++ {\n\t\tmapping[i] = byte(i)\n\t}\n\t// lower case letters are safe\n\tfor i := 'a'; i <= 'z'; i++ {\n\t\tmapping[i] = byte(i)\n\t}\n\t// upper case letters are safe, but convert them to lower case\n\tfor i := 'A'; i <= 'Z'; i++ {\n\t\tmapping[i] = byte(i - 'A' + 'a')\n\t}\n\t// dash and dot are safe\n\tmapping['-'] = '-'\n\tmapping['.'] = '.'\n\n\t// prepare array of pairs of bad/good characters\n\toldnew := make([]string, 0, 2*(256-2-10-int('z'-'a'+1)))\n\tfor i := range mapping {\n\t\tif mapping[i] != byte(i) {\n\t\t\toldnew = append(oldnew, string(rune(i)), string(rune(mapping[i])))\n\t\t}\n\t}\n\n\treturn strings.NewReplacer(oldnew...)\n}", "func Auto(c *rux.Context, i interface{}) {\n\n}", "func replaceImports(content string, imports []string) string {\n\t// make sure that deeper imports will be replaced first\n\t// it is required for correct processing of nested packages\n\tsort.Sort(sort.Reverse(sort.StringSlice(imports)))\n\tfor i, imp := range imports {\n\t\tcontent = strings.Replace(content, imp, genPackageAlias(i), -1)\n\t}\n\treturn content\n}", "func substitution(answer string) string {\n\treflections := map[string]string{\n\t\t\"am\": \"are\",\n\t\t\"was\": \"were\",\n\t\t\"i\": \"you\",\n\t\t\"i'd\": \"you would\",\n\t\t\"i've\": \"you have\",\n\t\t\"i'll\": \"you will\",\n\t\t\"my\": \"your\",\n\t\t\"are\": \"am\",\n\t\t\"you've\": \"I have\",\n\t\t\"you'll\": \"I will\",\n\t\t\"your\": \"my\",\n\t\t\"yours\": \"mine\",\n\t\t\"you\": \"me\",\n\t\t\"me\": \"you\",\n\t\t\"myself\": \"yourself\",\n\t\t\"yourself\": \"myself\",\n\t\t\"i'm\": \"you are\",\n\t}\n\n\twords := strings.Split(answer, \" \") // get slices of the words\n\n\tfor i, word := range words {\t// loop through whole sentence\n\t\tif val, ok := reflections[word]; ok {\t// check for the word in reflection\n\t\t\twords[i] = val // substitite the value\n\t\t}//if\n\t}//for\n\n\t// Return substituted string\n\treturn strings.Join(words, \" \") // join back into sentence\n}", "func AddComponent(parent *ast.File, compo *adl.Struct) (component *ast.Struct, _ error) {\n\trequiresInitStub := false\n\tfor _, method := range compo.Methods {\n\t\tif method.StubDefault {\n\t\t\trequiresInitStub = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(compo.Inject) > 0 {\n\t\trequiresInitStub = true\n\t}\n\n\tcomponent = ast.NewStruct(compo.Name.String()).SetComment(compo.Comment.String() + \"\\n\\nThe stereotype of this type is '\" + compo.Stereotype.String() + \"'.\")\n\tparent.AddTypes(component)\n\n\tif requiresInitStub {\n\t\tshortName := strings.ToLower(compo.Name.String()[0:1])\n\t\tc := ast.NewFunc(\"New\"+golang.MakePublic(compo.Name.String())).SetComment(\"...allocates and initializes a new \"+compo.Name.String()+\" instance.\").\n\t\t\tAddResults(\n\t\t\t\tast.NewParam(\"\", ast.NewTypeDeclPtr(ast.NewSimpleTypeDecl(ast.Name(parent.Pkg().Path+\".\"+compo.Name.String())))),\n\t\t\t\tast.NewParam(\"\", ast.NewSimpleTypeDecl(stdlib.Error)),\n\t\t\t)\n\n\t\tinjectFieldAssigns := \"\"\n\t\tfor _, injection := range compo.Inject {\n\t\t\tp := ast.NewParam(injection.Name.String(), astutil.MakeTypeDecl(injection.Type))\n\t\t\tif injection.Comment.String() != \"\" {\n\t\t\t\tp.SetComment(injection.Comment.String())\n\t\t\t}\n\n\t\t\tc.AddParams(p)\n\t\t\tinjectFieldAssigns += shortName + \".\" + MakePrivate(injection.Name.String()) + \"=\" + injection.Name.String() + \"\\n\"\n\t\t}\n\n\t\tc.SetBody(ast.NewBlock(ast.NewTpl(shortName + \" := &\" + compo.Name.String() + \"{}\\n\" + injectFieldAssigns + \"\\nif err := \" + shortName + \".init(); err != nil {\\nreturn nil, {{.Use \\\"fmt.Errorf\\\"}}(\\\"cannot initialize '\" + compo.Name.String() + \"': %w\\\",err)}\\n\\n return \" + shortName + \",nil\\n\")))\n\n\t\tcomponent.AddFactoryRefs(c)\n\t\tparent.AddNodes(c)\n\t}\n\n\tif requiresInitStub {\n\t\tdefaultComponent := ast.NewStruct(golang.MakePrivate(\"Default\" + compo.Name.String())).\n\t\t\tSetComment(\"...is an implementation stub for \" + compo.Name.String() + \".\\nThe sole purpose of this type is to mock the method contract and each method should be shadowed\\nby a concrete implementation.\").\n\t\t\tSetVisibility(ast.Private)\n\n\t\tdefaultComponent.AddMethods(ast.NewFunc(\"init\").\n\t\t\tAddResults(ast.NewParam(\"\", ast.NewSimpleTypeDecl(stdlib.Error))).\n\t\t\tSetVisibility(ast.Private).\n\t\t\tSetComment(\"...is invoked from the constructor/factory function to setup any pre-variants.\\nShadow this method as required.\").\n\t\t\tSetBody(ast.NewBlock(ast.NewReturnStmt(ast.NewIdentLit(\"nil\")))))\n\n\t\tcomponent.AddEmbedded(ast.NewSimpleTypeDecl(ast.Name(defaultComponent.TypeName)))\n\n\t\tfor _, method := range compo.Methods {\n\t\t\taMethod := ast.NewFunc(method.Name.String()).SetComment(method.Comment.String() + \"\\nShadow this method as required.\")\n\t\t\tfor _, param := range method.In {\n\t\t\t\taMethod.AddParams(ast.NewParam(param.Name.String(), astutil.MakeTypeDecl(param.Type)).SetComment(param.Comment.String()))\n\t\t\t}\n\n\t\t\tfor _, param := range method.Out {\n\t\t\t\taMethod.AddResults(ast.NewParam(param.Name.String(), astutil.MakeTypeDecl(param.Type)).SetComment(param.Comment.String()))\n\t\t\t}\n\n\t\t\taMethod.SetBody(ast.NewBlock(ast.NewTpl(`panic(\"not yet implemented\")`)))\n\t\t\tdefaultComponent.AddMethods(aMethod)\n\n\t\t}\n\n\t\tparent.AddTypes(defaultComponent)\n\t}\n\n\tfor _, decl := range compo.Inject {\n\t\tf := ast.NewField(MakePrivate(decl.Name.String()),\n\t\t\tastutil.MakeTypeDecl(decl.Type)).\n\t\t\tSetComment(decl.Comment.String()).\n\t\t\tSetVisibility(ast.Private)\n\n\t\tif decl.Comment.String() == \"\" {\n\t\t\tswitch decl.Stereotype.String() {\n\t\t\tcase adl.Cfg:\n\t\t\t\tf.SetComment(\"...is the components configuration and injected at construction time.\")\n\t\t\tdefault:\n\t\t\t\tif decl.Stereotype.String() != \"\" {\n\t\t\t\t\tf.SetComment(\"...is the components '\" + decl.Stereotype.String() + \"' and injected at construction time.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcomponent.AddFields(f)\n\t}\n\n\tfor _, field := range compo.Fields {\n\t\tf := ast.NewField(field.Name.String(), astutil.MakeTypeDecl(field.Type)).SetComment(field.Comment.String())\n\t\tif field.Private {\n\t\t\tf.SetVisibility(ast.Private)\n\t\t}\n\n\t\tif field.CfgCmdLineFlag {\n\t\t\tstereotype.FieldFrom(f).SetProgramFlag(true)\n\t\t}\n\n\t\tcomponent.AddFields(f)\n\t}\n\n\tswitch compo.Stereotype.String() {\n\tcase adl.Cfg:\n\t\tstereotype.StructFrom(component).\n\t\t\tSetIsConfiguration(true)\n\t}\n\n\treturn component, nil\n}", "func (b *Baa) SetDI(name string, h interface{}) {\n\tswitch name {\n\tcase \"logger\":\n\t\tif _, ok := h.(Logger); !ok {\n\t\t\tpanic(\"DI logger must be implement interface baa.Logger\")\n\t\t}\n\tcase \"render\":\n\t\tif _, ok := h.(Renderer); !ok {\n\t\t\tpanic(\"DI render must be implement interface baa.Renderer\")\n\t\t}\n\tcase \"router\":\n\t\tif _, ok := h.(Router); !ok {\n\t\t\tpanic(\"DI router must be implement interface baa.Router\")\n\t\t}\n\t}\n\tb.di.Set(name, h)\n}", "func IFaceAnnotationGenerator(toDir string, an ast.AnnotationDeclaration, itr ast.InterfaceDeclaration, pkgDeclr ast.PackageDeclaration, pkg ast.Package) ([]gen.WriteDirective, error) {\n\tinterfaceName := itr.Object.Name.Name\n\tinterfaceNameLower := strings.ToLower(interfaceName)\n\n\tmethods := itr.Methods(&pkgDeclr)\n\n\timports := make(map[string]string, 0)\n\n\tfor _, method := range methods {\n\t\t// Retrieve all import paths for arguments.\n\t\tfunc(args []ast.ArgType) {\n\t\t\tfor _, argument := range args {\n\t\t\t\tif argument.Import2.Path != \"\" {\n\t\t\t\t\timports[argument.Import2.Path] = argument.Import2.Name\n\t\t\t\t}\n\t\t\t\tif argument.Import.Path != \"\" {\n\t\t\t\t\timports[argument.Import.Path] = argument.Import.Name\n\t\t\t\t}\n\t\t\t}\n\t\t}(method.Args)\n\n\t\t// Retrieve all import paths for returns.\n\t\tfunc(args []ast.ArgType) {\n\t\t\tfor _, argument := range args {\n\t\t\t\tif argument.Import2.Path != \"\" {\n\t\t\t\t\timports[argument.Import2.Path] = argument.Import2.Name\n\t\t\t\t}\n\t\t\t\tif argument.Import.Path != \"\" {\n\t\t\t\t\timports[argument.Import.Path] = argument.Import.Name\n\t\t\t\t}\n\t\t\t}\n\t\t}(method.Returns)\n\t}\n\n\tvar wantedImports []gen.ImportItemDeclr\n\n\tfor path, name := range imports {\n\t\twantedImports = append(wantedImports, gen.Import(path, name))\n\t}\n\n\timplGen := gen.Block(\n\t\tgen.Package(\n\t\t\tgen.Name(ast.WhichPackage(toDir, pkg)),\n\t\t\tgen.Imports(wantedImports...),\n\t\t\tgen.Block(\n\t\t\t\tgen.SourceText(\n\t\t\t\t\tstring(templates.Must(\"iface/iface.tml\")),\n\t\t\t\t\tstruct {\n\t\t\t\t\t\tInterfaceName string\n\t\t\t\t\t\tPackage ast.Package\n\t\t\t\t\t\tMethods []ast.FunctionDefinition\n\t\t\t\t\t}{\n\t\t\t\t\t\tPackage: pkg,\n\t\t\t\t\t\tMethods: methods,\n\t\t\t\t\t\tInterfaceName: interfaceName,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t)\n\n\tvar directives []gen.WriteDirective\n\n\timpImports := append([]gen.ImportItemDeclr{\n\t\tgen.Import(\"time\", \"\"),\n\t\tgen.Import(\"runtime\", \"\"),\n\t\tgen.Import(pkg.Path, \"\"),\n\t}, wantedImports...)\n\n\tdirectives = append(directives, gen.WriteDirective{\n\t\tWriter: fmtwriter.New(implGen, true, true),\n\t\tFileName: fmt.Sprintf(\"%s_impl.go\", interfaceNameLower),\n\t\tDontOverride: true,\n\t})\n\n\tif val, ok := an.Params[\"tests\"]; ok && val == \"true\" {\n\t\timplSnitchGen := gen.Block(\n\t\t\tgen.Package(\n\t\t\t\tgen.Name(\"snitch\"),\n\t\t\t\tgen.Imports(impImports...),\n\t\t\t\tgen.Block(\n\t\t\t\t\tgen.SourceText(\n\t\t\t\t\t\tstring(templates.Must(\"iface/iface-little-snitch.tml\")),\n\t\t\t\t\t\tstruct {\n\t\t\t\t\t\t\tPackage ast.Package\n\t\t\t\t\t\t\tInterfaceName string\n\t\t\t\t\t\t\tMethods []ast.FunctionDefinition\n\t\t\t\t\t\t}{\n\t\t\t\t\t\t\tPackage: pkg,\n\t\t\t\t\t\t\tInterfaceName: interfaceName,\n\t\t\t\t\t\t\tMethods: itr.Methods(&pkgDeclr),\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\n\t\tdirectives = append(directives, gen.WriteDirective{\n\t\t\tDir: \"snitch\",\n\t\t\tWriter: fmtwriter.New(implSnitchGen, true, true),\n\t\t\tFileName: fmt.Sprintf(\"%s_little_snitch.go\", interfaceNameLower),\n\t\t\tDontOverride: true,\n\t\t})\n\n\t\ttestImports := append([]gen.ImportItemDeclr{\n\t\t\tgen.Import(\"testing\", \"\"),\n\t\t\tgen.Import(pkg.Path, \"\"),\n\t\t\tgen.Import(\"github.com/influx6/faux/tests\", \"\"),\n\t\t\tgen.Import(filepath.Join(pkg.Path, toDir, \"snitch\"), \"\"),\n\t\t}, wantedImports...)\n\n\t\ttestGen := gen.Block(\n\t\t\tgen.Package(\n\t\t\t\tgen.Name(fmt.Sprintf(\"%s_test\", ast.WhichPackage(toDir, pkg))),\n\t\t\t\tgen.Imports(testImports...),\n\t\t\t\tgen.Block(\n\t\t\t\t\tgen.SourceText(\n\t\t\t\t\t\tstring(templates.Must(\"iface/iface-test.tml\")),\n\t\t\t\t\t\tstruct {\n\t\t\t\t\t\t\tInterfaceName string\n\t\t\t\t\t\t\tPackage ast.Package\n\t\t\t\t\t\t\tMethods []ast.FunctionDefinition\n\t\t\t\t\t\t}{\n\t\t\t\t\t\t\tPackage: pkg,\n\t\t\t\t\t\t\tInterfaceName: interfaceName,\n\t\t\t\t\t\t\tMethods: itr.Methods(&pkgDeclr),\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\n\t\tdirectives = append(directives, gen.WriteDirective{\n\t\t\tWriter: fmtwriter.New(testGen, true, true),\n\t\t\tFileName: fmt.Sprintf(\"%s_impl_test.go\", interfaceNameLower),\n\t\t\tDontOverride: true,\n\t\t})\n\t}\n\n\treturn directives, nil\n}", "func Replace(node Node, visitor func(Node) Node) {\n\tswitch n := node.(type) {\n\tcase *Abort:\n\tcase *API:\n\t\tfor i, c := range n.Enums {\n\t\t\tn.Enums[i] = visitor(c).(*Enum)\n\t\t}\n\t\tfor i, c := range n.Definitions {\n\t\t\tn.Definitions[i] = visitor(c).(*Definition)\n\t\t}\n\t\tfor i, c := range n.Classes {\n\t\t\tn.Classes[i] = visitor(c).(*Class)\n\t\t}\n\t\tfor i, c := range n.Pseudonyms {\n\t\t\tn.Pseudonyms[i] = visitor(c).(*Pseudonym)\n\t\t}\n\t\tfor i, c := range n.Externs {\n\t\t\tn.Externs[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Subroutines {\n\t\t\tn.Subroutines[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Functions {\n\t\t\tn.Functions[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Methods {\n\t\t\tn.Methods[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Globals {\n\t\t\tn.Globals[i] = visitor(c).(*Global)\n\t\t}\n\t\tfor i, c := range n.StaticArrays {\n\t\t\tn.StaticArrays[i] = visitor(c).(*StaticArray)\n\t\t}\n\t\tfor i, c := range n.Maps {\n\t\t\tn.Maps[i] = visitor(c).(*Map)\n\t\t}\n\t\tfor i, c := range n.Pointers {\n\t\t\tn.Pointers[i] = visitor(c).(*Pointer)\n\t\t}\n\t\tfor i, c := range n.Slices {\n\t\t\tn.Slices[i] = visitor(c).(*Slice)\n\t\t}\n\t\tfor i, c := range n.References {\n\t\t\tn.References[i] = visitor(c).(*Reference)\n\t\t}\n\t\tfor i, c := range n.Signatures {\n\t\t\tn.Signatures[i] = visitor(c).(*Signature)\n\t\t}\n\tcase *ArrayAssign:\n\t\tn.To = visitor(n.To).(*ArrayIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *ArrayIndex:\n\t\tn.Array = visitor(n.Array).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *ArrayInitializer:\n\t\tn.Array = visitor(n.Array).(Type)\n\t\tfor i, c := range n.Values {\n\t\t\tn.Values[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Slice:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *SliceIndex:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *SliceAssign:\n\t\tn.To = visitor(n.To).(*SliceIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *Assert:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\tcase *Assign:\n\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\tn.RHS = visitor(n.RHS).(Expression)\n\tcase *Annotation:\n\t\tfor i, c := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Block:\n\t\tfor i, c := range n.Statements {\n\t\t\tn.Statements[i] = visitor(c).(Statement)\n\t\t}\n\tcase BoolValue:\n\tcase *BinaryOp:\n\t\tif n.LHS != nil {\n\t\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\t}\n\t\tif n.RHS != nil {\n\t\t\tn.RHS = visitor(n.RHS).(Expression)\n\t\t}\n\tcase *BitTest:\n\t\tn.Bitfield = visitor(n.Bitfield).(Expression)\n\t\tn.Bits = visitor(n.Bits).(Expression)\n\tcase *UnaryOp:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Branch:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\t\tn.True = visitor(n.True).(*Block)\n\t\tif n.False != nil {\n\t\t\tn.False = visitor(n.False).(*Block)\n\t\t}\n\tcase *Builtin:\n\tcase *Reference:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Call:\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tn.Target = visitor(n.Target).(*Callable)\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(Expression)\n\t\t}\n\tcase *Callable:\n\t\tif n.Object != nil {\n\t\t\tn.Object = visitor(n.Object).(Expression)\n\t\t}\n\t\tn.Function = visitor(n.Function).(*Function)\n\tcase *Case:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *Cast:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Class:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*Field)\n\t\t}\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *ClassInitializer:\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*FieldInitializer)\n\t\t}\n\tcase *Choice:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Definition:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *DefinitionUsage:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\t\tn.Definition = visitor(n.Definition).(*Definition)\n\tcase *DeclareLocal:\n\t\tn.Local = visitor(n.Local).(*Local)\n\t\tif n.Local.Value != nil {\n\t\t\tn.Local.Value = visitor(n.Local.Value).(Expression)\n\t\t}\n\tcase Documentation:\n\tcase *Enum:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, e := range n.Entries {\n\t\t\tn.Entries[i] = visitor(e).(*EnumEntry)\n\t\t}\n\tcase *EnumEntry:\n\tcase *Fence:\n\t\tif n.Statement != nil {\n\t\t\tn.Statement = visitor(n.Statement).(Statement)\n\t\t}\n\tcase *Field:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase *FieldInitializer:\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase Float32Value:\n\tcase Float64Value:\n\tcase *Function:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tif n.Return != nil {\n\t\t\tn.Return = visitor(n.Return).(*Parameter)\n\t\t}\n\t\tfor i, c := range n.FullParameters {\n\t\t\tn.FullParameters[i] = visitor(c).(*Parameter)\n\t\t}\n\t\tif n.Block != nil {\n\t\t\tn.Block = visitor(n.Block).(*Block)\n\t\t}\n\t\tn.Signature = visitor(n.Signature).(*Signature)\n\tcase *Global:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\tcase *StaticArray:\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\t\tn.SizeExpr = visitor(n.SizeExpr).(Expression)\n\tcase *Signature:\n\tcase Int8Value:\n\tcase Int16Value:\n\tcase Int32Value:\n\tcase Int64Value:\n\tcase *Iteration:\n\t\tn.Iterator = visitor(n.Iterator).(*Local)\n\t\tn.From = visitor(n.From).(Expression)\n\t\tn.To = visitor(n.To).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *MapIteration:\n\t\tn.IndexIterator = visitor(n.IndexIterator).(*Local)\n\t\tn.KeyIterator = visitor(n.KeyIterator).(*Local)\n\t\tn.ValueIterator = visitor(n.ValueIterator).(*Local)\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase Invalid:\n\tcase *Length:\n\t\tn.Object = visitor(n.Object).(Expression)\n\tcase *Local:\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Map:\n\t\tn.KeyType = visitor(n.KeyType).(Type)\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\tcase *MapAssign:\n\t\tn.To = visitor(n.To).(*MapIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *MapContains:\n\t\tn.Key = visitor(n.Key).(Expression)\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *MapIndex:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *MapRemove:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Key = visitor(n.Key).(Expression)\n\tcase *MapClear:\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *Member:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Field = visitor(n.Field).(*Field)\n\tcase *MessageValue:\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(*FieldInitializer)\n\t\t}\n\tcase *New:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\tcase *Parameter:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Pointer:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Pseudonym:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.To = visitor(n.To).(Type)\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *Return:\n\t\tif n.Value != nil {\n\t\t\tn.Value = visitor(n.Value).(Expression)\n\t\t}\n\tcase *Select:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Choices {\n\t\t\tn.Choices[i] = visitor(c).(*Choice)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase StringValue:\n\tcase *Switch:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Cases {\n\t\t\tn.Cases[i] = visitor(c).(*Case)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(*Block)\n\t\t}\n\tcase Uint8Value:\n\tcase Uint16Value:\n\tcase Uint32Value:\n\tcase Uint64Value:\n\tcase *Unknown:\n\tcase *Clone:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *Copy:\n\t\tn.Src = visitor(n.Src).(Expression)\n\t\tn.Dst = visitor(n.Dst).(Expression)\n\tcase *Create:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\t\tn.Initializer = visitor(n.Initializer).(*ClassInitializer)\n\tcase *Ignore:\n\tcase *Make:\n\t\tn.Type = visitor(n.Type).(*Slice)\n\t\tn.Size = visitor(n.Size).(Expression)\n\tcase Null:\n\tcase *PointerRange:\n\t\tn.Pointer = visitor(n.Pointer).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Read:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceContains:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceRange:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Write:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unsupported semantic node type %T\", n))\n\t}\n}", "func nonResolvingHandler(name string, input interface{}, template interface{}) interface{} {\n\treturn nil\n}", "func IC(o ...interface{}) {\n\tif enableOutput {\n\t\tas, _ := toArgSlice(o, reflectsource.GetParentArgExprAllAsString())\n\t\toutputFunction(formatToString(as, enableSyntaxHighlighting))\n\t}\n}", "func (r *NuxeoReconciler) annotateDep(backingService v1alpha1.BackingService, dep *appsv1.Deployment) error {\n\tbuf := &bytes.Buffer{}\n\tenc := gob.NewEncoder(buf)\n\tif err := enc.Encode(backingService); err != nil {\n\t\treturn err\n\t}\n\tutil.AnnotateTemplate(dep, common.BackingSvcAnnotation+\".\"+backingService.Name, util.CRCBytes(buf.Bytes()))\n\treturn nil\n}", "func Infod(output string, d interface{}) {\n\tbuildAndShipMessage(output, \"INFO\", false, d)\n}", "func (d *DefaulterBuilder) ToInterfaceImplementation() *astmodel.InterfaceImplementation {\n\tgrp, ver := d.resourceName.PackageReference().GroupVersion()\n\n\t// e.g. grp = \"microsoft.network.azure.com\"\n\t// e.g. resource = \"backendaddresspools\"\n\t// e.g. ver = \"v1\"\n\n\tresource := d.resourceName.Name()\n\n\tgrp = strings.ToLower(grp + astmodel.GroupSuffix)\n\tnonPluralResource := strings.ToLower(resource)\n\tresource = strings.ToLower(d.resourceName.Plural().Name())\n\n\t// e.g. \"mutate-microsoft-network-azure-com-v1-backendaddresspool\"\n\t// note that this must match _exactly_ how controller-runtime generates the path\n\t// or it will not work!\n\tpath := fmt.Sprintf(\"/mutate-%s-%s-%s\", strings.ReplaceAll(grp, \".\", \"-\"), ver, nonPluralResource)\n\n\t// e.g. \"default.v123.backendaddresspool.azure.com\"\n\tname := fmt.Sprintf(\"default.%s.%s.%s\", ver, resource, grp)\n\n\tannotation := fmt.Sprintf(\n\t\t\"+kubebuilder:webhook:path=%s,mutating=true,sideEffects=None,\"+\n\t\t\t\"matchPolicy=Exact,failurePolicy=fail,groups=%s,resources=%s,\"+\n\t\t\t\"verbs=create;update,versions=%s,name=%s,admissionReviewVersions=v1\",\n\t\tpath,\n\t\tgrp,\n\t\tresource,\n\t\tver,\n\t\tname)\n\n\tfuncs := []astmodel.Function{\n\t\tNewResourceFunction(\n\t\t\t\"Default\",\n\t\t\td.resource,\n\t\t\td.idFactory,\n\t\t\td.defaultFunction,\n\t\t\tastmodel.NewPackageReferenceSet(astmodel.GenRuntimeReference)),\n\t\tNewResourceFunction(\n\t\t\t\"defaultImpl\",\n\t\t\td.resource,\n\t\t\td.idFactory,\n\t\t\td.localDefault,\n\t\t\tastmodel.NewPackageReferenceSet(astmodel.GenRuntimeReference)),\n\t}\n\n\t// Add the actual individual default functions\n\tfor _, def := range d.defaults {\n\t\tfuncs = append(funcs, def)\n\t}\n\n\treturn astmodel.NewInterfaceImplementation(\n\t\tastmodel.DefaulterInterfaceName,\n\t\tfuncs...).WithAnnotation(annotation)\n}", "func cgounimpl() {\n\tthrow(\"cgo not implemented\")\n}", "func init() {\n\timports.Packages[\"github.com/cosmos72/gomacro/typeutil\"] = imports.Package{\n\t\tBinds: map[string]r.Value{\n\t\t\t\"Identical\": r.ValueOf(Identical),\n\t\t\t\"IdenticalIgnoreTags\": r.ValueOf(IdenticalIgnoreTags),\n\t\t\t\"MakeHasher\": r.ValueOf(MakeHasher),\n\t\t},\n\t\tTypes: map[string]r.Type{\n\t\t\t\"Hasher\": r.TypeOf((*Hasher)(nil)).Elem(),\n\t\t\t\"Map\": r.TypeOf((*Map)(nil)).Elem(),\n\t\t},\n\t\tProxies: map[string]r.Type{}}\n}", "func DoReplacements(input string, mapping MappingFunc) interface{} {\n\tvar buf strings.Builder\n\tcheckpoint := 0\n\tfor cursor := 0; cursor < len(input); cursor++ {\n\t\tif input[cursor] == operator && cursor+1 < len(input) {\n\t\t\t// Copy the portion of the input string since the last\n\t\t\t// checkpoint into the buffer\n\t\t\tbuf.WriteString(input[checkpoint:cursor])\n\n\t\t\t// Attempt to read the variable name as defined by the\n\t\t\t// syntax from the input string\n\t\t\tread, isVar, advance := tryReadVariableName(input[cursor+1:])\n\n\t\t\tif isVar {\n\t\t\t\t// We were able to read a variable name correctly;\n\t\t\t\t// apply the mapping to the variable name and copy the\n\t\t\t\t// bytes into the buffer\n\t\t\t\tmapped := mapping(read)\n\t\t\t\tif input == syntaxWrap(read) {\n\t\t\t\t\t// Preserve the type of variable\n\t\t\t\t\treturn mapped\n\t\t\t\t}\n\n\t\t\t\t// Variable is used in a middle of a string\n\t\t\t\tbuf.WriteString(fmt.Sprintf(\"%v\", mapped))\n\t\t\t} else {\n\t\t\t\t// Not a variable name; copy the read bytes into the buffer\n\t\t\t\tbuf.WriteString(read)\n\t\t\t}\n\n\t\t\t// Advance the cursor in the input string to account for\n\t\t\t// bytes consumed to read the variable name expression\n\t\t\tcursor += advance\n\n\t\t\t// Advance the checkpoint in the input string\n\t\t\tcheckpoint = cursor + 1\n\t\t}\n\t}\n\n\t// Return the buffer and any remaining unwritten bytes in the\n\t// input string.\n\treturn buf.String() + input[checkpoint:]\n}", "func dialectMsgDefToGo(in string) string {\n\tre := regexp.MustCompile(\"_[a-z]\")\n\tin = strings.ToLower(in)\n\tin = re.ReplaceAllStringFunc(in, func(match string) string {\n\t\treturn strings.ToUpper(match[1:2])\n\t})\n\treturn strings.ToUpper(in[:1]) + in[1:]\n}", "func si(vm *VM, argument string) {\n\tsco := &Scope{\n\t\tprevious: vm.Scope,\n\t}\n\tvm.Scope = sco\n}", "func (*bzlLibraryLang) Fix(c *config.Config, f *rule.File) {}", "func MergeInjections(inja ...Injections) (ret Injections) {\n\tret = make(Injections)\n\tfor _, is := range inja {\n\t\tfor it, io := range is {\n\t\t\tret[it] = io\n\t\t}\n\t}\n\treturn\n}", "func (b Container) SetupGlobalInjection(i interface{}) {\n\tt := reflect.TypeOf(i)\n\tb.globalInjections[t] = i\n\tb.Bindings().AddInjection(i) // Add Injection for all existing bindings.\n}", "func convertInitialisms(s string) string {\n\tfor i := 0; i < len(commonInitialisms); i++ {\n\t\ts = strings.ReplaceAll(s, commonInitialisms[i][1], commonInitialisms[i][0])\n\t}\n\treturn s\n}", "func init() {\n\tPackages[\"encoding/gob\"] = Package{\n\tBinds: map[string]Value{\n\t\t\"NewDecoder\":\tValueOf(gob.NewDecoder),\n\t\t\"NewEncoder\":\tValueOf(gob.NewEncoder),\n\t\t\"Register\":\tValueOf(gob.Register),\n\t\t\"RegisterName\":\tValueOf(gob.RegisterName),\n\t}, Types: map[string]Type{\n\t\t\"CommonType\":\tTypeOf((*gob.CommonType)(nil)).Elem(),\n\t\t\"Decoder\":\tTypeOf((*gob.Decoder)(nil)).Elem(),\n\t\t\"Encoder\":\tTypeOf((*gob.Encoder)(nil)).Elem(),\n\t\t\"GobDecoder\":\tTypeOf((*gob.GobDecoder)(nil)).Elem(),\n\t\t\"GobEncoder\":\tTypeOf((*gob.GobEncoder)(nil)).Elem(),\n\t}, Proxies: map[string]Type{\n\t\t\"GobDecoder\":\tTypeOf((*P_encoding_gob_GobDecoder)(nil)).Elem(),\n\t\t\"GobEncoder\":\tTypeOf((*P_encoding_gob_GobEncoder)(nil)).Elem(),\n\t}, \n\t}\n}", "func (db Db) ServiceDefinitionToOsb(sd map[string]interface{}) osb.Service {\n\t// TODO: Marshal spec straight from the yaml in an osb.Plan, possibly using gjson\n\tglog.Infof(\"converting service definition %q \", sd[\"name\"].(string))\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tglog.Errorln(errors.Wrap(r, 2).ErrorStack())\n\t\t\tglog.Errorf(\"Failed to convert service definition for %q\", sd[\"name\"].(string))\n\t\t}\n\t}()\n\tf := false\n\tserviceid := uuid.NewV5(db.Accountuuid, sd[\"name\"].(string)).String()\n\toutp := osb.Service{}\n\toutp.ID = serviceid\n\toutp.Name = sd[\"name\"].(string)\n\toutp.Bindable = sd[\"bindable\"].(bool)\n\toutp.Description = sd[\"description\"].(string)\n\toutp.PlanUpdatable = &f\n\tmetadata := make(map[string]interface{})\n\tfor index, key := range sd[\"metadata\"].(map[interface{}]interface{}) {\n\t\tmetadata[index.(string)] = key\n\t}\n\toutp.Metadata = metadata\n\tvar tags []string\n\tfor _, key := range sd[\"tags\"].([]interface{}) {\n\t\ttags = append(tags, key.(string))\n\t}\n\toutp.Tags = tags\n\tvar plans []osb.Plan\n\tfor _, key := range sd[\"plans\"].([]interface{}) {\n\t\tplan := osb.Plan{}\n\t\tfor i, k := range key.(map[interface{}]interface{}) {\n\t\t\tif i.(string) == \"name\" {\n\t\t\t\tplan.Name = k.(string)\n\t\t\t} else if i.(string) == \"description\" {\n\t\t\t\tplan.Description = k.(string)\n\t\t\t} else if i.(string) == \"free\" {\n\t\t\t\tfree := k.(bool)\n\t\t\t\tplan.Free = &free\n\t\t\t} else if i.(string) == \"metadata\" {\n\t\t\t\tmetadata := make(map[string]interface{})\n\t\t\t\tfor i2, k2 := range k.(map[interface{}]interface{}) {\n\t\t\t\t\tmetadata[i2.(string)] = k2\n\t\t\t\t}\n\t\t\t\tplan.Metadata = metadata\n\t\t\t} else if i.(string) == \"parameters\" {\n\t\t\t\tpropsForCreate := make(map[string]interface{})\n\t\t\t\trequiredForCreate := make([]string, 0)\n\t\t\t\tpropsForUpdate := make(map[string]interface{})\n\t\t\t\trequiredForUpdate := make([]string, 0)\n\t\t\t\tfor _, param := range k.([]interface{}) {\n\t\t\t\t\tvar name string\n\t\t\t\t\tvar required, updatable bool\n\t\t\t\t\tpvals := make(map[string]interface{})\n\t\t\t\t\tfor pk, pv := range param.(map[interface{}]interface{}) {\n\t\t\t\t\t\tswitch pk {\n\t\t\t\t\t\tcase \"name\":\n\t\t\t\t\t\t\tname = pv.(string)\n\t\t\t\t\t\tcase \"required\":\n\t\t\t\t\t\t\trequired = pv.(bool)\n\t\t\t\t\t\tcase \"type\":\n\t\t\t\t\t\t\tswitch pv {\n\t\t\t\t\t\t\tcase \"enum\":\n\t\t\t\t\t\t\t\tpvals[pk.(string)] = \"string\"\n\t\t\t\t\t\t\tcase \"int\":\n\t\t\t\t\t\t\t\tpvals[pk.(string)] = \"integer\"\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tpvals[pk.(string)] = pv\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"updatable\":\n\t\t\t\t\t\t\tupdatable = pv.(bool)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tpvals[pk.(string)] = pv\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpropsForCreate[name] = pvals\n\t\t\t\t\tif required {\n\t\t\t\t\t\trequiredForCreate = append(requiredForCreate, name)\n\t\t\t\t\t}\n\t\t\t\t\tif updatable {\n\t\t\t\t\t\tpropsForUpdate[name] = pvals\n\t\t\t\t\t\tif required {\n\t\t\t\t\t\t\trequiredForUpdate = append(requiredForUpdate, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tplan.Schemas = &osb.Schemas{\n\t\t\t\t\tServiceInstance: &osb.ServiceInstanceSchema{\n\t\t\t\t\t\tCreate: &osb.InputParametersSchema{\n\t\t\t\t\t\t\tParameters: map[string]interface{}{\n\t\t\t\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\t\t\t\"properties\": propsForCreate,\n\t\t\t\t\t\t\t\t\"$schema\": \"http://json-schema.org/draft-06/schema#\",\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\tif len(requiredForCreate) > 0 {\n\t\t\t\t\t// Cloud Foundry does not allow \"required\" to be an empty slice\n\t\t\t\t\tplan.Schemas.ServiceInstance.Create.Parameters.(map[string]interface{})[\"required\"] = requiredForCreate\n\t\t\t\t}\n\t\t\t\tif len(propsForUpdate) > 0 {\n\t\t\t\t\tplan.Schemas.ServiceInstance.Update = &osb.InputParametersSchema{\n\t\t\t\t\t\tParameters: map[string]interface{}{\n\t\t\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\t\t\"properties\": propsForUpdate,\n\t\t\t\t\t\t\t\"$schema\": \"http://json-schema.org/draft-06/schema#\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tif len(requiredForUpdate) > 0 {\n\t\t\t\t\t\t// Cloud Foundry does not allow \"required\" to be an empty slice\n\t\t\t\t\t\tplan.Schemas.ServiceInstance.Update.Parameters.(map[string]interface{})[\"required\"] = requiredForUpdate\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tplanid := uuid.NewV5(db.Accountuuid, \"service__\"+sd[\"name\"].(string)+\"__plan__\"+plan.Name).String()\n\t\tplan.ID = planid\n\t\tplans = append(plans, plan)\n\t}\n\toutp.Plans = plans\n\tglog.Infof(\"done converting service definition %q \", sd[\"name\"].(string))\n\treturn outp\n}", "func (self *Dependency) BindDep(controller Controller) {\n\tctrl := reflect.ValueOf(controller).Elem() //controllers are all pointer\n\tfor i := 0; i < ctrl.NumField(); i++ {\n\t\tf := ctrl.Field(i)\n\t\tif f.Kind() != reflect.Ptr || !f.IsNil() {\n\t\t\tcontinue\n\t\t}\n\t\tif p := self.GetDep(f.Type()); p != nil && f.CanInterface() {\n\t\t\tf.Set(reflect.New(f.Type().Elem()))\n\t\t\tf.Elem().Set(reflect.ValueOf(p).Elem())\n\t\t}\n\t}\n}", "func init() {\n\tPackages[\"fmt\"] = Package{\n\tBinds: map[string]Value{\n\t\t\"Errorf\":\tValueOf(fmt.Errorf),\n\t\t\"Fprint\":\tValueOf(fmt.Fprint),\n\t\t\"Fprintf\":\tValueOf(fmt.Fprintf),\n\t\t\"Fprintln\":\tValueOf(fmt.Fprintln),\n\t\t\"Fscan\":\tValueOf(fmt.Fscan),\n\t\t\"Fscanf\":\tValueOf(fmt.Fscanf),\n\t\t\"Fscanln\":\tValueOf(fmt.Fscanln),\n\t\t\"Print\":\tValueOf(fmt.Print),\n\t\t\"Printf\":\tValueOf(fmt.Printf),\n\t\t\"Println\":\tValueOf(fmt.Println),\n\t\t\"Scan\":\tValueOf(fmt.Scan),\n\t\t\"Scanf\":\tValueOf(fmt.Scanf),\n\t\t\"Scanln\":\tValueOf(fmt.Scanln),\n\t\t\"Sprint\":\tValueOf(fmt.Sprint),\n\t\t\"Sprintf\":\tValueOf(fmt.Sprintf),\n\t\t\"Sprintln\":\tValueOf(fmt.Sprintln),\n\t\t\"Sscan\":\tValueOf(fmt.Sscan),\n\t\t\"Sscanf\":\tValueOf(fmt.Sscanf),\n\t\t\"Sscanln\":\tValueOf(fmt.Sscanln),\n\t}, Types: map[string]Type{\n\t\t\"Formatter\":\tTypeOf((*fmt.Formatter)(nil)).Elem(),\n\t\t\"GoStringer\":\tTypeOf((*fmt.GoStringer)(nil)).Elem(),\n\t\t\"ScanState\":\tTypeOf((*fmt.ScanState)(nil)).Elem(),\n\t\t\"Scanner\":\tTypeOf((*fmt.Scanner)(nil)).Elem(),\n\t\t\"State\":\tTypeOf((*fmt.State)(nil)).Elem(),\n\t\t\"Stringer\":\tTypeOf((*fmt.Stringer)(nil)).Elem(),\n\t}, Proxies: map[string]Type{\n\t\t\"Formatter\":\tTypeOf((*P_fmt_Formatter)(nil)).Elem(),\n\t\t\"GoStringer\":\tTypeOf((*P_fmt_GoStringer)(nil)).Elem(),\n\t\t\"ScanState\":\tTypeOf((*P_fmt_ScanState)(nil)).Elem(),\n\t\t\"Scanner\":\tTypeOf((*P_fmt_Scanner)(nil)).Elem(),\n\t\t\"State\":\tTypeOf((*P_fmt_State)(nil)).Elem(),\n\t\t\"Stringer\":\tTypeOf((*P_fmt_Stringer)(nil)).Elem(),\n\t}, \n\t}\n}", "func Uninject(opts *options.Options, optionsFunc ...cliutils.OptionsFunc) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"uninject\",\n\t\tShort: \"Remove SDS & istio-proxy sidecars from gateway-proxy pod\",\n\t\tLong: \"Removes the istio-proxy sidecar from the gateway-proxy pod. \" +\n\t\t\t\"Also removes the sds sidecar from the gateway-proxy pod. \" +\n\t\t\t\"Also removes the gateway_proxy_sds cluster from the gateway-proxy envoy bootstrap ConfigMap.\",\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := istioUninject(args, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcliutils.ApplyOptions(cmd, optionsFunc)\n\treturn cmd\n}", "func (self *Rectangle) InflateI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"inflate\", args)}\n}", "func demangle(s string) string {\n\tvar correct strings.Builder\n\n\t// copy s into correct, using lookahead to rewrite letters\n\tvar i int\n\tfor i = 0; i < len(s)-1; i++ {\n\t\tc := s[i]\n\t\tif c == '!' {\n\t\t\tnext := s[i+1]\n\t\t\tif next >= 'a' && next <= 'z' {\n\t\t\t\tcorrect.WriteByte(next - ('a' - 'A'))\n\t\t\t\ti++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tcorrect.WriteByte(c)\n\t}\n\n\t// if the last 2 letters were not an encoding, copy the last letter\n\tif i == len(s)-1 {\n\t\tcorrect.WriteByte(s[i])\n\t}\n\n\treturn correct.String()\n}", "func returnGoSubServiceSvcDefinition(name string, hasDB bool) (string, error) {\n\t// service types\n\tsrvcDefinitionString := fmt.Sprintf(\"\\n\\n // New%s loads related SQL statements and initializes the container struct\\n\", strings.Title(name)+\"Service\") +\n\t\tfmt.Sprintf(\"func New%s(s *Services) %s {\\n\", strings.Title(name)+\"Service\", strings.Title(name)+\"Service\")\n\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\t// create initial interface \\n\") +\n\t\t\tfmt.Sprintf(\"\tctx := &db.%s{}\\n\", strings.Title(name)+\"StructDB\") +\n\t\t\tfmt.Sprintf(\"\tctx.DB = s.db \\n\")\n\t}\n\n\tsrvcDefinitionString += fmt.Sprintf(\"\tsrvc := &%s{}\\n\", strings.ToLower(name)+\"Service\")\n\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\tsrvc.I%s = &validation.%s{I%s: ctx}\\n\", strings.Title(name)+\"DB\", strings.Title(name)+\"Validator\", strings.Title(name)+\"DB\")\n\t}\n\tsrvcDefinitionString += fmt.Sprintf(\"\treturn srvc\\n }\\n\\n\") +\n\t\t// interface type\n\t\tfmt.Sprintf(\"// %s is a wrapper for related components\\n\", strings.Title(name)+\"Services\") +\n\t\tfmt.Sprintf(\"type %s interface {\\n\", strings.Title(name)+\"Service\")\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\tdb.I%s\\n\", strings.Title(name)+\"DB\")\n\t}\n\tsrvcDefinitionString += fmt.Sprintf(\"}\\n\\n\") +\n\t\t// struct type\n\t\tfmt.Sprintf(\"type %s struct {\\n\", strings.ToLower(name)+\"Service\")\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\tdb.I%s\\n\", strings.Title(name)+\"DB\")\n\t}\n\tsrvcDefinitionString += fmt.Sprintf(\"}\\n\")\n\n\treturn srvcDefinitionString, nil\n}", "func DI() proto.RoomServicesServer {\n\tiulidGenerator := util.NewULIDGenerator()\n\tiFactory := room.NewFactory(iulidGenerator)\n\tdb := mysql.ConnectGorm()\n\tiRepository := room2.NewRepositoryImpl(db)\n\tiDomainService := room3.NewDomainService(iRepository)\n\tiInputPort := room4.NewInteractor(iFactory, iRepository, iDomainService)\n\troomIInputPort := room5.NewInteractor(iRepository)\n\tclient := redis.NewClient()\n\tmessageIRepository := message.NewRepositoryImpl(db, client)\n\tmessageIInputPort := message2.NewInteractor(messageIRepository)\n\tmessageIFactory := message3.NewFactory(iulidGenerator)\n\tiInputPort2 := room6.NewInteractor(messageIFactory, messageIRepository, iRepository)\n\troomServicesServer := room7.NewController(iInputPort, roomIInputPort, messageIInputPort, iInputPort2)\n\treturn roomServicesServer\n}", "func InjectGraphQLService(\n\truntime env.Runtime,\n\tprefix provider.LogPrefix,\n\tlogLevel logger.LogLevel,\n\tsqlDB *sql.DB,\n\tgraphqlPath provider.GraphQLPath,\n\tsecret provider.ReCaptchaSecret,\n\tjwtSecret provider.JwtSecret,\n\tbufferSize provider.KeyGenBufferSize,\n\tkgsRPCConfig provider.KgsRPCConfig,\n\ttokenValidDuration provider.TokenValidDuration,\n\tdataDogAPIKey provider.DataDogAPIKey,\n\tsegmentAPIKey provider.SegmentAPIKey,\n\tipStackAPIKey provider.IPStackAPIKey,\n\tgoogleAPIKey provider.GoogleAPIKey,\n) (service.GraphQL, error) {\n\twire.Build(\n\t\twire.Bind(new(timer.Timer), new(timer.System)),\n\t\twire.Bind(new(graphql.API), new(gqlapi.Short)),\n\t\twire.Bind(new(graphql.Handler), new(graphql.GraphGopherHandler)),\n\n\t\twire.Bind(new(risk.BlackList), new(google.SafeBrowsing)),\n\t\twire.Bind(new(repository.UserURLRelation), new(sqldb.UserURLRelationSQL)),\n\t\twire.Bind(new(repository.ChangeLog), new(sqldb.ChangeLogSQL)),\n\t\twire.Bind(new(repository.URL), new(*sqldb.URLSql)),\n\n\t\twire.Bind(new(changelog.ChangeLog), new(changelog.Persist)),\n\t\twire.Bind(new(url.Retriever), new(url.RetrieverPersist)),\n\t\twire.Bind(new(url.Creator), new(url.CreatorPersist)),\n\n\t\tobservabilitySet,\n\t\tauthSet,\n\t\tkeyGenSet,\n\n\t\tenv.NewDeployment,\n\t\tprovider.NewGraphQLService,\n\t\tgraphql.NewGraphGopherHandler,\n\t\twebreq.NewHTTPClient,\n\t\twebreq.NewHTTP,\n\t\ttimer.NewSystem,\n\n\t\tgqlapi.NewShort,\n\t\tprovider.NewSafeBrowsing,\n\t\trisk.NewDetector,\n\t\tprovider.NewReCaptchaService,\n\t\tsqldb.NewChangeLogSQL,\n\t\tsqldb.NewURLSql,\n\t\tsqldb.NewUserURLRelationSQL,\n\n\t\tvalidator.NewLongLink,\n\t\tvalidator.NewCustomAlias,\n\t\tchangelog.NewPersist,\n\t\turl.NewRetrieverPersist,\n\t\turl.NewCreatorPersist,\n\t\trequester.NewVerifier,\n\t)\n\treturn service.GraphQL{}, nil\n}", "func TempDI(name string) (di DI, clean func(), err error) {\n\thdir, err := homedir.Dir()\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to determine homedir\")\n\t}\n\n\tkcfg, err := clientcmd.BuildConfigFromFlags(\"\", filepath.Join(hdir, \".kube\", \"config\"))\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to build config form kube config\")\n\t}\n\n\tif !strings.Contains(fmt.Sprintf(\"%#v\", kcfg), \"minikube\") {\n\t\treturn nil, nil, ErrMinikubeOnly\n\t}\n\n\tval := validator.New()\n\tval.RegisterValidation(\"is-abs-path\", ValidateAbsPath)\n\n\ttdi := &tmpDI{\n\t\tlogs: logrus.New(),\n\t\tval: val,\n\t}\n\n\ttdi.kube, err = kubernetes.NewForConfig(kcfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create kube client from config\")\n\t}\n\n\ttdi.crd, err = crd.NewForConfig(kcfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create CRD client from config\")\n\t}\n\n\tif name == \"\" {\n\t\td := make([]byte, 16)\n\t\t_, err = rand.Read(d)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"failed to read random bytes\")\n\t\t}\n\n\t\tname = hex.EncodeToString(d)\n\t}\n\n\tns, err := tdi.kube.CoreV1().Namespaces().Create(&v1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{GenerateName: name},\n\t})\n\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create temporary namespace\")\n\t}\n\n\ttdi.ns = ns.GetName()\n\treturn tdi, func() {\n\t\terr := tdi.kube.CoreV1().Namespaces().Delete(ns.Name, nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}, nil\n}", "func UserTypeUnmarshalerImpl(u *design.UserTypeDefinition, versioned bool, defaultPkg, context string) string {\n\tvar required []string\n\tfor _, v := range u.Validations {\n\t\tif r, ok := v.(*design.RequiredValidationDefinition); ok {\n\t\t\trequired = r.Names\n\t\t\tbreak\n\t\t}\n\t}\n\tvar impl string\n\tswitch {\n\tcase u.IsObject():\n\t\timpl = objectUnmarshalerR(u, required, versioned, defaultPkg, context, \"source\", \"target\", 1)\n\tcase u.IsArray():\n\t\timpl = arrayUnmarshalerR(u.ToArray(), versioned, defaultPkg, context, \"source\", \"target\", 1)\n\tcase u.IsHash():\n\t\timpl = hashUnmarshalerR(u.ToHash(), versioned, defaultPkg, context, \"source\", \"target\", 1)\n\tdefault:\n\t\treturn \"\" // No function for primitive types - they just get casted\n\t}\n\tdata := map[string]interface{}{\n\t\t\"Name\": userTypeUnmarshalerFuncName(u),\n\t\t\"Type\": u,\n\t\t\"Impl\": impl,\n\t}\n\treturn RunTemplate(unmUserImplT, data)\n}", "func godef(ds design.DataStructure, versioned bool, defPkg string, tabs int, jsonTags, inner, res bool) string {\n\tvar buffer bytes.Buffer\n\tdef := ds.Definition()\n\tt := def.Type\n\tswitch actual := t.(type) {\n\tcase design.Primitive:\n\t\treturn GoTypeName(t, tabs)\n\tcase *design.Array:\n\t\treturn \"[]\" + godef(actual.ElemType, versioned, defPkg, tabs, jsonTags, true, res)\n\tcase *design.Hash:\n\t\tkeyDef := godef(actual.KeyType, versioned, defPkg, tabs, jsonTags, true, res)\n\t\telemDef := godef(actual.ElemType, versioned, defPkg, tabs, jsonTags, true, res)\n\t\treturn fmt.Sprintf(\"map[%s]%s\", keyDef, elemDef)\n\tcase design.Object:\n\t\tif inner {\n\t\t\tbuffer.WriteByte('*')\n\t\t}\n\t\tbuffer.WriteString(\"struct {\\n\")\n\t\tkeys := make([]string, len(actual))\n\t\ti := 0\n\t\tfor n := range actual {\n\t\t\tkeys[i] = n\n\t\t\ti++\n\t\t}\n\t\tsort.Strings(keys)\n\t\tfor _, name := range keys {\n\t\t\tWriteTabs(&buffer, tabs+1)\n\t\t\ttypedef := godef(actual[name], versioned, defPkg, tabs+1, jsonTags, true, res)\n\t\t\tfname := Goify(name, true)\n\t\t\tvar tags string\n\t\t\tif jsonTags {\n\t\t\t\tvar omit string\n\t\t\t\tif !def.IsRequired(name) {\n\t\t\t\t\tomit = \",omitempty\"\n\t\t\t\t}\n\t\t\t\ttags = fmt.Sprintf(\" `json:\\\"%s%s\\\"`\", name, omit)\n\t\t\t}\n\t\t\tdesc := actual[name].Description\n\t\t\tif desc != \"\" {\n\t\t\t\tdesc = fmt.Sprintf(\"// %s\\n\", desc)\n\t\t\t}\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"%s%s %s%s\\n\", desc, fname, typedef, tags))\n\t\t}\n\t\tWriteTabs(&buffer, tabs)\n\t\tbuffer.WriteString(\"}\")\n\t\treturn buffer.String()\n\tcase *design.UserTypeDefinition:\n\t\tname := GoPackageTypeName(actual, versioned, defPkg, tabs)\n\t\tif actual.Type.IsObject() {\n\t\t\treturn \"*\" + name\n\t\t}\n\t\treturn name\n\tcase *design.MediaTypeDefinition:\n\t\tif res && actual.Resource != nil {\n\t\t\treturn \"*\" + Goify(actual.Resource.Name, true)\n\t\t}\n\t\tname := GoPackageTypeName(actual, versioned, defPkg, tabs)\n\t\tif actual.Type.IsObject() {\n\t\t\treturn \"*\" + name\n\t\t}\n\t\treturn name\n\tdefault:\n\t\tpanic(\"goa bug: unknown data structure type\")\n\t}\n}", "func sf(vm *VM, argument string) {\n\tsco := vm.Scope\n\tif sco == nil || sco.previous == nil {\n\t\tvm.err = ErrorScopeMin\n\t\treturn\n\t}\n\tvm.Scope = sco.previous\n\tfor name, variable := range sco.variables {\n\t\tvm.scopeResolve(name, func(scope *Scope) {\n\t\t\tscope.variables[name] = variable\n\t\t})\n\t}\n}", "func (app AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func NoopTranslator() Translator { return noopTranslator }", "func CovertSwaggerMethordToLocalMethord(schema *registry.SchemaContent, src *registry.MethodInfo, dst *DefMethod) {\n\tdst.OperaID = src.OperationID\n\ttmpParas := make([]MethParam, len(src.Parameters))\n\ti := 0\n\tfor _, para := range src.Parameters {\n\t\tvar defPara MethParam\n\t\tdefPara.Name = para.Name\n\t\tif para.Type == \"\" {\n\t\t\tif para.Schema.Type != \"\" {\n\t\t\t\tdefPara.Dtype = para.Schema.Type\n\t\t\t} else {\n\t\t\t\tdefPara.Dtype = \"object\"\n\t\t\t\tif para.Schema.Reference != \"\" {\n\t\t\t\t\tdefPara.ObjRef = GetDefTypeFromDef(schema.Definition, para.Schema.Reference)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tdefPara.Dtype = para.Type\n\t\t}\n\t\tdefPara.Required = para.Required\n\t\tdefPara.Where = para.In\n\t\tdefPara.Indx = i\n\t\ttmpParas[i] = defPara\n\t\ti++\n\t}\n\tdst.Paras = tmpParas\n\ttmpRsps := make(map[string]*MethRespond)\n\tfor key, rsp := range src.Response {\n\t\tvar defRsp MethRespond\n\t\tif dtype, ok := rsp.Schema[\"type\"]; ok {\n\t\t\tdefRsp.DType = dtype\n\t\t} else {\n\t\t\tdefRsp.DType = \"object\"\n\t\t\tif dRef, ok := rsp.Schema[\"$ref\"]; ok {\n\t\t\t\tdefRsp.ObjRef = GetDefTypeFromDef(schema.Definition, dRef)\n\t\t\t}\n\t\t}\n\t\tdefRsp.Status = key\n\t\ttmpRsps[key] = &defRsp\n\t}\n\tdst.Responds = tmpRsps\n}", "func init() {\n\ttransformCmd.AddCommand(replaceCmd)\n}", "func _() {\n\tX(Interface[*F /* ERROR got 1 arguments but 2 type parameters */ [string]](Impl{}))\n}", "func definition(s selection, args []string) {\n\tvar gd serial.Definition\n\tjs := runWithStdin(s.archive(), \"guru\", \"-json\", \"-modified\", \"definition\", s.pos())\n\tif err := json.Unmarshal([]byte(js), &gd); err != nil {\n\t\tlog.Fatalf(\"failed to unmarshal guru json: %v\\n\", err)\n\t}\n\tif err := plumbText(gd.ObjPos); err != nil {\n\t\tfmt.Println(gd.ObjPos)\n\t\tlog.Fatalf(\"failed to plumb: %v\\n\", err)\n\t}\n}", "func initTagConversionMap() {\n\n\tTagStrToInt[\"bos\"] = 0\n\tTagStrToInt[\"$\"] = 1\n\tTagStrToInt[\"\\\"\"] = 2\n\tTagStrToInt[\"(\"] = 3\n\tTagStrToInt[\")\"] = 4\n\tTagStrToInt[\",\"] = 5\n\tTagStrToInt[\"--\"] = 6\n\tTagStrToInt[\".\"] = 7\n\tTagStrToInt[\":\"] = 8\n\tTagStrToInt[\"cc\"] = 9\n\tTagStrToInt[\"cd\"] = 10\n\tTagStrToInt[\"dt\"] = 11\n\tTagStrToInt[\"fw\"] = 12\n\tTagStrToInt[\"jj\"] = 13\n\tTagStrToInt[\"ls\"] = 14\n\tTagStrToInt[\"nn\"] = 15\n\tTagStrToInt[\"np\"] = 16\n\tTagStrToInt[\"pos\"] = 17\n\tTagStrToInt[\"pr\"] = 18\n\tTagStrToInt[\"rb\"] = 19\n\tTagStrToInt[\"sym\"] = 20\n\tTagStrToInt[\"to\"] = 21\n\tTagStrToInt[\"uh\"] = 22\n\tTagStrToInt[\"vb\"] = 23\n\tTagStrToInt[\"md\"] = 24\n\tTagStrToInt[\"in\"] = 25\n\n\tTagIntToStr[0] = \"bos\"\n\tTagIntToStr[1] = \"$\"\n\tTagIntToStr[2] = \"\\\"\"\n\tTagIntToStr[3] = \"(\"\n\tTagIntToStr[4] = \")\"\n\tTagIntToStr[5] = \",\"\n\tTagIntToStr[6] = \"--\"\n\tTagIntToStr[7] = \".\"\n\tTagIntToStr[8] = \":\"\n\tTagIntToStr[9] = \"cc\"\n\tTagIntToStr[10] = \"cd\"\n\tTagIntToStr[11] = \"dt\"\n\tTagIntToStr[12] = \"fw\"\n\tTagIntToStr[13] = \"jj\"\n\tTagIntToStr[14] = \"ls\"\n\tTagIntToStr[15] = \"nn\"\n\tTagIntToStr[16] = \"np\"\n\tTagIntToStr[17] = \"pos\"\n\tTagIntToStr[18] = \"pr\"\n\tTagIntToStr[19] = \"rb\"\n\tTagIntToStr[20] = \"sym\"\n\tTagIntToStr[21] = \"to\"\n\tTagIntToStr[22] = \"uh\"\n\tTagIntToStr[23] = \"vb\"\n\tTagIntToStr[24] = \"md\"\n\tTagIntToStr[25] = \"in\"\n}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func Replacer(old, new string) NameMapper {\n\treturn func(s string) string {\n\t\treturn strings.ReplaceAll(s, old, new)\n\t}\n}", "func (s *BaseSyslParserListener) EnterFacade(ctx *FacadeContext) {}", "func (a *Client) ReplaceBind(params *ReplaceBindParams, authInfo runtime.ClientAuthInfoWriter) (*ReplaceBindOK, *ReplaceBindAccepted, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewReplaceBindParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"replaceBind\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/services/haproxy/configuration/binds/{name}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ReplaceBindReader{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, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *ReplaceBindOK:\n\t\treturn value, nil, nil\n\tcase *ReplaceBindAccepted:\n\t\treturn nil, value, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ReplaceBindDefault)\n\treturn nil, nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func ZopfliDeflate(d policies.DEFLATE,data []byte) []byte {\n\tbuf := new(bytes.Buffer)\n\to := zopfli.DefaultOptions()\n\to.NumIterations = 15\n\to.BlockSplittingLast = true\n\to.BlockType = 2\n\tdef := zopfli.NewDeflator(buf,&o)\n\tdef.Deflate(true,data)\n\treturn buf.Bytes()\n}", "func initApiScope(scope *apiScope) *apiScope {\n\tname := scope.name\n\tscopeByName[name] = scope\n\tallScopeNames = append(allScopeNames, name)\n\tscope.propertyName = strings.ReplaceAll(name, \"-\", \"_\")\n\tscope.fieldName = proptools.FieldNameForProperty(scope.propertyName)\n\tscope.stubsTag = scopeDependencyTag{\n\t\tname: name + \"-stubs\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractStubsLibraryInfoFromDependency,\n\t}\n\tscope.stubsSourceTag = scopeDependencyTag{\n\t\tname: name + \"-stubs-source\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractStubsSourceInfoFromDep,\n\t}\n\tscope.apiFileTag = scopeDependencyTag{\n\t\tname: name + \"-api\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractApiInfoFromDep,\n\t}\n\tscope.stubsSourceAndApiTag = scopeDependencyTag{\n\t\tname: name + \"-stubs-source-and-api\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractStubsSourceAndApiInfoFromApiStubsProvider,\n\t}\n\n\t// To get the args needed to generate the stubs source append all the args from\n\t// this scope and all the scopes it extends as each set of args adds additional\n\t// members to the stubs.\n\tvar scopeSpecificArgs []string\n\tif scope.annotation != \"\" {\n\t\tscopeSpecificArgs = []string{\"--show-annotation\", scope.annotation}\n\t}\n\tfor s := scope; s != nil; s = s.extends {\n\t\tscopeSpecificArgs = append(scopeSpecificArgs, s.extraArgs...)\n\n\t\t// Ensure that the generated stubs includes all the API elements from the API scope\n\t\t// that this scope extends.\n\t\tif s != scope && s.annotation != \"\" {\n\t\t\tscopeSpecificArgs = append(scopeSpecificArgs, \"--show-for-stub-purposes-annotation\", s.annotation)\n\t\t}\n\t}\n\n\t// Escape any special characters in the arguments. This is needed because droidstubs\n\t// passes these directly to the shell command.\n\tscope.droidstubsArgs = proptools.ShellEscapeList(scopeSpecificArgs)\n\n\treturn scope\n}", "func (injector *InterfaceImplementationInjector) Inject(\n\tdef TypeDefinition, implementations ...*InterfaceImplementation) (TypeDefinition, error) {\n\tresult := def\n\n\tfor _, impl := range implementations {\n\t\tvar err error\n\t\tresult, err = injector.visitor.VisitDefinition(result, impl)\n\t\tif err != nil {\n\t\t\treturn TypeDefinition{}, err\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (self *PhysicsP2) CreateRotationalSpringI(args ...interface{}) *PhysicsP2RotationalSpring{\n return &PhysicsP2RotationalSpring{self.Object.Call(\"createRotationalSpring\", args)}\n}", "func (g *Generator) Fgenerate(w io.Writer) {\n\ttpkg := templateBuilder(\"package\", `package {{ .Package }}{{\"\\n\\n\"}}`)\n\n\ttimp := templateBuilder(\"imports\", `import {{ if eq (len .Imports) 1 }}\"{{ index .Imports 0 }}\"{{else}}(\n{{ range .Imports }}{{\"\\t\"}}\"{{ . }}\"\n{{ end }}){{ end }}{{\"\\n\\n\"}}`)\n\n\tttyp := templateBuilder(\"type\", `type {{ .Opts.Type }} struct{{\"{\"}}\n{{- if gt (len .Deps) 0 -}}{{ \"\\n\" }}\n {{- range .Deps -}}\n {{- \"\\t\" }}{{ .Name }} {{ .Type -}}{{ \"\\n\" }}\n {{- end -}}\n{{- end -}}\n}{{\"\\n\\n\"}}`)\n\n\ttdep := templateBuilder(\"deps\", `{{- $cname := .Opts.Name -}}\n{{- $ctype := .Opts.Type -}}\n{{- range .Deps -}}\nfunc ({{ $cname }} *{{ $ctype }}) New{{ .Name | ucfirst }}() {{ .Type }} {{ .Func }}{{ \"\\n\\n\" }}\nfunc ({{ $cname }} *{{ $ctype }}) {{ .Name | ucfirst }}() {{ .Type }} {\n{{ \"\\t\" }}if {{ $cname }}.{{ .Name | lcfirst }} == nil {\n{{ \"\\t\\t\" }}{{ $cname }}.{{ .Name | lcfirst }} = {{ $cname }}.New{{ .Name | ucfirst }}()\n{{ \"\\t\" }}}\n{{ \"\\t\" }}return {{ $cname }}.{{ .Name | lcfirst }}\n}{{ \"\\n\\n\" }}\n{{- end -}}`)\n\n\terr := tpkg.Execute(w, g.opts)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(g.opts.Imports) > 0 {\n\t\terr = timp.Execute(w, g.opts)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tgWithPublicFields := struct {\n\t\tOpts opts\n\t\tDeps []dep\n\t}{\n\t\tg.opts,\n\t\tg.deps,\n\t}\n\n\terr = ttyp.Execute(w, gWithPublicFields)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(g.deps) > 0 {\n\t\terr = tdep.Execute(w, gWithPublicFields)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (mdr *Modder) ReplaceDependency(m *Module) error {\n\t// Don't add the root module to the dependencies\n\tif mdr.module.Module == m.Module {\n\t\treturn nil\n\t}\n\t// save module to depsMap, that's it? (yes)\n\tmdr.depsMap[m.Module] = m\n\n\treturn nil\n}", "func (cli *CLI) hookBeforeCall(cc *Arg) {\n\tcli.loadDataSyntax(cc)\n\tcli.loadScriptSyntax(cc)\n}", "func main() {\n\t// initialize the app with custom registered objects in the injection container\n\tc := clif.New(\"My App\", \"1.0.0\", \"An example application\").\n\t\tRegister(&exampleStruct{\"bar1\"}).\n\t\tRegisterAs(reflect.TypeOf((*exampleInterface)(nil)).Elem().String(), &exampleStruct{\"bar2\"}).\n\t\tNew(\"hello\", \"The obligatory hello world\", callHello)\n\n\t// extend output styles\n\tclif.DefaultStyles[\"mine\"] = \"\\033[32;1m\"\n\n\t// customize error handler\n\tclif.Die = func(msg string, args ...interface{}) {\n\t\tc.Output().Printf(\"<error>Everyting went wrong: %s<reset>\\n\\n\", fmt.Sprintf(msg, args...))\n\t\tos.Exit(1)\n\t}\n\n\t// build & add a complex command\n\tcmd := clif.NewCommand(\"foo\", \"It does foo\", callFoo).\n\t\tNewArgument(\"name\", \"Name for greeting\", \"\", true, false).\n\t\tNewArgument(\"more-names\", \"And more names for greeting\", \"\", false, true).\n\t\tNewOption(\"whatever\", \"w\", \"Some required option\", \"\", true, false)\n\tcnt := clif.NewOption(\"counter\", \"c\", \"Show how high you can count\", \"\", false, false)\n\tcnt.SetValidator(clif.IsInt)\n\tcmd.AddOption(cnt)\n\tc.Add(cmd)\n\n\tcb := func(c *clif.Command, out clif.Output) {\n\t\tout.Printf(\"Called %s\\n\", c.Name)\n\t}\n\tc.New(\"bar:baz\", \"A grouped command\", cb).\n\t\tNew(\"bar:zoing\", \"Another grouped command\", cb).\n\t\tNew(\"hmm:huh\", \"Yet another grouped command\", cb).\n\t\tNew(\"hmm:uhm\", \"And yet another grouped command\", cb)\n\n\t// execute the main loop\n\tc.Run()\n}", "func (c *Converter) convertDefinition(decl *nast.Definition, visitType int) error {\n\tif visitType == ast.PreVisit {\n\t\tc.setDefinition(decl.Name, decl)\n\t\treturn ast.NewNodeReplacement()\n\t}\n\treturn nil\n}", "func AddDefaultRefactorings() {\n\tAddRefactoring(\"rename\", new(refactoring.Rename))\n\tAddRefactoring(\"extract\", new(refactoring.ExtractFunc))\n\tAddRefactoring(\"var\", new(refactoring.ExtractLocal))\n\tAddRefactoring(\"toggle\", new(refactoring.ToggleVar))\n\tAddRefactoring(\"godoc\", new(refactoring.AddGoDoc))\n\tAddRefactoring(\"debug\", new(refactoring.Debug))\n\tAddRefactoring(\"null\", new(refactoring.Null))\n}", "func (s *BaseCobol85PreprocessorListener) EnterReplacement(ctx *ReplacementContext) {}", "func OnDelString(stringID string) {\n\tundeclareServicesOfString(stringID)\n}", "func FromOracle(layout string) string {\n\treturn oracleStringReplacer.Replace(strings.ToUpper(layout))\n}", "func (c *Converter) setDefinition(name string, val *nast.Definition) {\n\tname = strings.ToLower(name)\n\tc.definitions[name] = val\n}", "func Init() {\n\tfmt.Println(\"Loading sanitizer...\")\n\treplacer = *strings.NewReplacer(append(confusables, diacritics...)...)\n\tfmt.Printf(\"Loaded %d confusables and %d diacritics\\n\", len(confusables)/2, len(diacritics)/2)\n}", "func injectNameSpace(namespace string) mf.Transformer {\n\treturn func(u *unstructured.Unstructured) error {\n\t\tkind := u.GetKind()\n\t\tif kind == \"Role\" || kind == \"RoleBinding\" {\n\t\t\tu.SetNamespace(namespace)\n\t\t}\n\t\treturn nil\n\t}\n}", "func newBinder(chart *chart.Chart, cmIface v1.ConfigMapInterface) (mode.Binder, error) {\n\t// parse the values file for steward-specific config map info\n\tcmNames, err := getStewardConfigMapInfo(chart.Values)\n\tif err != nil {\n\t\tlogger.Errorf(\"getting steward config map info (%s)\", err)\n\t\treturn nil, err\n\t}\n\tlogger.Debugf(\"got config map names for helm chart %s\", cmNames)\n\treturn binder{\n\t\tcmNames: cmNames,\n\t\tcmIface: cmIface,\n\t}, nil\n}", "func (l *Libvirt) InterfaceUndefine(Iface Interface) (err error) {\n\tvar buf []byte\n\n\targs := InterfaceUndefineArgs {\n\t\tIface: Iface,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(132, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func defangIPaddr(address string) string {\n\treturn strings.Replace(address, \".\", \"[.]\", -1)\n}", "func (b binding) resolve(c Container) (interface{}, error) {\n\tif b.instance != nil {\n\t\treturn b.instance, nil\n\t}\n\n\treturn c.invoke(b.resolver)\n}", "func BindToFS(w common.WellFormedName) (fs string) {\n\t// Initialize the output with the CPE v2.3 string prefix.\n\tfs = \"cpe:2.3:\"\n\tattributes := []string{\"part\", \"vendor\", \"product\", \"version\",\n\t\t\"update\", \"edition\", \"language\", \"sw_edition\", \"target_sw\",\n\t\t\"target_hw\", \"other\"}\n\tfor _, a := range attributes {\n\t\tv := bindValueForFS(w.Get(a))\n\t\tfs += v\n\t\tif a != common.AttributeOther {\n\t\t\tfs += \":\"\n\t\t}\n\t}\n\treturn fs\n}", "func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (self *PhysicsP2) RemoveSpringI(args ...interface{}) *PhysicsP2Spring{\n return &PhysicsP2Spring{self.Object.Call(\"removeSpring\", args)}\n}", "func libNameByConvention(nc namingConvention, imp string, pkgName string) string {\n\tif nc == goDefaultLibraryNamingConvention {\n\t\treturn defaultLibName\n\t}\n\tname := libNameFromImportPath(imp)\n\tisCommand := pkgName == \"main\"\n\tif name == \"\" {\n\t\tif isCommand {\n\t\t\tname = \"lib\"\n\t\t} else {\n\t\t\tname = pkgName\n\t\t}\n\t} else if isCommand {\n\t\tname += \"_lib\"\n\t}\n\treturn name\n}", "func (b Binding) addGlobalInjections() {\n\tfor _, v := range b.base().container.globalInjections {\n\t\tb.AddInjection(v)\n\t}\n}", "func InjectRoutingService(\n\truntime env.Runtime,\n\tprefix provider.LogPrefix,\n\tlogLevel logger.LogLevel,\n\tsqlDB *sql.DB,\n\tgithubClientID provider.GithubClientID,\n\tgithubClientSecret provider.GithubClientSecret,\n\tfacebookClientID provider.FacebookClientID,\n\tfacebookClientSecret provider.FacebookClientSecret,\n\tfacebookRedirectURI provider.FacebookRedirectURI,\n\tgoogleClientID provider.GoogleClientID,\n\tgoogleClientSecret provider.GoogleClientSecret,\n\tgoogleRedirectURI provider.GoogleRedirectURI,\n\tjwtSecret provider.JwtSecret,\n\tbufferSize provider.KeyGenBufferSize,\n\tkgsRPCConfig provider.KgsRPCConfig,\n\twebFrontendURL provider.WebFrontendURL,\n\ttokenValidDuration provider.TokenValidDuration,\n\tdataDogAPIKey provider.DataDogAPIKey,\n\tsegmentAPIKey provider.SegmentAPIKey,\n\tipStackAPIKey provider.IPStackAPIKey,\n) (service.Routing, error) {\n\twire.Build(\n\t\twire.Bind(new(timer.Timer), new(timer.System)),\n\t\twire.Bind(new(geo.Geo), new(geo.IPStack)),\n\n\t\twire.Bind(new(url.Retriever), new(url.RetrieverPersist)),\n\t\twire.Bind(new(repository.UserURLRelation), new(sqldb.UserURLRelationSQL)),\n\t\twire.Bind(new(repository.User), new(*sqldb.UserSQL)),\n\t\twire.Bind(new(repository.URL), new(*sqldb.URLSql)),\n\n\t\tobservabilitySet,\n\t\tauthSet,\n\t\tgithubAPISet,\n\t\tfacebookAPISet,\n\t\tgoogleAPISet,\n\t\tkeyGenSet,\n\t\tfeatureDecisionSet,\n\n\t\tservice.NewRouting,\n\t\twebreq.NewHTTPClient,\n\t\twebreq.NewHTTP,\n\t\tgraphql.NewClientFactory,\n\t\ttimer.NewSystem,\n\t\tprovider.NewIPStack,\n\t\tenv.NewDeployment,\n\n\t\tsqldb.NewUserSQL,\n\t\tsqldb.NewURLSql,\n\t\tsqldb.NewUserURLRelationSQL,\n\t\turl.NewRetrieverPersist,\n\t\taccount.NewProvider,\n\t\tprovider.NewShortRoutes,\n\t)\n\treturn service.Routing{}, nil\n}", "func camelizeDown(s string) string {\n\tif s == \"ID\" {\n\t\treturn \"id\"\n\t\t// note: not sure why I need this, there's a lot that deals with\n\t\t// accronyms in the dependency packages but they don't seem to behave\n\t\t// as expected in this case.\n\t}\n\treturn defaultRuleset.CamelizeDownFirst(s)\n}", "func toGobDiagnostic(posToLocation func(start, end token.Pos) (protocol.Location, error), a *analysis.Analyzer, diag analysis.Diagnostic) (gobDiagnostic, error) {\n\tvar fixes []gobSuggestedFix\n\tfor _, fix := range diag.SuggestedFixes {\n\t\tvar gobEdits []gobTextEdit\n\t\tfor _, textEdit := range fix.TextEdits {\n\t\t\tloc, err := posToLocation(textEdit.Pos, textEdit.End)\n\t\t\tif err != nil {\n\t\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in SuggestedFixes: %w\", err)\n\t\t\t}\n\t\t\tgobEdits = append(gobEdits, gobTextEdit{\n\t\t\t\tLocation: loc,\n\t\t\t\tNewText: textEdit.NewText,\n\t\t\t})\n\t\t}\n\t\tfixes = append(fixes, gobSuggestedFix{\n\t\t\tMessage: fix.Message,\n\t\t\tTextEdits: gobEdits,\n\t\t})\n\t}\n\n\tvar related []gobRelatedInformation\n\tfor _, r := range diag.Related {\n\t\tloc, err := posToLocation(r.Pos, r.End)\n\t\tif err != nil {\n\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in Related: %w\", err)\n\t\t}\n\t\trelated = append(related, gobRelatedInformation{\n\t\t\tLocation: loc,\n\t\t\tMessage: r.Message,\n\t\t})\n\t}\n\n\tloc, err := posToLocation(diag.Pos, diag.End)\n\tif err != nil {\n\t\treturn gobDiagnostic{}, err\n\t}\n\n\t// The Code column of VSCode's Problems table renders this\n\t// information as \"Source(Code)\" where code is a link to CodeHref.\n\t// (The code field must be nonempty for anything to appear.)\n\tdiagURL := effectiveURL(a, diag)\n\tcode := \"default\"\n\tif diag.Category != \"\" {\n\t\tcode = diag.Category\n\t}\n\n\treturn gobDiagnostic{\n\t\tLocation: loc,\n\t\t// Severity for analysis diagnostics is dynamic,\n\t\t// based on user configuration per analyzer.\n\t\tCode: code,\n\t\tCodeHref: diagURL,\n\t\tSource: a.Name,\n\t\tMessage: diag.Message,\n\t\tSuggestedFixes: fixes,\n\t\tRelated: related,\n\t\t// Analysis diagnostics do not contain tags.\n\t}, nil\n}", "func newInjection() *injection {\n\treturn &injection{\n\t\tmarkerSQLs: map[injectionMarker][]string{},\n\t}\n}", "func AdvicesReplacer(locale, entry, response, _ string) (string, string) {\n\n\tresp, err := http.Get(adviceURL)\n\tif err != nil {\n\t\tresponseTag := \"no advices\"\n\t\treturn responseTag, util.GetMessage(locale, responseTag)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tresponseTag := \"no advices\"\n\t\treturn responseTag, util.GetMessage(locale, responseTag)\n\t}\n\n\tvar result map[string]interface{}\n\tjson.Unmarshal(body, &result)\n\tadvice := result[\"slip\"].(map[string]interface{})[\"advice\"]\n\n\treturn AdvicesTag, fmt.Sprintf(response, advice)\n}", "func bindEnvs(iface interface{}, parts ...string) {\n\tifv := reflect.ValueOf(iface)\n\tift := reflect.TypeOf(iface)\n\tfor i := 0; i < ift.NumField(); i++ {\n\t\tv := ifv.Field(i)\n\t\tt := ift.Field(i)\n\t\ttv, ok := t.Tag.Lookup(\"mapstructure\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch v.Kind() {\n\t\tcase reflect.Struct:\n\t\t\tbindEnvs(v.Interface(), append(parts, tv)...)\n\t\tdefault:\n\t\t\tviper.BindEnv(strings.Join(append(parts, tv), \".\"))\n\t\t}\n\t}\n}", "func reflect(fragment string) string {\n words := strings.Split(fragment, \" \")\n for i, word := range words {\n if Reflections, ok := Reflections[word]; ok {\n words[i] = Reflections\n }\n }\n return strings.Join(words, \" \")\n}", "func AutoG(w http.ResponseWriter, req *http.Request) {\n\tvar frase Frase\n\t_ = json.NewDecoder(req.Body).Decode(&frase)\n\tfraseNooized := \"\"\n\trand.Seed(time.Now().UnixNano())\n\tnum := rand.Intn(3)\n\tswitch num {\n\tcase 0:\n\t\tfraseNooized = NDecorator(frase.Testo)\n\tcase 1:\n\t\tfraseNooized = GDecorator(frase.Testo)\n\tdefault:\n\t\tfraseNooized = EDecorator(frase.Testo)\n\t}\n\tjson.NewEncoder(w).Encode(fraseNooized)\n}", "func (s *SidecarInjectField) Inject(pod *corev1.Pod) {\n\tlog.Info(fmt.Sprintf(\"inject pod : %s\", pod.GenerateName))\n\t// add initcontrainers to spec\n\tif pod.Spec.InitContainers != nil {\n\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, s.Initcontainer)\n\t} else {\n\t\tpod.Spec.InitContainers = []corev1.Container{s.Initcontainer}\n\t}\n\n\t// add volume to spec\n\tif pod.Spec.Volumes == nil {\n\t\tpod.Spec.Volumes = []corev1.Volume{}\n\t}\n\tpod.Spec.Volumes = append(pod.Spec.Volumes, s.SidecarVolume)\n\n\t// choose a specific container to inject\n\ttargetContainers := s.findInjectContainer(pod.Spec.Containers)\n\n\t// add volumemount and env to container\n\tfor i := range targetContainers {\n\t\tlog.Info(fmt.Sprintf(\"inject container : %s\", targetContainers[i].Name))\n\t\tif (*targetContainers[i]).VolumeMounts == nil {\n\t\t\t(*targetContainers[i]).VolumeMounts = []corev1.VolumeMount{}\n\t\t}\n\n\t\t(*targetContainers[i]).VolumeMounts = append((*targetContainers[i]).VolumeMounts, s.SidecarVolumeMount)\n\n\t\tif (*targetContainers[i]).Env != nil {\n\t\t\t(*targetContainers[i]).Env = append((*targetContainers[i]).Env, s.Env)\n\t\t} else {\n\t\t\t(*targetContainers[i]).Env = []corev1.EnvVar{s.Env}\n\t\t}\n\n\t\t// envs to be append\n\t\tvar envsTBA []corev1.EnvVar\n\t\tfor j, envInject := range s.Envs {\n\t\t\tisExists := false\n\t\t\tfor _, envExists := range targetContainers[i].Env {\n\t\t\t\tif strings.EqualFold(envExists.Name, envInject.Name) {\n\t\t\t\t\tisExists = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !isExists {\n\t\t\t\tenvsTBA = append(envsTBA, s.Envs[j])\n\t\t\t}\n\t\t}\n\t\tif len(s.Envs) > 0 {\n\t\t\t(*targetContainers[i]).Env = append((*targetContainers[i]).Env, envsTBA...)\n\t\t}\n\t}\n}", "func (compilerWrapper *CompilerWrapper) resolveAbiParamType(contractName string,\r\n typeStr string,\r\n aliases map[string]string,\r\n staticIntConsts *map[string]*big.Int) string {\r\n\r\n if IsArrayType(typeStr) {\r\n return compilerWrapper.resolveArrayTypeStaticIntConsts(contractName, typeStr, staticIntConsts)\r\n } else {\r\n return ResolveType(typeStr, aliases)\r\n }\r\n}", "func Connect(tag string, reference interface{}) (Injector, error) {\n\tinjector := injector{tag, reflect.Indirect(reflect.ValueOf(reference))}\n\treturn injector, injector.Inject(getFields(reference)...)\n}", "func findServiceInheritance(t *defs, svcOffset *serviceOffset, useAttr attrVal, hostname string, hgEnabled *attrVal , hgExcluded *attrVal, ID string, name string, vistedTemplate *attrVal) {\n // speed up lookup for the same inheritance chain\n for _, tmpl := range useAttr {\n // check if the template already been lookup for inheritance\n if !vistedTemplate.Has(tmpl){\n for _, def := range *t {\n if tmpl == def[\"name\"].ToString() {\n *vistedTemplate = append(*vistedTemplate, tmpl)\n if def.attrExist(\"host_name\") {\n if def[\"host_name\"].RegexHas(hostname){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostName\", ID, def[\"name\"].ToString())\n if def.attrExist(\"service_description\") {\n svcOffset.others.Add(def[\"service_description\"].ToString())\n }\n }else {\n svcOffset.Add(\"tmplhostName\", ID, def[\"service_description\"].ToString())\n }\n }\n if def[\"host_name\"].RegexHas(\"!\"+hostname){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostNameExcl\", ID, def[\"name\"].ToString())\n }else{\n svcOffset.Add(\"tmplhostNameExcl\", ID, def[\"service_description\"].ToString())\n }\n }\n }\n if def.attrExist(\"hostgroup_name\"){\n if def[\"hostgroup_name\"].HasAny(*hgEnabled...){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostgroupName\", ID, def[\"name\"].ToString())\n if def.attrExist(\"service_description\") {\n svcOffset.others.Add(def[\"service_description\"].ToString())\n }\n }else{\n svcOffset.Add(\"tmplhostgroupName\", ID, def[\"service_description\"].ToString())\n }\n }\n if def[\"hostgroup_name\"].HasAny(*hgExcluded...){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostgroupNameExcl\", ID, def[\"name\"].ToString())\n }else{\n svcOffset.Add(\"tmplhostgroupNameExcl\", ID, def[\"service_description\"].ToString())\n }\n }\n }\n if def.attrExist(\"use\") {\n findServiceInheritance(t , svcOffset , *def[\"use\"], hostname , hgEnabled, hgExcluded, ID, name, vistedTemplate)\n }\n break\n }\n }\n }\n }\n}", "func ExpandAbbreviations(template, abbreviations string) {\n\n}", "func (t *Taipan) bindFlags(ctx context.Context, cmd *cobra.Command) error {\n\tcollector := &gotils.ErrCollector{}\n\tb := func(flag *pflag.Flag, name string) {\n\t\tlog.Ctx(ctx).Trace().Str(\"flag\", flag.Name).Str(\"viper-name\", name).Msg(\"Binding flag\")\n\t\tcollector.Collect(t.v.BindPFlag(name, flag))\n\n\t\tenvVarSuffix := name\n\t\tif strings.ContainsAny(name, \"-.\") {\n\t\t\tenvVarSuffix = strings.NewReplacer(\"-\", \"_\", \".\", \"_\").Replace(name)\n\t\t}\n\n\t\tenvVarSuffix = strings.ToUpper(envVarSuffix)\n\t\tenvVar := fmt.Sprintf(\"%s_%s\", t.config.EnvironmentPrefix, envVarSuffix)\n\t\tlog.Ctx(ctx).Trace().Str(\"env-key\", envVar).Str(\"viper-name\", name).Msg(\"Binding environment\")\n\n\t\tcollector.Collect(t.v.BindEnv(name, envVar))\n\n\t\t// Apply the viper config value to the flag when the flag is not set and viper has a value\n\t\tif !flag.Changed && t.v.IsSet(name) {\n\t\t\tval := t.v.Get(name)\n\t\t\tcollector.Collect(cmd.Flags().Set(flag.Name, fmt.Sprintf(\"%v\", val)))\n\t\t}\n\t}\n\n\treplace := identity\n\tif t.config.NamespaceFlags {\n\t\treplacer := strings.NewReplacer(\"-\", \".\", \"_\", \".\")\n\t\treplace = replacer.Replace\n\t}\n\n\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\tname := replace(f.Name)\n\n\t\tif t.config.PrefixCommands {\n\t\t\tprefix := prefix(cmd)\n\t\t\tfor _, p := range prefix {\n\t\t\t\talias := fmt.Sprintf(\"%s.%s\", p, name)\n\t\t\t\tb(f, alias)\n\t\t\t}\n\t\t}\n\n\t\tb(f, name)\n\t})\n\n\tif collector.HasErrors() {\n\t\treturn collector\n\t}\n\n\treturn nil\n}" ]
[ "0.61296785", "0.5149551", "0.4850799", "0.47487968", "0.46673915", "0.44889128", "0.4452262", "0.44432408", "0.44358099", "0.44134143", "0.43503362", "0.43301424", "0.4324857", "0.43207198", "0.4270548", "0.42602628", "0.425869", "0.425649", "0.42529112", "0.42438713", "0.42188358", "0.42141685", "0.41994244", "0.41947135", "0.41941774", "0.41940698", "0.41816735", "0.41756913", "0.41740984", "0.41641256", "0.41562235", "0.41242582", "0.41154313", "0.41023657", "0.40737808", "0.4067468", "0.40670443", "0.40613684", "0.4061049", "0.40546718", "0.4053674", "0.4049933", "0.4034684", "0.40337527", "0.40227175", "0.40185314", "0.40106186", "0.4007622", "0.40021145", "0.40018573", "0.3999768", "0.3998142", "0.39959064", "0.39944077", "0.39897314", "0.39897314", "0.39897314", "0.39897314", "0.39809662", "0.3976137", "0.3965891", "0.39529097", "0.39503893", "0.3949454", "0.39428008", "0.39409465", "0.39349908", "0.39306146", "0.39295295", "0.39284873", "0.39282256", "0.39278227", "0.39251047", "0.39244518", "0.3924136", "0.3919737", "0.39184526", "0.39180705", "0.39089775", "0.39071113", "0.39056405", "0.39054117", "0.3905208", "0.3904074", "0.39019206", "0.38928527", "0.3892732", "0.38924327", "0.38869646", "0.38856128", "0.38848478", "0.38842747", "0.38815728", "0.38811028", "0.387294", "0.3870656", "0.3870292", "0.3870138", "0.38673803", "0.38654825" ]
0.7187308
0
IsFanged Takes an IOC and returns if it is fanged. Non fanging types (bitcoin, hashes, file, cve) are always determined to not be fanged
IsFanged принимает IOC и возвращает, является ли он фанговым. Типы, которые не поддерживают фангование (биткойн, хэши, файл, CVE), всегда определяются как не фанговые
func (ioc *IOC) IsFanged() bool { if ioc.Type == Bitcoin || ioc.Type == MD5 || ioc.Type == SHA1 || ioc.Type == SHA256 || ioc.Type == SHA512 || ioc.Type == File || ioc.Type == CVE { return false } // Basically just check if the fanged version is different from the input // This does label a partially fanged IOC is NOT fanged. I.e https://exampe[.]test.com/url is labled as NOT fanged if ioc.Fang().IOC == ioc.IOC { // They are equal, it's fanged return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Bet) IsForced() bool {\n\tswitch b.Type {\n\tcase bet.Ante, bet.BringIn, bet.SmallBlind, bet.BigBlind, bet.GuestBlind, bet.Straddle:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (me TxsdWorkType) IsFc() bool { return me.String() == \"FC\" }", "func (me TxsdWorkType) IsFo() bool { return me.String() == \"FO\" }", "func IsDuck(s interface{}) bool {\n\t_, ok := s.(Duck)\n\treturn ok\n}", "func (me TxsdInvoiceType) IsFs() bool { return me.String() == \"FS\" }", "func (gs *GaleShapely) isBetterThanFiance(man, woman, fiance int) bool {\n\tfor _, choice := range gs.womenWishes[woman] {\n\t\tswitch choice {\n\t\tcase man:\n\t\t\treturn true\n\t\tcase fiance:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (me TrefreshModeEnumType) IsOnChange() bool { return me == \"onChange\" }", "func (me TxsdInvoiceType) IsFt() bool { return me.String() == \"FT\" }", "func (me TxsdTaxAccountingBasis) IsF() bool { return me.String() == \"F\" }", "func (me TxsdInvoiceStatus) IsF() bool { return me.String() == \"F\" }", "func (f *Flapper) IsFlapping(service string, recompute bool) bool {\n\tif state, ok := f.services[service]; ok {\n\t\tif recompute {\n\t\t\tstate.Add(time.Now().Unix(), 0)\n\t\t}\n\t\treturn state.Total() >= int(f.max)\n\t}\n\treturn false\n}", "func (me TxsdMovementType) IsGd() bool { return me.String() == \"GD\" }", "func (i *Interest) MustBeFresh() bool {\n\treturn i.mustBeFresh\n}", "func mustFunc(c closed.Type) bool {\n\tswitch c.(type) {\n\tcase *closed.Interface, *closed.EmptySum:\n\t\treturn true\n\t}\n\treturn false\n}", "func (_BREMICO *BREMICOCaller) IsOverdue(opts *bind.CallOpts) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"isOverdue\")\n\treturn *ret0, err\n}", "func IsOrExtendsForgeFedTicketDependency(other vocab.Type) bool {\n\treturn typeticketdependency.IsOrExtendsTicketDependency(other)\n}", "func (me TrefreshModeEnumType) IsOnExpire() bool { return me == \"onExpire\" }", "func (e *Event) IsDownstream() bool {\n\treturn int32(e.GetType())&int32(EVENT_TYPE_DOWNSTREAM) != 0\n}", "func (*Component_Fan) IsYANGGoStruct() {}", "func (me TAttlistArticleDateDateType) IsElectronic() bool { return me.String() == \"Electronic\" }", "func (me TxsdMovementType) IsGc() bool { return me.String() == \"GC\" }", "func (me TxsdWorkStatus) IsF() bool { return me.String() == \"F\" }", "func (me TxsdMovementStatus) IsF() bool { return me.String() == \"F\" }", "func (me TAttlistCommentsCorrectionsRefType) IsErratumFor() bool { return me.String() == \"ErratumFor\" }", "func (me TitemIconStateEnumType) IsClosed() bool { return me == \"closed\" }", "func (me TxsdCounterSimpleContentExtensionType) IsFlow() bool { return me.String() == \"flow\" }", "func (b *OGame) IsDonutSystem() bool {\n\treturn b.isDonutSystem()\n}", "func (o *StoragePhysicalDiskAllOf) HasFdeCapable() bool {\n\tif o != nil && o.FdeCapable != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func ByTypeF(t typ.Type) func(Pokemon) bool {\n\treturn func(p Pokemon) bool {\n\t\treturn p.Type1() == t || p.Type2() == t\n\t}\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) IsDeposit(opts *bind.CallOpts, blockNum *big.Int) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"isDeposit\", blockNum)\n\treturn *ret0, err\n}", "func (me TxsdFeMorphologyTypeOperator) IsDilate() bool { return me.String() == \"dilate\" }", "func (b Bond) Interesting(f Filter) bool {\n\t// remove bonds with low coupon\n\tif b.Coupon < f.MinimumCoupon {\n\t\treturn false\n\t}\n\n\t// remove bonds with no date or more than 6 years of maturity\n\tmaximumMaturity := time.Now().Add(f.MaximumMaturity.Duration)\n\tif b.Maturity == nil || b.Maturity.After(maximumMaturity) {\n\t\treturn false\n\t}\n\n\t// remove bonds with low price or too expensive\n\tif b.LastPrice < f.MinimumPrice || b.LastPrice > f.MaximumPrice {\n\t\treturn false\n\t}\n\n\tif b.MinimumPiece < f.MinimumPiece || b.MinimumPiece > f.MaximumPiece {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (me TAttlistOtherIDSource) IsCpfh() bool { return me.String() == \"CPFH\" }", "func IsOrExtendsForgeFedBranch(other vocab.Type) bool {\n\treturn typebranch.IsOrExtendsBranch(other)\n}", "func (me TimePeriod) IsLifeToDate() bool { return me.String() == \"LifeToDate\" }", "func IsDefenseID(id int) bool {\n\treturn ID(id).IsDefense()\n}", "func (me TxsdFeTurbulenceTypeType) IsFractalNoise() bool { return me.String() == \"fractalNoise\" }", "func (o *W2) HasFederalIncomeTaxWithheld() bool {\n\tif o != nil && o.FederalIncomeTaxWithheld.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (*OpenconfigPlatform_Components_Component_Fan) IsYANGGoStruct() {}", "func IsOrExtendsForgeFedCommit(other vocab.Type) bool {\n\treturn typecommit.IsOrExtendsCommit(other)\n}", "func (me TitemIconStateEnumType) IsOpen() bool { return me == \"open\" }", "func (*NamedTypeDummy) isType() {}", "func (*Component_Chassis) IsYANGGoStruct() {}", "func (a *_Atom) isFunctional() bool {\n\tif a.atNum != 6 {\n\t\treturn true\n\t}\n\tif len(a.features) > 0 {\n\t\treturn true\n\t}\n\tif a.unsaturation > cmn.UnsaturationNone {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsFromCIPD(git string) bool {\n\treturn strings.Contains(git, \"cipd_bin_packages\")\n}", "func (el *gameStruct) IsForceField() bool {\n\treturn IsForceField(el.icon)\n}", "func (me TactionType) IsInvestigate() bool { return me.String() == \"investigate\" }", "func (*OnfTest1Choice_Vehicle) IsYANGGoStruct() {}", "func (me TxsdWithholdingTaxType) IsIs() bool { return me.String() == \"IS\" }", "func IsOrExtendsForgeFedTicket(other vocab.Type) bool {\n\treturn typeticket.IsOrExtendsTicket(other)\n}", "func IsOpen(err error) bool {\n\tfor err != nil {\n\t\tif bserr, ok := err.(stater); ok {\n\t\t\treturn bserr.State() == Open\n\t\t}\n\n\t\tif cerr, ok := err.(causer); ok {\n\t\t\terr = cerr.Cause()\n\t\t}\n\t}\n\treturn false\n}", "func (me TxsdInvoiceType) IsFr() bool { return me.String() == \"FR\" }", "func (*OnfTest1Choice_Vehicle_Battery) IsYANGGoStruct() {}", "func (deployment *Deployment) IsForce() bool {\n\tif force, ok := deployment.Flag(\"force\").(bool); ok {\n\t\treturn force\n\t} else {\n\t\treturn false\n\t}\n}", "func (me TviewRefreshModeEnumType) IsNever() bool { return me == \"never\" }", "func (x *fastReflection_LightClientAttackEvidence) Has(fd protoreflect.FieldDescriptor) bool {\n\tswitch fd.FullName() {\n\tcase \"tendermint.types.LightClientAttackEvidence.conflicting_block\":\n\t\treturn x.ConflictingBlock != nil\n\tcase \"tendermint.types.LightClientAttackEvidence.common_height\":\n\t\treturn x.CommonHeight != int64(0)\n\tcase \"tendermint.types.LightClientAttackEvidence.byzantine_validators\":\n\t\treturn len(x.ByzantineValidators) != 0\n\tcase \"tendermint.types.LightClientAttackEvidence.total_voting_power\":\n\t\treturn x.TotalVotingPower != int64(0)\n\tcase \"tendermint.types.LightClientAttackEvidence.timestamp\":\n\t\treturn x.Timestamp != nil\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: tendermint.types.LightClientAttackEvidence\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message tendermint.types.LightClientAttackEvidence does not contain field %s\", fd.FullName()))\n\t}\n}", "func (t *fsNotifyTrigger) Debounce() bool {\n\t// This trigger has built-in debouncing.\n\treturn false\n}", "func IsSafeClosed(\n\tt *testing.T, // : the T pointer\n\tds data.CXDS, // : ds already opened\n\treopen func() (data.CXDS, error), // : reopen ds to check the flag\n) {\n\t// IsSafeClosed() bool\n\n\tif ds.IsSafeClosed() == false {\n\t\tt.Error(\"fresh db is not safe closed\")\n\t}\n\n\tif reopen == nil {\n\t\treturn\n\t}\n\n\tvar err error\n\tif err = ds.Close(); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif ds, err = reopen(); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif ds.IsSafeClosed() == false {\n\t\tt.Error(\"not safe closed, after reopenning\")\n\t}\n\n}", "func (t Type) shouldFlush() bool {\n\tswitch t {\n\tcase TypeWebsocket, TypeTCP, TypeControlStream:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (*Component_Fabric) IsYANGGoStruct() {}", "func (del Delegation) IsFluidStakingActive() bool {\n\t// get the delegation fluid upgrade data\n\tfluid, err := del.repo.DelegationFluidStakingActive(&del.Delegation)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn fluid\n}", "func (f FooBarProps) IsProps() {}", "func CfnFilter_IsConstruct(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_guardduty.CfnFilter\",\n\t\t\"isConstruct\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (g GroupGate) IsOpen(f feature.Feature, a actor.Actor) bool {\n\tfor name := range g.value {\n\t\tif f, ok := registry[name]; ok && f(a) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (t *Ship) Diliver() bool {\n\tfmt.Println(\"Dilivering via Ship\")\n\treturn true\n}", "func (t *Truck) Diliver() bool {\n\tfmt.Println(\"Dilivering via Truck\")\n\treturn true\n}", "func (o *StoragePhysicalDisk) HasFdeCapable() bool {\n\tif o != nil && o.FdeCapable != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p RProc) IsCFunc() bool { return int(C._MRB_PROC_CFUNC_P(p.p)) != 0 }", "func (me TisoLanguageCodes) IsFi() bool { return me.String() == \"FI\" }", "func (g GenPluginType) IsGogo() bool {\n\treturn _genPluginTypeToIsGogo[g]\n}", "func (*NamedType) isType() {}", "func isRecursibleType(rv reflect.Value) bool {\n\tty := rv.Type()\n\tif ty.Kind() == reflect.Struct {\n\t\treturn unmarshalerFor(rv) == nil\n\t}\n\n\treturn false\n}", "func (t *Type) IsUntyped() bool", "func (me TxsdPaymentMechanism) IsCd() bool { return me.String() == \"CD\" }", "func (_BaseContentFactoryExt *BaseContentFactoryExtTransactor) IsContract(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _BaseContentFactoryExt.contract.Transact(opts, \"isContract\", addr)\n}", "func (g PercentageOfTimeGate) IsOpen(f feature.Feature, a actor.Actor) bool {\n\tr := seed.Uint32()\n\treturn r < (g.value / rangeFactor)\n}", "func (d *Door) IsOpen() bool {\n\t_, ok := d.DoorState.(OpenDoorState)\n\treturn ok\n}", "func (E_OnfTest1_Cont1A_Cont2D_Chocolate) IsYANGGoEnum() {}", "func (this *AggregateBase) IsCumulateDone(cumulative value.Value, context Context) (bool, error) {\n\treturn false, fmt.Errorf(\"There is no %v.IsCumulateDone().\", this.Name())\n}", "func (iface *Iface) IsPatched() bool {\n\treturn !(iface.patched == nil)\n}", "func (me TxsdInvoiceType) IsCs() bool { return me.String() == \"CS\" }", "func (me TactionType) IsOther() bool { return me.String() == \"other\" }", "func (f *FixUp) IsFixUp() bool {\n\tconfig := f.CustomConfiguration()\n\treturn overrideIsFixUp(config, true)\n}", "func (b *Base) IsEvent() bool {\n\treturn true\n}", "func (c CombatState) IsPartyDefeated() bool {\n\tfor _, actor := range c.Actors[party] {\n\t\tif !actor.IsKOed() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m *sdt) IsEffective() *bool {\n\treturn m.isEffectiveField\n}", "func (rs *RuleSet) IsCoherent() bool {\n\t// walk the graph\n\tfor start, ends := range rs.conflicts {\n\t\tfor _, end := range ends {\n\t\t\t// check if start and end of a conflict rule are dependents\n\t\t\tcanWalk := rs.canWalkBetween(start, end)\n\t\t\tif canWalk {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (*OnfTest1Choice_Vehicle_UnderCarriage) IsYANGGoStruct() {}", "func hasGCFinalizer(obj metav1.Object) bool {\n\tfor _, item := range obj.GetFinalizers() {\n\t\tswitch item {\n\t\tcase metav1.FinalizerDeleteDependents, metav1.FinalizerOrphanDependents:\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (me TshapeEnumType) IsCylinder() bool { return me == \"cylinder\" }", "func (me TxsdInvoiceType) IsDa() bool { return me.String() == \"DA\" }", "func (d *common) isUsed() (bool, error) {\n\tusedBy, err := d.usedBy(true)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn len(usedBy) > 0, nil\n}", "func (me TxsdTaxType) IsIs() bool { return me.String() == \"IS\" }", "func (_Rootchain *RootchainCaller) IsMature(opts *bind.CallOpts, exitableTimestamp uint64) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"isMature\", exitableTimestamp)\n\treturn *ret0, err\n}", "func (me TxsdActuate) IsOther() bool { return me == \"other\" }", "func (pkg *goPackage) isBuildable(c *config.Config) bool {\n\treturn pkg.firstGoFile() != \"\" || !pkg.proto.sources.isEmpty()\n}", "func (me TxsdWorkType) IsDc() bool { return me.String() == \"DC\" }", "func IsOrExtendsForgeFedRepository(other vocab.Type) bool {\n\treturn typerepository.IsOrExtendsRepository(other)\n}", "func (me TEventType) IsHITDisposed() bool { return me.String() == \"HITDisposed\" }", "func (t *Type) IsContainer() bool {\n\t_, ok := frugalContainerTypes[t.Name]\n\treturn ok\n}" ]
[ "0.5777848", "0.5636446", "0.5450624", "0.53252184", "0.5296213", "0.52835715", "0.5083163", "0.5069068", "0.49672344", "0.4967114", "0.4961127", "0.49527285", "0.4931717", "0.49222323", "0.49133813", "0.49083734", "0.4903117", "0.48999462", "0.48911142", "0.48828495", "0.48580572", "0.48571712", "0.4855442", "0.48481435", "0.48435348", "0.48275355", "0.48109904", "0.47920045", "0.47572386", "0.47517", "0.47515056", "0.47463518", "0.47202498", "0.47153938", "0.46910533", "0.468709", "0.46843666", "0.46764243", "0.46609902", "0.46497652", "0.46426728", "0.4632424", "0.46256024", "0.46250874", "0.46210933", "0.46197164", "0.46167505", "0.46127278", "0.46066007", "0.46003538", "0.45947802", "0.45920205", "0.45902503", "0.4589901", "0.45894894", "0.45749664", "0.45703813", "0.45664668", "0.4562838", "0.4557202", "0.45471004", "0.454357", "0.45432884", "0.45420647", "0.45397264", "0.45381996", "0.45344177", "0.45298353", "0.45293152", "0.45289803", "0.45273855", "0.45269796", "0.4524892", "0.45235968", "0.4513439", "0.4510988", "0.4510754", "0.45087278", "0.45073202", "0.450297", "0.44963205", "0.44957477", "0.44952238", "0.44924158", "0.44848058", "0.44824076", "0.44744918", "0.44733143", "0.44658697", "0.4460727", "0.44597882", "0.44556308", "0.4452836", "0.44452882", "0.44424072", "0.4440296", "0.44383872", "0.4437985", "0.4431422", "0.44298235" ]
0.7952134
0
Get finds projects by tags or all projects or the project in the current directory
Get находит проекты по тегам или все проекты или проект в текущей директории
func (i *Index) Get(tags []string, all bool) ([]string, error) { switch { case all: err := i.clean() return i.projects(), err case len(tags) > 0: if err := i.clean(); err != nil { return []string{}, err } projectsWithTags := []string{} for _, p := range i.projects() { found, err := i.hasTags(p, tags) if err != nil { return []string{}, nil } if found { projectsWithTags = append(projectsWithTags, p) } } sort.Strings(projectsWithTags) return projectsWithTags, nil default: curProjPath, _, err := Paths() if err != nil { return []string{}, err } if _, ok := i.Projects[curProjPath]; !ok { i.add(curProjPath) if err := i.save(); err != nil { return []string{}, err } } return []string{curProjPath}, nil } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetProjects(w http.ResponseWriter, r *http.Request, auth string) []Project {\n\tvar projects []Project\n\tprojectFileName := auth + globals.PROJIDFILE\n\t//First see if project already exist\n\tstatus, filepro := caching.ShouldFileCache(projectFileName, globals.PROJIDDIR)\n\tdefer filepro.Close()\n\tif status == globals.Error || status == globals.DirFail {\n\t\thttp.Error(w, \"Failed to create a file\", http.StatusInternalServerError)\n\t\treturn nil\n\t}\n\tif status == globals.Exist {\n\t\t//The file exist\n\t\t//We read from file\n\t\terr := caching.ReadFile(filepro, &projects)\n\t\tif err != nil {\n\t\t\terrmsg := \"The Failed Reading from file with error\" + err.Error()\n\t\t\thttp.Error(w, errmsg, http.StatusInternalServerError)\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\t//Else we need to query to get it\n\t\tfor i := 0; i < globals.MAXPAGE; i++ {\n\t\t\tvar subProj []Project\n\t\t\tquery := globals.GITAPI + globals.PROJQ + globals.PAGEQ + strconv.Itoa(i+1)\n\t\t\terr := apiGetCall(w, query, auth, &subProj)\n\t\t\tif err != nil {\n\t\t\t\t//The API call has failed\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t//When it's empty we no longer need to do calls\n\t\t\tif len(subProj) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprojects = append(projects, subProj...)\n\t\t}\n\t\tcaching.CacheStruct(filepro, projects)\n\n\t}\n\treturn projects\n}", "func Projects() []types.ProjectConfig {\n\tvar projects []types.ProjectConfig\n\tvar projectsWithPath []types.ProjectConfig\n\trootPath := ProjectRoot()\n\tprojectsDir := viper.GetString(\"projectDirectory\")\n\n\tif err := viper.UnmarshalKey(\"projects\", &projects); err != nil {\n\t\tlog.Print(err)\n\t\tlog.Fatal(\"Error: could not parse projects from config file\")\n\t}\n\n\t// extrapolate the full repo path\n\tfor _, project := range projects {\n\t\tvar dir string\n\n\t\t// default to project name if path fragement is not configured\n\t\tif project.Path != nil {\n\t\t\tdir = *project.Path\n\t\t} else {\n\t\t\tdir = project.Name\n\t\t}\n\n\t\tfullPath := path.Join(rootPath, projectsDir, dir)\n\t\tproject.FullPath = &fullPath\n\t\tprojectsWithPath = append(projectsWithPath, project)\n\t}\n\n\treturn projectsWithPath\n}", "func Projects() map[string]Project {\n\t// todo don't expose map here\n\treturn projects\n}", "func (dp *DummyProject) Get(name string) *project.Project {\n\tfor _, p := range projects {\n\t\tif p.Name == name {\n\t\t\treturn p\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetProjects(w http.ResponseWriter, r *http.Request) {\n\t// Get IDs for projects\n\t// Grab those projects.\n\t// Return those cool projects and response\n}", "func GetProjects(e Executor, userID string) (*ProjectSimpleList, error) {\n\treq, _ := http.NewRequest(\"GET\", RexBaseURL+apiProjectByOwner+userID, nil)\n\n\tresp, err := e.Execute(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tvar projects ProjectSimpleList\n\terr = json.NewDecoder(resp.Body).Decode(&projects)\n\n\t// set ID for convenience\n\tfor i, p := range projects.Embedded.Projects {\n\t\tre, _ := regexp.Compile(\"/projects/(.*)\")\n\t\tvalues := re.FindStringSubmatch(p.Links.Self.Href)\n\t\tif len(values) > 0 {\n\t\t\tprojects.Embedded.Projects[i].ID = values[1]\n\t\t}\n\t}\n\treturn &projects, err\n}", "func (uh *UserHandler) GetProjectsWMatchTags(w http.ResponseWriter, r *http.Request) {\n\n\tuser := uh.Authentication(r)\n\tif user == nil {\n\t\thttp.Redirect(w, r, \"/Login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tuid := user.UID\n\n\tprojects := uh.UService.SearchProjectWMatchTag(uid)\n\n\tjson, err := json.Marshal(projects)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tw.Write(json)\n}", "func (p *Provider) GetProjects() []string {\n\treturn p.opts.projects\n}", "func GetProjects() []m.Project {\n body, err := authenticatedGet(\"projects\")\n if err != nil {\n panic(err.Error())\n } else {\n var responseData projectResponse\n err = json.Unmarshal(body, &responseData)\n if err != nil {\n panic(err.Error())\n }\n\n return responseData.Data\n }\n}", "func (a *DefaultApiService) Projects(ctx context.Context) ([]Project, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload []Project\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/projects\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json; charset=utf-8\", }\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{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarQueryParams.Add(\"circle-token\", key)\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func (s *Server) Get(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProject, error) {\n\tif !s.enf.EnforceClaims(ctx.Value(\"claims\"), \"projects\", \"get\", q.Name) {\n\t\treturn nil, grpc.ErrPermissionDenied\n\t}\n\treturn s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Name, metav1.GetOptions{})\n}", "func SearchProjects(userID int) ([]models.Project, error) {\n\to := GetOrmer()\n\tsql := `select distinct p.project_id, p.name, p.public \n\t\tfrom project p \n\t\tleft join project_member pm on p.project_id = pm.project_id \n\t\twhere (pm.user_id = ? or p.public = 1) and p.deleted = 0`\n\n\tvar projects []models.Project\n\n\tif _, err := o.Raw(sql, userID).QueryRows(&projects); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn projects, nil\n}", "func (s projectService) Get(projectsQuery ProjectsQuery) (*Projects, error) {\n\tv, _ := query.Values(projectsQuery)\n\tpath := s.BasePath\n\tencodedQueryString := v.Encode()\n\tif len(encodedQueryString) > 0 {\n\t\tpath += \"?\" + encodedQueryString\n\t}\n\n\tresp, err := apiGet(s.getClient(), new(Projects), path)\n\tif err != nil {\n\t\treturn &Projects{}, err\n\t}\n\n\treturn resp.(*Projects), nil\n}", "func (s *ProjectService) Get(projectsQuery ProjectsQuery) (*resources.Resources[*Project], error) {\n\tv, _ := query.Values(projectsQuery)\n\tpath := s.BasePath\n\tencodedQueryString := v.Encode()\n\tif len(encodedQueryString) > 0 {\n\t\tpath += \"?\" + encodedQueryString\n\t}\n\n\tresp, err := api.ApiGet(s.GetClient(), new(resources.Resources[*Project]), path)\n\tif err != nil {\n\t\treturn &resources.Resources[*Project]{}, err\n\t}\n\n\treturn resp.(*resources.Resources[*Project]), nil\n}", "func getRequestedProjects(names []string, all bool) ([]*ddevapp.DdevApp, error) {\n\trequestedProjects := make([]*ddevapp.DdevApp, 0)\n\n\t// If no project is specified, return the current project\n\tif len(names) == 0 && !all {\n\t\tproject, err := ddevapp.GetActiveApp(\"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn append(requestedProjects, project), nil\n\t}\n\n\tallDockerProjects := ddevapp.GetDockerProjects()\n\n\t// If all projects are requested, return here\n\tif all {\n\t\treturn allDockerProjects, nil\n\t}\n\n\t// Convert all projects slice into map indexed by project name to prevent duplication\n\tallDockerProjectMap := map[string]*ddevapp.DdevApp{}\n\tfor _, project := range allDockerProjects {\n\t\tallDockerProjectMap[project.Name] = project\n\t}\n\n\t// Select requested projects\n\trequestedProjectsMap := map[string]*ddevapp.DdevApp{}\n\tfor _, name := range names {\n\t\tvar exists bool\n\t\t// If the requested project name is found in the docker map, OK\n\t\t// If not, if we find it in the globl project list, OK\n\t\t// Otherwise, error.\n\t\tif requestedProjectsMap[name], exists = allDockerProjectMap[name]; !exists {\n\t\t\tif _, exists = globalconfig.DdevGlobalConfig.ProjectList[name]; exists {\n\t\t\t\trequestedProjectsMap[name] = &ddevapp.DdevApp{Name: name}\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"could not find requested project %s\", name)\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// Convert map back to slice\n\tfor _, project := range requestedProjectsMap {\n\t\trequestedProjects = append(requestedProjects, project)\n\t}\n\n\treturn requestedProjects, nil\n}", "func (m *manager) List(query ...*models.ProjectQueryParam) ([]*models.Project, error) {\n\tvar q *models.ProjectQueryParam\n\tif len(query) > 0 {\n\t\tq = query[0]\n\t}\n\treturn dao.GetProjects(q)\n}", "func getProjects(r *http.Request) ([]byte, error) {\n\tm := bson.M{}\n\tif pid, e := convert.Id(r.FormValue(\"id\")); e == nil {\n\t\tm[db.ID] = pid\n\t}\n\tp, e := db.Projects(m, nil)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn util.JSON(map[string]interface{}{\"projects\": p})\n}", "func ProjectPs(p project.APIProject, c *cli.Context) error {\n\tqFlag := c.Bool(\"q\")\n\tallInfo, err := p.Ps(context.Background(), qFlag, c.Args()...)\n\tif err != nil {\n\t\treturn cli.NewExitError(err.Error(), 1)\n\t}\n\tos.Stdout.WriteString(allInfo.String(!qFlag))\n\treturn nil\n}", "func Projects(ctx context.Context) (map[string]*configpb.ProjectConfig, error) {\n\tval, err := projectCacheSlot.Fetch(ctx, func(any) (val any, exp time.Duration, err error) {\n\t\tvar pc map[string]*configpb.ProjectConfig\n\t\tif pc, err = fetchProjects(ctx); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\treturn pc, time.Minute, nil\n\t})\n\tswitch {\n\tcase err == caching.ErrNoProcessCache:\n\t\t// A fallback useful in unit tests that may not have the process cache\n\t\t// available. Production environments usually have the cache installed\n\t\t// by the framework code that initializes the root context.\n\t\treturn fetchProjects(ctx)\n\tcase err != nil:\n\t\treturn nil, err\n\tdefault:\n\t\tpc := val.(map[string]*configpb.ProjectConfig)\n\t\treturn pc, nil\n\t}\n}", "func projectsWithConfig(ctx context.Context) ([]string, error) {\n\tprojects, err := cfgclient.ProjectsWithConfig(ctx, ConfigFileName)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to get projects with %q from LUCI Config\",\n\t\t\tConfigFileName).Tag(transient.Tag).Err()\n\t}\n\treturn projects, nil\n}", "func GetUserRelevantProjects(userID int, projectName string) ([]models.Project, error) {\n\to := GetOrmer()\n\tsql := `select distinct\n\t\tp.project_id, p.owner_id, p.name,p.creation_time, p.update_time, p.public, pm.role role \n\t from project p \n\t\tleft join project_member pm on p.project_id = pm.project_id\n\t where p.deleted = 0 and pm.user_id= ?`\n\n\tqueryParam := make([]interface{}, 1)\n\tqueryParam = append(queryParam, userID)\n\tif projectName != \"\" {\n\t\tsql += \" and p.name like ? \"\n\t\tqueryParam = append(queryParam, projectName)\n\t}\n\tsql += \" order by p.name \"\n\tvar r []models.Project\n\t_, err := o.Raw(sql, queryParam).QueryRows(&r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}", "func (s *ProjectsService) Get(ctx context.Context, projectName string) (*Project, error) {\n\tquery := url.Values{\n\t\t\"name\": []string{projectName},\n\t}\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, newURI(projectsURI), WithQuery(query))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get project request creation failed: %w\", err)\n\t}\n\tres, resp, err := s.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get project failed: %w\", err)\n\t}\n\n\tif resp != nil && resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, ErrNotFound\n\t}\n\n\tp := &ProjectsList{\n\t\tProjects: []*Project{},\n\t}\n\tif err := json.Unmarshal(res, &p); err != nil {\n\t\treturn nil, fmt.Errorf(\"get project failed, unable to unmarshal repository list json: %w\", err)\n\t}\n\n\tp.Projects[0].Session.set(resp)\n\treturn p.Projects[0], nil\n\n}", "func getSnykProjects(token string, org string) []string {\n\tclient, err := snyk.NewClient(snyk.WithToken(token))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// List all projects for the authenticated user.\n\tprojects, err := client.OrganizationProjects(context.TODO(), org)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Generate a slice containing all the full project names for an org.\n\tvar s []string\n\tfor _, project := range projects {\n\t\t// Project names contain manifest files after a colon; only grab the project name.\n\t\ts = append(s, strings.Split(project.Name, \":\")[0])\n\t}\n\t// In case there were multiple manifests for a project, there are now multiple items duplicated in\n\t// our list. The deduplicate() function removes these.\n\treturn deduplicate(s)\n}", "func (o *OpenShot) GetProjects() (*Projects, error) {\n\tlog := getLogger(\"GetProjects\")\n\tvar projects Projects\n\n\terr := o.http.Get(log, o.projectsURL(), nil, &projects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &projects, nil\n}", "func (s projectService) GetAll() ([]*Project, error) {\n\titems := []*Project{}\n\tpath, err := getAllPath(s)\n\tif err != nil {\n\t\treturn items, err\n\t}\n\n\t_, err = apiGet(s.getClient(), &items, path)\n\treturn items, err\n}", "func (self *CassandraMetaStore) findAllProjects() ([]*meta.Project, error) {\n\titr := self.cassandraService.Client.Query(\"select name, oids from projects;\").Iter()\n\tvar oids []string\n\tvar name string\n\tproject_list := []*meta.Project{}\n\tfor itr.Scan(&name, &oids) {\n\t\tproject_list = append(project_list, &meta.Project{Name: name, Oids: oids})\n\t}\n\n\tif err := itr.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(project_list) == 0 {\n\t\treturn nil, meta.ErrProjectNotFound\n\t}\n\treturn project_list, nil\n}", "func All() []model.Project {\n projects := []model.Project{}\n\n // Find Projects and eager-load ProjectConfig.\n app.DB.\n Preload(\"ProjectConfig\").\n Order(\"nsp desc\").\n Find(&projects)\n\n return projects\n}", "func (repo *repo) GetProjects(params *project.GetProjectsParams) (*models.Projects, error) {\n\ttableName := fmt.Sprintf(\"cla-%s-projects\", repo.stage)\n\n\t// Use the nice builder to create the expression\n\texpr, err := expression.NewBuilder().WithProjection(buildProjection()).Build()\n\tif err != nil {\n\t\tlog.Warnf(\"error building expression for project scan, error: %v\", err)\n\t}\n\n\t// Assemble the query input parameters\n\tscanInput := &dynamodb.ScanInput{\n\t\tExpressionAttributeNames: expr.Names(),\n\t\tExpressionAttributeValues: expr.Values(),\n\t\tFilterExpression: expr.Filter(),\n\t\tProjectionExpression: expr.Projection(),\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t// If we have the next key, set the exclusive start key value\n\tif params.NextKey != nil && *params.NextKey != \"\" {\n\t\tlog.Debugf(\"Received a nextKey, value: %s\", *params.NextKey)\n\t\t// The primary key of the first item that this operation will evaluate.\n\t\t// and the query key (if not the same)\n\t\tscanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{\n\t\t\t\"project_id\": {\n\t\t\t\tS: params.NextKey,\n\t\t\t},\n\t\t}\n\t}\n\n\t// If we have a page size, set the limit value - make sure it's a positive value\n\tif params.PageSize != nil && *params.PageSize > 0 {\n\t\tlog.Debugf(\"Received a pageSize parameter, value: %d\", *params.PageSize)\n\t\t// The primary key of the first item that this operation will evaluate.\n\t\t// and the query key (if not the same)\n\t\tscanInput.Limit = params.PageSize\n\t} else {\n\t\t// Default page size\n\t\t*params.PageSize = 50\n\t}\n\n\tvar projects []models.Project\n\tvar lastEvaluatedKey string\n\n\t// Loop until we have all the records\n\tfor ok := true; ok; ok = lastEvaluatedKey != \"\" {\n\t\tresults, errQuery := repo.dynamoDBClient.Scan(scanInput)\n\t\tif errQuery != nil {\n\t\t\tlog.Warnf(\"error retrieving projects, error: %v\", errQuery)\n\t\t\treturn nil, errQuery\n\t\t}\n\n\t\t// Convert the list of DB models to a list of response models\n\t\tprojectList, modelErr := repo.buildProjectModels(results.Items)\n\t\tif modelErr != nil {\n\t\t\tlog.Warnf(\"error converting project DB model to response model, error: %v\",\n\t\t\t\tmodelErr)\n\t\t\treturn nil, modelErr\n\t\t}\n\n\t\t// Add to the project response models to the list\n\t\tprojects = append(projects, projectList...)\n\n\t\tif results.LastEvaluatedKey[\"project_id\"] != nil {\n\t\t\tlastEvaluatedKey = *results.LastEvaluatedKey[\"project_id\"].S\n\t\t\tscanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{\n\t\t\t\t\"project_id\": {\n\t\t\t\t\tS: aws.String(lastEvaluatedKey),\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\tlastEvaluatedKey = \"\"\n\t\t}\n\n\t\tif int64(len(projects)) >= *params.PageSize {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn &models.Projects{\n\t\tLastKeyScanned: lastEvaluatedKey,\n\t\tPageSize: *params.PageSize,\n\t\tProjects: projects,\n\t}, nil\n}", "func getRequestedProjects(names []string, all bool) ([]*ddevapp.DdevApp, error) {\n\trequestedProjects := make([]*ddevapp.DdevApp, 0)\n\n\t// If no project is specified, return the current project\n\tif len(names) == 0 && !all {\n\t\tproject, err := ddevapp.GetActiveApp(\"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn append(requestedProjects, project), nil\n\t}\n\n\tallProjects := ddevapp.GetApps()\n\n\t// If all projects are requested, return here\n\tif all {\n\t\treturn allProjects, nil\n\t}\n\n\t// Convert all projects slice into map indexed by project name to prevent duplication\n\tallProjectsMap := map[string]*ddevapp.DdevApp{}\n\tfor _, project := range allProjects {\n\t\tallProjectsMap[project.Name] = project\n\t}\n\n\t// Select requested projects\n\trequestedProjectsMap := map[string]*ddevapp.DdevApp{}\n\tfor _, name := range names {\n\t\tvar exists bool\n\t\tif requestedProjectsMap[name], exists = allProjectsMap[name]; !exists {\n\t\t\treturn nil, fmt.Errorf(\"could not find project %s\", name)\n\t\t}\n\t}\n\n\t// Convert map back to slice\n\tfor _, project := range requestedProjectsMap {\n\t\trequestedProjects = append(requestedProjects, project)\n\t}\n\n\treturn requestedProjects, nil\n}", "func (ps *ProjectStore) GetAll() ([]models.Project, error) {\n\tvar projects []models.Project\n\n\trows, err := ps.db.Query(`SELECT p.id, p.created_date, p.name, \n\t\t\t\t\t\t\t\t p.key, p.repo, p.homepage,\n\t\t\t\t\t\t\t\t p.icon_url, \n\t\t\t\t\t\t\t \t json_build_object('id', lead.id, 'username', lead.username, 'email', lead.email, 'full_name', lead.full_name, 'profile_picture', lead.profile_picture) AS lead\n\t\t\t\t\t\t\t FROM projects AS p\n\t\t\t\t\t\t\t JOIN users AS lead ON p.lead_id = lead.id;`)\n\tif err != nil {\n\t\treturn projects, handlePqErr(err)\n\t}\n\n\tfor rows.Next() {\n\t\tvar p models.Project\n\n\t\terr = intoProject(rows, &p)\n\t\tif err != nil {\n\t\t\treturn projects, handlePqErr(err)\n\t\t}\n\n\t\tprojects = append(projects, p)\n\t}\n\n\treturn projects, nil\n}", "func (g *GitLab) getProject(ctx context.Context, client *gitlab.Client, owner, name string) (*gitlab.Project, error) {\n\trepo, _, err := client.Projects.GetProject(fmt.Sprintf(\"%s/%s\", owner, name), nil, gitlab.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repo, nil\n}", "func (c *Client) Projects(page int, per_page int) ([]*Project, error) {\n\n\turl, opaque := c.ResourceUrl(projectsUrl, nil, QMap{\n\t\t\"page\": strconv.Itoa(page),\n\t\t\"per_page\": strconv.Itoa(per_page),\n\t})\n\n\tvar projects []*Project\n\n\tcontents, err := c.Do(\"GET\", url, opaque, nil)\n\tif err == nil {\n\t\terr = json.Unmarshal(contents, &projects)\n\t}\n\n\treturn projects, err\n}", "func ProjectsGET(c *gin.Context) {\n\tuser := c.MustGet(\"user\").(*User)\n\tif err := user.FetchProjects(); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, user.Projects)\n}", "func FilterProjects(db *sql.DB, collabSpace string) []Project {\n\tprojects := []Project{}\n\tfmt.Println(collabSpace)\n\tsqlQuery := `SELECT * FROM projects WHERE tags[1]=$1;`\n\trows, err := db.Query(sqlQuery, collabSpace)\n\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tfor rows.Next() {\n\t\tproject := Project{}\n\t\trows.Scan(&project.Name, pq.Array(&project.ProjectImgs),\n\t\t\t&project.DefaultImageIndex, pq.Array(&project.Tags),\n\t\t\t&project.Description, &project.Followers)\n\n\t\tprojects = append(projects, project)\n\t}\n\n\treturn projects\n}", "func All() ([]Project, error) {\n\tnames, err := workdir.ProjectNames()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprojects := []Project{}\n\tnow := time.Now()\n\tfor _, name := range names {\n\t\tp, err := FromName(name)\n\t\tif err != nil {\n\t\t\tcontinue // should not happen\n\t\t}\n\t\tp.Lock = locks.Check(name, now)\n\t\tprojects = append(projects, *p)\n\t}\n\treturn projects, nil\n}", "func (c Client) Projects() ([]Project, error) {\n\tu := mustParseURL(c.baseURL)\n\tu.Path += \"projects\"\n\n\tprojects := make([]Project, 0)\n\n\t// if there's more projects than returned by default by the API, links array will\n\t// be provided. The object that has the 'rel' field with the value of 'next' will\n\t// also contain the 'href' with the complete link to the next page.\n\tfor u != nil {\n\t\tresp, err := c.request(http.MethodGet, u, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"fetching files failed: %s\", err.Error())\n\t\t}\n\t\tdefer resp.Close()\n\n\t\tvar r struct {\n\t\t\tapiOKResponseTemplate\n\t\t\tProjects []Project `json:\"items\"`\n\t\t}\n\t\tif err := json.NewDecoder(resp).Decode(&r); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unmarshalling response failed: %s\", err.Error())\n\t\t}\n\t\tprojects = append(projects, r.Projects...)\n\n\t\tu = nil\n\t\tfor _, link := range r.Links {\n\t\t\tif link.Rel == \"next\" {\n\t\t\t\tu = mustParseURL(link.Href)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn projects, nil\n}", "func (pu *ProjectUtil) GetProjects(name string) ([]models.ExistingProject, error) {\n\turl := pu.rootURI + \"/api/v2.0/projects\"\n\tif len(strings.TrimSpace(name)) > 0 {\n\t\turl = url + \"?name=\" + name\n\t}\n\tdata, err := pu.testingClient.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pros []models.ExistingProject\n\tif err = json.Unmarshal(data, &pros); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pros, nil\n}", "func Get(name string) (Project, error) {\n\tproj, ok := projects[name]\n\tif !ok {\n\t\treturn nil, ErrProjectNotFound\n\t}\n\treturn proj, nil\n}", "func (h *Handler) GetProjects(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar projects []data.Project\n\n\tif projects, err = h.TodoGo.GetProjects(r.Context()); err != nil {\n\t\tresponse.Error(w, err)\n\t\treturn\n\t}\n\tresponse.Success(200, w, projects)\n}", "func List(ctx context.Context, client *selvpcclient.ServiceClient) ([]*Project, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract projects from the response body.\n\tvar result struct {\n\t\tProjects []*Project `json:\"projects\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Projects, responseResult, nil\n}", "func GetProject(w http.ResponseWriter, r *http.Request) {\n\t// Get item params\n\t// Perform get, db n' stuff.\n\t// render.JSON(w, r)\n}", "func GetProjects() ([]*github.Repository) {\n\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: os.Getenv(\"GITHUB_PAT\")},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\n\tclient := github.NewClient(tc)\n\n\t// list all repositories for the authenticated user\n\trepos, _, _ := client.Repositories.List(ctx, \"\", nil)\n\n\t// for _, repo := range repos {\n \n // fmt.Println(*repo.HTMLURL)\n // }\n\n\treturn repos\n}", "func GetProjects(_ *router.WebRequest) *model.Container {\n\tlist, err := factory.GetGitClient().ListProjects()\n\tif err != nil {\n\t\treturn model.ErrorResponse(model.MessageItem{\n\t\t\tCode: \"list-error\",\n\t\t\tMessage: err.Error(),\n\t\t}, 500)\n\t}\n\tdata := make([]interface{}, 0)\n\tfor _, item := range list {\n\t\tdata = append(data, item)\n\t}\n\treturn model.ListResponse(data)\n}", "func ProjectGet(w http.ResponseWriter, r *http.Request) {\n\tdb := utils.GetDB()\n\tdefer db.Close()\n\n\tvar projects []models.Project\n\terr := db.Find(&projects).Error\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\tutils.LOG.Println(err)\n\t\treturn\n\t}\n\n\terr = json.NewEncoder(w).Encode(projects)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\tutils.LOG.Println(err)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(`success`))\n\n}", "func (s *Server) Get(ctx context.Context, q *project.ProjectQuery) (*v1alpha1.AppProject, error) {\n\tif err := s.enf.EnforceErr(ctx.Value(\"claims\"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, q.Name); err != nil {\n\t\treturn nil, err\n\t}\n\tproj, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(ctx, q.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tproj.NormalizeJWTTokens()\n\treturn proj, err\n}", "func (b *ProjectModels) GetProjects(addwhere string, limit string, offset string, orderby string) ([]ProjectAll, error) {\n\tresult := make([]ProjectAll, 0)\n\tjoin := fmt.Sprintf(\"join %s on %s.id = %s.project_id \", TblProjectDetail, PROJECT, TblProjectDetail)\n\tselects := fmt.Sprintf(\"%s.*,%s.*\", PROJECT, TblProjectDetail)\n\torder := fmt.Sprintf(\"%s.%s\", PROJECT, orderby)\n\twhere := `(name LIKE \"%` + addwhere + `%\" OR description LIKE \"%` + addwhere + `%\" OR address LIKE \"%` + addwhere + `%\")`\n\n\terr := configs.GetDB.Table(PROJECT).Select(selects).Joins(join).Where(where).Limit(limit).Offset(offset).Order(order).Find(&result).Error\n\treturn result, err\n}", "func (s *ProjectService) GetAll() ([]*Project, error) {\n\titems := []*Project{}\n\tpath, err := services.GetAllPath(s)\n\tif err != nil {\n\t\treturn items, err\n\t}\n\n\t_, err = api.ApiGet(s.GetClient(), &items, path)\n\treturn items, err\n}", "func (w Workspace) Projects(\n\tctx context.Context,\n\tafter *string,\n\tbefore *string,\n\tfirst *int,\n\tlast *int,\n) (ProjectConnection, error) {\n\treturn PaginateProjectIDSliceContext(ctx, w.ProjectIDs, after, before, first, last)\n}", "func GetTrendingProjects(db *sql.DB) []Project {\n\tprojects := []Project{}\n\n\tsqlQuery := `SELECT * FROM projects ORDER BY followers desc LIMIT 20;`\n\trows, err := db.Query(sqlQuery)\n\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tfor rows.Next() {\n\t\tproject := Project{}\n\t\trows.Scan(&project.Name, pq.Array(&project.ProjectImgs),\n\t\t\t&project.DefaultImageIndex, pq.Array(&project.Tags),\n\t\t\t&project.Description, &project.Followers)\n\n\t\tprojects = append(projects, project)\n\t}\n\n\treturn projects\n}", "func (c *Client) getProjectID(owner, repoName, projURL string) (int64, error) {\n\tvar cancels []context.CancelFunc\n\tdefer func() {\n\t\tfor _, cancel := range cancels {\n\t\t\tcancel()\n\t\t}\n\t}()\n\tvar page int\n\tfor {\n\t\tplo := &gh.ProjectListOptions{\n\t\t\tListOptions: gh.ListOptions{\n\t\t\t\tPage: page,\n\t\t\t\tPerPage: 10,\n\t\t\t},\n\t\t}\n\t\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\t\tcancels = append(cancels, cancel)\n\t\tprojects, resp, err := c.GHClient.Repositories.ListProjects(ctx, owner, repoName, plo)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tfor _, project := range projects {\n\t\t\tif project.GetHTMLURL() == projURL {\n\t\t\t\treturn project.GetID(), nil\n\t\t\t}\n\t\t}\n\t\tpage = resp.NextPage\n\t\tif page == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn 0, nil\n}", "func ParserProjectFindOneById(id string) (*ParserProject, error) {\n\treturn ParserProjectFindOne(ParserProjectById(id))\n}", "func (dp *DummyProject) GetAll(owner ...string) []*project.Project {\n\tpr := []*project.Project{}\n\n\tfor _, p := range projects {\n\t\tfor _, ow := range owner {\n\t\t\tif p.Owner == ow {\n\t\t\t\tpr = append(pr, p)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, ok := acl[p.Name]; ok {\n\t\t\t\tfor _, u := range a {\n\t\t\t\t\tif ow == u {\n\t\t\t\t\t\tpr = append(pr, p)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pr\n}", "func (s Step) Projects(\n\tctx context.Context,\n\tafter *string,\n\tbefore *string,\n\tfirst *int,\n\tlast *int,\n) (ProjectConnection, error) {\n\treturn PaginateProjectIDSliceContext(ctx, s.ProjectIDs, after, before, first, last)\n}", "func (c *ProjectService) List() ([]Project, *http.Response, error) {\n\tresponse := new(projectListResponse)\n\tapiError := new(APIError)\n\tresp, err := c.sling.New().Get(\"\").Receive(response, apiError)\n\treturn response.Results, resp, relevantError(err, *apiError)\n}", "func (pc *MockProjectConnector) FindProjects(key string, limit int, sortDir int, isAuthenticated bool) ([]model.ProjectRef, error) {\n\tprojects := []model.ProjectRef{}\n\tif sortDir > 0 {\n\t\tfor i := 0; i < len(pc.CachedProjects); i++ {\n\t\t\tp := pc.CachedProjects[i]\n\t\t\tvisible := isAuthenticated || (!isAuthenticated && !p.Private)\n\t\t\tif p.Identifier >= key && visible {\n\t\t\t\tprojects = append(projects, p)\n\t\t\t\tif len(projects) == limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := len(pc.CachedProjects) - 1; i >= 0; i-- {\n\t\t\tp := pc.CachedProjects[i]\n\t\t\tvisible := isAuthenticated || (!isAuthenticated && !p.Private)\n\t\t\tif p.Identifier < key && visible {\n\t\t\t\tprojects = append(projects, p)\n\t\t\t\tif len(projects) == limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn projects, nil\n}", "func GetProjectList(tasks []api.Task) []api.Task {\n\tvar result []api.Task\n\tfor _, task := range tasks {\n\t\tif task.IsProject() {\n\t\t\tresult = append(result, task)\n\t\t}\n\t}\n\treturn result\n}", "func (pg *MongoDb) ListProjects(ctx context.Context, filter string, pageSize int, pageToken string) ([]*prpb.Project, string, error) {\n\t//id := decryptInt64(pageToken, pg.PaginationKey, 0)\n\t//TODO\n\treturn nil, \"\", nil\n}", "func (self *CassandraMetaStore) Projects() ([]*meta.Project, error) {\n\treturn self.findAllProjects()\n}", "func Projects(mods ...qm.QueryMod) projectQuery {\n\tmods = append(mods, qm.From(\"`projects`\"))\n\treturn projectQuery{NewQuery(mods...)}\n}", "func (w *ServerInterfaceWrapper) Projects(ctx echo.Context) error {\n\tvar err error\n\n\t// HasSecurity is set\n\n\tctx.Set(\"OpenId.Scopes\", []string{\"exitus/project.read\"})\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params ProjectsParams\n\t// ------------- Optional query parameter \"q\" -------------\n\tif paramValue := ctx.QueryParam(\"q\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"q\", ctx.QueryParams(), &params.Q)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter q: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"offset\" -------------\n\tif paramValue := ctx.QueryParam(\"offset\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"offset\", ctx.QueryParams(), &params.Offset)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter offset: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"limit\" -------------\n\tif paramValue := ctx.QueryParam(\"limit\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"limit\", ctx.QueryParams(), &params.Limit)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter limit: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.Projects(ctx, params)\n\treturn err\n}", "func (p *ProjectListAPIView) GET(w http.ResponseWriter, r *http.Request) {\n\tmanager := models.NewProjectManager(p.context)\n\tpaging := manager.NewPagingFromRequest(r)\n\tprojects := manager.NewProjectList()\n\n\tif err := manager.FilterPaged(&projects, paging); err != nil {\n\t\tglog.Error(err)\n\t\tresponse.New(http.StatusInternalServerError).Write(w, r)\n\t\treturn\n\t}\n\n\t// update paging\n\tresponse.New(http.StatusOK).Result(projects).Paging(paging).Write(w, r)\n}", "func Projects(mods ...qm.QueryMod) projectQuery {\n\tmods = append(mods, qm.From(\"`project`\"))\n\treturn projectQuery{NewQuery(mods...)}\n}", "func (s *ProjectsService) All(ctx context.Context) ([]*Project, error) {\n\tp := []*Project{}\n\topts := &PagingOptions{Limit: perPageLimit}\n\terr := allPages(opts, func() (*Paging, error) {\n\t\tlist, err := s.List(ctx, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp = append(p, list.GetProjects()...)\n\t\treturn &list.Paging, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}", "func GetProjects(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tname := vars[\"name\"]\n\n\tsite, err := database.GetSiteByName(name)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusNotFound, \"not_found\", nil)\n\t\treturn\n\t}\n\n\tprojects, err := database.GetProjects(site.ID)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusNotFound, err.Error(), nil)\n\t\treturn\n\t}\n\tutils.RespondWithJSON(w, http.StatusOK, \"success\", projects)\n\treturn\n}", "func (s *Service) Find(id entity.ID) (*entity.Project, error) {\n\treturn s.repo.Find(id)\n}", "func FindProject(project string) (*gitlab.Project, error) {\n\tif target, ok := localProjects[project]; ok {\n\t\treturn target, nil\n\t}\n\n\tsearch := project\n\t// Assuming that a \"/\" in the project means its owned by an org\n\tif !strings.Contains(project, \"/\") {\n\t\tsearch = user + \"/\" + project\n\t}\n\n\tvar opts gitlab.GetProjectOptions\n\ttarget, resp, err := lab.Projects.GetProject(search, &opts)\n\tif resp != nil && resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, ErrProjectNotFound\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// fwiw, I feel bad about this\n\tlocalProjects[project] = target\n\n\treturn target, nil\n}", "func FilterProjects() error {\n\t// Acquire a handle to the \"gn\" binary on the local workstation.\n\tgn, err := util.NewGn(Config.GnPath, Config.BuildDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Run \"fx gn <>\" command, and retrieve the output data.\n\tgen, err := gn.Gen(context.Background(), Config.Target)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Generate a map:\n\t// [filepath for every file in project X] -> [Project X]\n\t// With this mapping, we can match GN targets and file inputs\n\t// to check-license Project structs.\n\tfileMap, err := getFileMap()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Find Projects that match each target in the dependency tree.\n\tRootProject, err = processGenOutput(gen, fileMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Current() (*Project, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, errors.New(err.Error())\n\t}\n\n\tcounter := 0\n\tfor i := 0; i < 4; i++ {\n\t\tif _, err := os.Stat(wd + \"/.atlas\"); os.IsNotExist(err) && i == 3 {\n\t\t\treturn nil, errors.New(\"Not in an atlas project\")\n\t\t}\n\t\tif _, err := os.Stat(wd + \"/.atlas\"); err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tcounter++\n\t\twd += \"/..\"\n\t}\n\n\twdArr := strings.Split(wd, \"/\")\n\tfor i := 0; i < counter*2; i++ {\n\t\twdArr = wdArr[:len(wdArr)-1]\n\t}\n\n\twd = strings.Join(wdArr, \"/\")\n\n\tproject := Project{\n\t\tName: filepath.Base(wd),\n\t\tAbsolutePath: wd,\n\t\tPort: \"\",\n\t\tDBURL: \"\",\n\t}\n\treturn &project, nil\n}", "func Company_get_multiple_by_project () {\n\n // GET /projects/{project_id}/companies.json\n\n }", "func (test *Test) GetProject(projectName string) (models.Project, error) {\n\tps, err := test.GetProjects()\n\tvar projects []models.Project\n\tprojects = append([]models.Project{}, ps...)\n\n\tif err != nil {\n\t\treturn models.Project{}, errors.New(\"Could not get projects\" + err.Error())\n\t}\n\n\tfor _, p := range projects {\n\t\tif p.Name == projectName {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\treturn models.Project{}, errors.New(\"Could not get project \" + projectName)\n}", "func (h *Handler) Get(res http.ResponseWriter, req *http.Request) {\n\tquery := req.URL.Query()\n\tproject := query.Get(\"project\")\n\tif len(project) == 0 {\n\t\th.getAll(res, req)\n\t} else {\n\t\th.getOne(res, req, query, project)\n\t}\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 (c *ClusterTx) GetProjectUsedBy(project Project) ([]string, error) {\n\tinstances, err := c.GetInstanceURIs(InstanceFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timages, err := c.GetImageURIs(ImageFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprofiles, err := c.GetProfileURIs(ProfileFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolumes, err := c.GetStorageVolumeURIs(project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetworks, err := c.GetNetworkURIs(project.ID, project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetworkACLs, err := c.GetNetworkACLURIs(project.ID, project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusedBy := instances\n\tusedBy = append(usedBy, images...)\n\tusedBy = append(usedBy, profiles...)\n\tusedBy = append(usedBy, volumes...)\n\tusedBy = append(usedBy, networks...)\n\tusedBy = append(usedBy, networkACLs...)\n\n\treturn usedBy, nil\n}", "func GetAffectedProjects(lastcommit string, ignore ...string) (map[string]string, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir := \"\"\n\tif list := strings.Split(lastcommit, \"/\"); len(list) > 1 {\n\t\tdir = strings.Join(list[:len(list)-1], \"/\")\n\t\tlastcommit = list[len(list)-1]\n\t}\n\twd = filepath.Join(wd, dir)\n\n\tcmd := exec.Command(\"git\", \"diff\", \"--name-only\", lastcommit, \"HEAD\")\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\tcmd.Dir = wd\n\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdirs := make(map[string]struct{})\n\n\tscanner := bufio.NewScanner(bytes.NewReader(out))\n\tfor scanner.Scan() {\n\t\tdirs[filepath.Dir(scanner.Text())] = struct{}{}\n\t}\n\n\tprojects := make(map[string]string)\n\ndirs:\n\tfor p := range dirs {\n\t\tfor p != \".\" {\n\t\t\tfiles, err := ioutil.ReadDir(filepath.Join(wd, p))\n\t\t\tif err != nil && os.IsExist(err) {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, f := range files {\n\t\t\t\tif filepath.Ext(f.Name()) == \".csproj\" && !isInside(p, ignore) {\n\t\t\t\t\tprojects[f.Name()] = filepath.Join(p, f.Name())\n\t\t\t\t\tcontinue dirs\n\t\t\t\t}\n\t\t\t}\n\t\t\tp = filepath.Clean(p + \"/..\")\n\t\t}\n\t}\n\treturn projects, nil\n}", "func (c *ProjectService) Get(id string) (*Project, *http.Response, error) {\n\tproject := new(Project)\n\tapiError := new(APIError)\n\tpath := fmt.Sprintf(\"%s\", id)\n\tresp, err := c.sling.New().Get(path).Receive(project, apiError)\n\treturn project, resp, relevantError(err, *apiError)\n}", "func (s *Service) FindByName(name string) ([]*entity.Project, error) {\n\treturn s.repo.FindByName(name)\n}", "func (sw *scanWrap) Project(paths ...string) Scan {\n\treturn &scanWrap{\n\t\tscan: sw.scan.Project(paths...),\n\t}\n}", "func projectHandler(w http.ResponseWriter, r *http.Request) {\n\n\thelper.GetProjects(w, r)\n\n}", "func Get(ctx context.Context, client *selvpcclient.ServiceClient, id string) (*Project, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL, id}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract a project from the response body.\n\tvar result struct {\n\t\tProject *Project `json:\"project\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Project, responseResult, nil\n}", "func (m *SystemMock) GetProjectHierarchy(projectToken string, inHouse bool) ([]Library, error) {\n\treturn m.Libraries, nil\n}", "func (s *Service) FindAll() ([]*entity.Project, error) {\n\treturn s.repo.FindAll()\n}", "func (p *BaseProcessor) ListTags() ([]*RepoTags, error) {\n\tprojects, err := p.Client.AllProjects(\"\", \"\")\n\tif err != nil {\n\t\tlogrus.Errorf(\"List projects error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tif len(p.Cfg.Projects) != 0 {\n\t\tprojectsMap := make(map[string]*harbor.Project)\n\t\tfor _, p := range projects {\n\t\t\tprojectsMap[p.Name] = p\n\t\t}\n\n\t\tvar configuredProjects []*harbor.Project\n\t\tfor _, p := range p.Cfg.Projects {\n\t\t\tif pinfo, ok := projectsMap[p]; ok {\n\t\t\t\tconfiguredProjects = append(configuredProjects, pinfo)\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"project %s not found\", p)\n\t\t\t}\n\t\t}\n\t\tprojects = configuredProjects\n\t}\n\n\tvar results []*RepoTags\n\tfor _, pinfo := range projects {\n\t\tlogrus.Infof(\"Start to collect images for project '%s'\", pinfo.Name)\n\t\trepos, err := p.Client.ListAllRepositories(pinfo.ProjectID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"list repos for project '%s' error: %v\", pinfo.Name, err)\n\t\t}\n\n\t\tfor _, repo := range repos {\n\t\t\tproj, r := utils.ParseRepository(repo.Name)\n\t\t\ttags, err := p.Client.ListTags(proj, r)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"List tags for '%s/%s' error: %v\", proj, r, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar tagsInfo []Tag\n\t\t\tfor _, tag := range tags {\n\t\t\t\ttagsInfo = append(tagsInfo, Tag{\n\t\t\t\t\tName: tag.Name,\n\t\t\t\t\tDigest: tag.Digest,\n\t\t\t\t\tCreated: tag.Created,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tresults = append(results, &RepoTags{Project: pinfo.Name, Repo: r, Tags: tagsInfo})\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (b *ProjectModels) GetProject(id string) (ProjectAll, error) {\n\tvar result ProjectAll\n\tjoin := fmt.Sprintf(\"join %s on %s.id = %s.project_id \", TblProjectDetail, PROJECT, TblProjectDetail)\n\twhere := fmt.Sprintf(\"%s.id = ?\", PROJECT)\n\tselects := fmt.Sprintf(\"%s.*,%s.*\", PROJECT, TblProjectDetail)\n\n\terr := configs.GetDB.Table(PROJECT).Select(selects).Joins(join).Where(where, id).Find(&result).Error\n\treturn result, err\n}", "func (d *Driver) ProjectGet(partitionID string) (*ProjectGetResponse, error) {\n\tresponse := &ProjectGetResponse{}\n\tgetProject := project.NewFindProjectParams()\n\tgetProject.ID = partitionID\n\tresp, err := d.project.FindProject(getProject, d.auth)\n\tif err != nil {\n\t\treturn response, err\n\t}\n\tresponse.Project = resp.Payload\n\treturn response, nil\n}", "func CommandShowProjects(conf Config, ctx, query Query) error {\n\tif len(query.IDs) > 0 || query.HasOperators() {\n\t\treturn errors.New(\"query/context not supported for show-projects\")\n\t}\n\n\tts, err := LoadTaskSet(conf.Repo, conf.IDsFile, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tts.DisplayProjects()\n\treturn nil\n}", "func (c PGClient) GetServicesByProject(projects []string) (*[]Service, error) {\n\tvar projectsID []int64\n\trows, err := c.DB.Query(\"select id from tProjects where name = any($1)\", pg.Array(projects))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor rows.Next() {\n\t\tvar tempID int64\n\t\terr := rows.Scan(&tempID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprojectsID = append(projectsID, tempID)\n\t}\n\n\trows, err = c.DB.Query(\"select service_id from tServiceProjects where project_id=any($1)\", pg.Array(projectsID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserviceIDs := make([]int64, 0, 10)\n\tfor rows.Next() {\n\t\tvar tempID int64\n\t\terr := rows.Scan(&tempID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserviceIDs = append(serviceIDs, tempID)\n\t}\n\trows, err = c.DB.Query(\"select id,name,host,port,type from tServices where id =any($1)\", pg.Array(serviceIDs))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := make([]Service, 0, 200)\n\tfor rows.Next() {\n\t\tt := Service{}\n\t\tif err = rows.Scan(&t.ID, &t.Name, &t.Host, &t.Port, &t.Type); err != nil {\n\t\t\treturn &res, err\n\t\t}\n\t\tres = append(res, t)\n\t}\n\treturn &res, err\n}", "func (w *Workspace) FindProject(id string) *Project {\n\tfor i, p := range w.Projects {\n\t\tif p.Identifier == id {\n\t\t\treturn w.Projects[i]\n\t\t}\n\t}\n\treturn nil\n}", "func ProjectListAll(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\n\tres, err := projects.Find(\"\", \"\", refStr)\n\n\tif err != nil && err.Error() != \"not found\" {\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func getProjectLanguages(project Project, counter int, path, fileNameToSearch string) (returnedProject Project, returnedCounter int, filePath string) {\n\treturnedProject = project\n\treturnedCounter = counter //set counter\n\tfiles, err := ioutil.ReadDir(path) //ReadDir returns a slice of FileInfo structs\n\tif isError(err) {\n\t\treturn\n\t}\n\tfor _, file := range files { //loop through each files and directories\n\t\tvar fileName = file.Name()\n\t\tif file.IsDir() { //skip if file is directory\n\t\t\tif fileName == \"Pods\" || fileName == \".git\" { //ignore Pods and .git directories\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar prevPath = path\n\t\t\tpath = path + \"/\" + fileName //update directory path by adding /fileName\n\t\t\treturnedProject, returnedCounter, filePath = getProjectLanguages(returnedProject, returnedCounter, path, fileNameToSearch) //recursively call this function again\n\t\t\tpath = prevPath //if not found, go to next directory, but update our path\n\t\t}\n\t\tfilePath = path + \"/\" + fileName //path of file\n\t\tif fileName == fileNameToSearch {\n\t\t\treturnedCounter += 1\n\t\t\tvar language = createLanguageFromPath(filePath)\n\t\t\treturnedProject.Languages = append(project.Languages, language)\n\t\t}\n\t}\n\treturn\n}", "func (o ShareSettingsOutput) Projects() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ShareSettings) []string { return v.Projects }).(pulumi.StringArrayOutput)\n}", "func ParserProjectFindOne(query db.Q) (*ParserProject, error) {\n\tproject := &ParserProject{}\n\terr := db.FindOneQ(ParserProjectCollection, query, project)\n\tif adb.ResultsNotFound(err) {\n\t\treturn nil, nil\n\t}\n\treturn project, err\n}", "func GetUserProjects(w http.ResponseWriter, r *http.Request) {\n\tregisteredUsers := user.Users{}\n\tregisteredUsersResp := getData(registeredUsersEndpoint)\n\tregisteredUsers.UnmarshalUsers(registeredUsersResp)\n\n\tunregisteredUsers := user.Users{}\n\tunregisteredUsersResp := getData(unregisteredusersEndpoint)\n\tunregisteredUsers.UnmarshalUsers(unregisteredUsersResp)\n\n\tusers := user.Users{}\n\tusers.UserList = append(registeredUsers.UserList, unregisteredUsers.UserList...)\n\n\tvar projects []project.Project = project.UnmarshalProjects(getData(projectsEndpoint))\n\tusersprojects := processUserProjects(users, projects)\n\n\tw.WriteHeader(http.StatusOK)\n\tresp, err := usersprojects.ToJSON()\n\terrs.HandleError(err)\n\tfmt.Fprintf(w, string(resp))\n}", "func (p *ProjectService) GetAll(ctx iris.Context) {\r\n\tvar dbData = map[string]interface{}{ \r\n\t\t\"dbName\" : c.SysDBName, \r\n\t\t\"collectionName\" : c.TrionConfig.DBConfig.MongoConfig.ProjectsColl,\r\n\t}\r\n\tvar filter = map[string]interface{}{} //init empty\r\n /*\r\n\tFiltering for content-type : application/json only.\r\n\t1. Detect if header declares content-type application/json\r\n\t2. If yes - parse json. If not - don't, empty filter.\r\n\trequest payload:\r\n\t{\r\n\t\t\"filter\" : {our filter json}\r\n\t}\r\n\t*/\r\n\tif strings.ToLower(ctx.GetContentTypeRequested()) == \"application/json\" {\r\n\t\tvar request map[string]interface{}\r\n\t\terr := ctx.ReadJSON(&request)\r\n\t\tif err != nil { c.BadRequestAfterErrorResponse(ctx,err); return }\r\n\r\n\t\t//validate schema\r\n\t\tdocLoader := gojsonschema.NewGoLoader(request)\r\n\t\tresult, err := p.ProjectFilterSchema.Validate(docLoader)\r\n\t\tif err != nil {\r\n\t\t\tc.BadRequestAfterErrorResponse(ctx,err)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tif result.Valid() {\r\n\t\t\tv, ok := request[\"filter\"].(map[string]interface{})\r\n\t\t\tif ok { filter = v } \r\n\t\t} else { \r\n\t\t\tc.BadRequestAfterJSchemaValidationResponse(ctx,result) \r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\t// get projects from DB\r\n\titemsMap, err:= p.DSS.Read(nil, filter, dbData); \r\n\terr=checkIfNotFound(err, len(itemsMap), filter) \r\n\tif err !=nil {\r\n\t\tc.APIErrorSwitch(ctx,err,c.SliceMapToJSONString(itemsMap))\r\n\t} else {\r\n\t\tc.StatusJSON(ctx,iris.StatusOK,\"%v\",c.SliceMapToJSONString(itemsMap))\r\n\t}\r\n\treturn\r\n}", "func (w *ServerInterfaceWrapper) GetProjects(ctx echo.Context) error {\n\tvar err error\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params GetProjectsParams\n\t// ------------- Optional query parameter \"query\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"query\", ctx.QueryParams(), &params.Query)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter query: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"identifier\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"identifier\", ctx.QueryParams(), &params.Identifier)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter identifier: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetProjects(ctx, params)\n\treturn err\n}", "func (mockProvider) GetAllProjectConfigs(c context.Context) (map[string]*tricium.ProjectConfig, error) {\n\treturn map[string]*tricium.ProjectConfig{}, nil\n}", "func (s *Server) List(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProjectList, error) {\n\tlist, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(metav1.ListOptions{})\n\tlist.Items = append(list.Items, v1alpha1.GetDefaultProject(s.ns))\n\tif list != nil {\n\t\tnewItems := make([]v1alpha1.AppProject, 0)\n\t\tfor i := range list.Items {\n\t\t\tproject := list.Items[i]\n\t\t\tif s.enf.EnforceClaims(ctx.Value(\"claims\"), \"projects\", \"get\", project.Name) {\n\t\t\t\tnewItems = append(newItems, project)\n\t\t\t}\n\t\t}\n\t\tlist.Items = newItems\n\t}\n\treturn list, err\n}", "func GetProjects() (projects []m.Project, err error) {\n\tfmt.Println(\"GetProjects()\")\n\tbody, err := authenticatedGet(\"projects\")\n\tif err != nil {\n\t\tfmt.Printf(\"Got an error loading projects: %s\", err.Error())\n\t\treturn\n\t}\n\n\tvar responseData projectResponse\n\terr = json.Unmarshal(body, &responseData)\n\tif err != nil {\n\t\tfmt.Printf(\"Got an error parsing unmarshalling projects response: %s\\n\", err.Error())\n\t\treturn\n\t}\n\n\tprojects = responseData.Data\n\n\treturn\n}", "func LookupProjects(ctx context.Context, host, repo string) ([]string, error) {\n\t// Fetch all MapPart entities for the given host and repo.\n\tmps, err := getAll(ctx, host, repo)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to fetch MapParts\").Err()\n\t}\n\tprjs := stringset.New(len(mps))\n\tfor _, mp := range mps {\n\t\tprjs.Add(mp.Project)\n\t}\n\treturn prjs.ToSortedSlice(), nil\n}", "func (data *ProjectData) ProjectRepos() []string {\n\treturn append([]string{\"jcenter()\"}, data.Lang.projectRepos()...)\n}", "func (a *Client) GetProjects(params *GetProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetProjectsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetProjectsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"GetProjects\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/projects\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetProjectsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*GetProjectsOK)\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 GetProjects: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}" ]
[ "0.649808", "0.61884755", "0.61773306", "0.61728644", "0.6160904", "0.6150968", "0.6148858", "0.61327946", "0.61255896", "0.6123783", "0.61141396", "0.6096289", "0.6066046", "0.60416514", "0.6032895", "0.6004244", "0.59767795", "0.59659183", "0.59482855", "0.5927783", "0.5922738", "0.5901618", "0.5869623", "0.5857388", "0.58559465", "0.5850671", "0.584789", "0.58461875", "0.58237123", "0.5799226", "0.57907027", "0.578966", "0.5786101", "0.5776273", "0.57688046", "0.5749167", "0.574892", "0.57474923", "0.57407874", "0.5740707", "0.5736178", "0.5730017", "0.57040256", "0.5692263", "0.56519383", "0.56306696", "0.5626261", "0.5618348", "0.5616497", "0.5614346", "0.5600437", "0.55908793", "0.5581202", "0.55788636", "0.5572146", "0.5565659", "0.55652416", "0.5554108", "0.5539582", "0.5530152", "0.55089694", "0.55072963", "0.5505247", "0.54918027", "0.54804295", "0.547942", "0.5478907", "0.54684997", "0.54649794", "0.54473317", "0.54451424", "0.54374087", "0.543299", "0.54257035", "0.54233277", "0.54169035", "0.54129016", "0.5410464", "0.5401031", "0.5389695", "0.5388224", "0.5379465", "0.53731215", "0.5371428", "0.53693175", "0.5365782", "0.5363842", "0.5363528", "0.53619856", "0.53555596", "0.53555536", "0.535302", "0.5351623", "0.53365916", "0.53349024", "0.53346026", "0.53287625", "0.5323683", "0.5319122", "0.53155273" ]
0.7243131
0
loginAttempt increments the number of login attempts in sessions variable
loginAttempt увеличивает количество попыток входа в сессионную переменную
func loginAttempt(sess *sessions.Session) { // Log the attempt if sess.Values[sessLoginAttempt] == nil { sess.Values[sessLoginAttempt] = 1 } else { sess.Values[sessLoginAttempt] = sess.Values[sessLoginAttempt].(int) + 1 } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\n\tvar userid string\n\tlog.Println(\"Authenticating Login credentials.\")\n\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\"email\")) //Escape special characters for security.\n\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\"password\")) //Escape special characters for security.\n\tlog.Println(\"Attempt email :\", attemptEmail, \"Attempt Password:\", attemptPassword)\n\trow := databases.GlobalDBM[\"mydb\"].Con.QueryRow(\"SELECT userid FROM user WHERE email = '\" + attemptEmail + \"' AND password = '\" + attemptPassword + \"'\")\n\terr := row.Scan(&userid)\n\tif err != nil { // User does not exist.\n\t\tlog.Println(\"User authentication failed.\")\n\t\treturn &sessions.Session{Status: sessions.DELETED}\n\t}\n\t//User exists.\n\tlog.Println(\"User authentication successful. Creating new Session.\")\n\treturn sessions.GlobalSM[\"usersm\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\n}", "func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\n\tvar userid string\n\tlog.Println(\"Authenticating Login credentials.\")\n\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\"email\")) //Escape special characters for security.\n\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\"password\")) //Escape special characters for security.\n\tlog.Println(\"Attempt email :\", attemptEmail, \"Attempt Password:\", attemptPassword)\n\trow := databases.GlobalDBM[\"mydb\"].Con.QueryRow(\"SELECT userid FROM user WHERE email = '\" + attemptEmail + \"' AND password = '\" + attemptPassword + \"'\")\n\terr := row.Scan(&userid)\n\tif err != nil { // User does not exist.\n\t\tlog.Println(\"User authentication failed.\")\n\t\treturn &sessions.Session{Status: sessions.DELETED}\n\t}\n\t//User exists.\n\tlog.Println(\"User authentication successful. Creating new Session.\")\n\treturn sessions.GlobalSM[\"usersm\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\n}", "func addLoginAttempt(usr string) {\n\tcurr_time := time.Now().Unix()\n\thashed_usr := Hash1(usr)\n\tquery := QUERY_INSERT_LAST_LOGIN\n\tExecDB(query, hashed_usr, curr_time)\n}", "func (dc *DatadogCollector) IncrementAttempts() {\n\t_ = dc.client.Count(dmAttempts, 1, dc.tags, 1.0)\n}", "func (atics *Analytics) UserLoginAttempt(successful bool, username string, message string) {\n\n\tproducer, err := atics.newKafkaProducer()\n\n\tif err != nil {\n\t\tlog.Warning(\"Error creating kafka producer.\")\n\t\treturn\n\t}\n\n\tdefer producer.Close()\n\n\t// Delivery report handler for produced messages\n\tgo func() {\n\t\tfor events := range producer.Events() {\n\t\t\tswitch ev := events.(type) {\n\t\t\tcase *kafka.Message:\n\t\t\t\tif ev.TopicPartition.Error != nil {\n\t\t\t\t\tlog.Warning(\"Delivery failed: \", ev.TopicPartition)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Warning(\"Delivered message to topic: \", ev.TopicPartition)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tmMessage, mErr := atics.createAnalyticsMessage(successful, username, message)\n\tif mErr != nil {\n\t\treturn\n\t}\n\n\tproducer.Produce(&kafka.Message{\n\t\tTopicPartition: kafka.TopicPartition{Topic: &atics.loginKafkaTopic, Partition: kafka.PartitionAny},\n\t\tValue: mMessage,\n\t}, nil)\n\n\t// Wait for message deliveries before shutting down\n\tproducer.Flush(15 * 1000)\n\n}", "func (u *MockUserRecord) NumLoginDays() int { return 0 }", "func UserLoginPost(w http.ResponseWriter, r *http.Request) {\n\tsess := session.Instance(r)\n\tvar loginResp webpojo.UserLoginResp\n\n\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\n\tif sess.Values[SessLoginAttempt] != nil && sess.Values[SessLoginAttempt].(int) >= 5 {\n\t\tlog.Println(\"Brute force login prevented\")\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_429, constants.Msg_429, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tlog.Println(readErr)\n\t\tReturnError(w, readErr)\n\t\treturn\n\t}\n\n\tif len(body) == 0 {\n\t\tlog.Println(\"Empty json payload\")\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_400, constants.Msg_400, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\t//log.Println(\"r.Body\", string(body))\n\tloginReq := webpojo.UserLoginReq{}\n\tjsonErr := json.Unmarshal(body, &loginReq)\n\tif jsonErr != nil {\n\t\tlog.Println(jsonErr)\n\t\tReturnError(w, jsonErr)\n\t\treturn\n\t}\n\tlog.Println(loginReq.Username)\n\n\t//should check for expiration\n\tif sess.Values[UserID] != nil && sess.Values[UserName] == loginReq.Username {\n\t\tlog.Println(\"Already signed in - session is valid!!\")\n\t\tsess.Save(r, w) //Should also start a new expiration\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_200, constants.Msg_200, \"/api/admin/leads\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tresult, dbErr := model.UserByEmail(loginReq.Username)\n\tif dbErr == model.ErrNoResult {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_204, constants.Msg_204, \"/api/admin/login\")\n\t} else if dbErr != nil {\n\t\tlog.Println(dbErr)\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_500, constants.Msg_500, \"/error\")\n\t} else if passhash.MatchString(result.Password, loginReq.Password) {\n\t\tlog.Println(\"Login successfully\")\n\t\tsession.Empty(sess)\n\t\tsess.Values[UserID] = result.UserID()\n\t\tsess.Values[UserName] = loginReq.Username\n\t\tsess.Values[UserRole] = result.UserRole\n\t\tsess.Save(r, w) //Should also store expiration\n\t\tloginResp = webpojo.UserLoginResp{}\n\t\tloginResp.StatusCode = constants.StatusCode_200\n\t\tloginResp.Message = constants.Msg_200\n\t\tloginResp.URL = \"/api/admin/leads\"\n\t\tloginResp.FirstName = result.FirstName\n\t\tloginResp.LastName = result.LastName\n\t\tloginResp.UserRole = result.UserRole\n\t\tloginResp.Email = loginReq.Username\n\t} else {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_404, constants.Msg_404, \"/api/admin/login\")\n\t}\n\n\tReturnJsonResp(w, loginResp)\n}", "func (serv *AppServer) Login(username string, password string) int {\n\th := sha256.New()\n\th.Write([]byte(password))\n\thashed := hex.EncodeToString(h.Sum(nil))\n\tret, _ := strconv.Atoi(serv.ServerRequest([]string{\"Login\", username, hashed}))\n\treturn ret\n}", "func Login(r *http.Request, username string, password string) (*Session, bool) {\n\tif PreLoginHandler != nil {\n\t\tPreLoginHandler(r, username, password)\n\t}\n\t// Get the user from DB\n\tuser := User{}\n\tGet(&user, \"username = ?\", username)\n\tif user.ID == 0 {\n\t\tIncrementMetric(\"uadmin/security/invalidlogin\")\n\t\tgo func() {\n\t\t\tlog := &Log{}\n\t\t\tif r.Form == nil {\n\t\t\t\tr.ParseForm()\n\t\t\t}\n\t\t\tctx := context.WithValue(r.Context(), CKey(\"login-status\"), \"invalid username\")\n\t\t\tr = r.WithContext(ctx)\n\t\t\tlog.SignIn(username, log.Action.LoginDenied(), r)\n\t\t\tlog.Save()\n\t\t}()\n\t\tincrementInvalidLogins(r)\n\t\treturn nil, false\n\t}\n\ts := user.Login(password, \"\")\n\tif s != nil && s.ID != 0 {\n\t\ts.IP = GetRemoteIP(r)\n\t\ts.Save()\n\t\tif s.Active && (s.ExpiresOn == nil || s.ExpiresOn.After(time.Now())) {\n\t\t\ts.User = user\n\t\t\tif s.User.Active && (s.User.ExpiresOn == nil || s.User.ExpiresOn.After(time.Now())) {\n\t\t\t\tIncrementMetric(\"uadmin/security/validlogin\")\n\t\t\t\t// Store login successful to the user log\n\t\t\t\tgo func() {\n\t\t\t\t\tlog := &Log{}\n\t\t\t\t\tif r.Form == nil {\n\t\t\t\t\t\tr.ParseForm()\n\t\t\t\t\t}\n\t\t\t\t\tlog.SignIn(user.Username, log.Action.LoginSuccessful(), r)\n\t\t\t\t\tlog.Save()\n\t\t\t\t}()\n\t\t\t\treturn s, s.User.OTPRequired\n\t\t\t}\n\t\t}\n\t} else {\n\t\tgo func() {\n\t\t\tlog := &Log{}\n\t\t\tif r.Form == nil {\n\t\t\t\tr.ParseForm()\n\t\t\t}\n\t\t\tctx := context.WithValue(r.Context(), CKey(\"login-status\"), \"invalid password or inactive user\")\n\t\t\tr = r.WithContext(ctx)\n\t\t\tlog.SignIn(username, log.Action.LoginDenied(), r)\n\t\t\tlog.Save()\n\t\t}()\n\t}\n\n\tincrementInvalidLogins(r)\n\n\t// Record metrics\n\tIncrementMetric(\"uadmin/security/invalidlogin\")\n\treturn nil, false\n}", "func (d *Dao) SecurityLoginCount(c context.Context, index int64, reason string, stime, etime time.Time) (res int64, err error) {\n\trow := d.db.QueryRow(c, fmt.Sprintf(_securityLoginCountSQL, hitHistory(index)), reason, stime, etime)\n\tif err = row.Scan(&res); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tlog.Error(\"row.Scan error(%v)\", err)\n\t\t}\n\t}\n\treturn\n}", "func (client *Client) Login() error {\n\tuserpass := fmt.Sprintf(\"%s_%s\", client.Username, client.Password)\n\thash := fmt.Sprintf(\"%x\", md5.Sum([]byte(userpass)))\n\tres, _, err := client.FormattedRequest(\"/login/%s\", hash)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.sessionKey = res.ObjectsMap[\"status\"].PropertiesMap[\"response\"].Data\n\treturn nil\n}", "func Login(userName, password string) (Session, error) {\n\t// TODO: add check login attempts count\n\n\tsession := Session{}\n\taccount := Account{UserName: userName, Password: password}\n\n\tif err := mongo.Execute(\"monotonic\", AccountCollectionName(),\n\t\tfunc(collection *mgo.Collection) error {\n\t\t\tselector := bson.M{\n\t\t\t\t\"user_name\": account.UserName,\n\t\t\t\t\"password\": account.Password,\n\t\t\t}\n\t\t\treturn collection.Find(selector).One(&account)\n\t\t}); err != nil {\n\t\treturn session, fmt.Errorf(\"Error[%s] while login with username[%s] and password[%s]\", err, account.UserName, account.Password)\n\t}\n\n\tsession.TenantID = account.TenantID\n\tsession.AccountID = account.ID\n\tsession.SessionType = \"login\"\n\tsession.CreatedBy = account.Email\n\tif err := session.Insert(account.TenantID); err != nil {\n\t\treturn session, fmt.Errorf(\"Error[%s] while create session with username[%s] and password[%s]\", err, account.UserName, account.Password)\n\t}\n\treturn session, nil\n}", "func Login() gin.HandlerFunc {\r\n\tif gin.Mode() == \"debug\" {\r\n\t\treturn func(c *gin.Context) { c.Next() }\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tsession := sessions.Default(c)\r\n\t\tUserID := session.Get(\"UserID\")\r\n\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\tfmt.Println(\"UserID, IsLeader\", UserID, IsLeader)\r\n\t\tif UserID == nil {\r\n\t\t\tstate := string([]byte(c.Request.URL.Path)[1:])\r\n\t\t\tc.Redirect(http.StatusFound, \"/login?state=\"+state)\r\n\t\t\tc.Abort()\r\n\t\t} else {\r\n\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\tc.Next()\r\n\t\t}\r\n\r\n\t}\r\n}", "func (m *TeamsAsyncOperation) SetAttemptsCount(value *int32)() {\n m.attemptsCount = value\n}", "func (cl *APIClient) Login(params ...string) *R.Response {\n\totp := \"\"\n\tif len(params) > 0 {\n\t\totp = params[0]\n\t}\n\tcl.SetOTP(otp)\n\trr := cl.Request(map[string]string{\"COMMAND\": \"StartSession\"})\n\tif rr.IsSuccess() {\n\t\tcol := rr.GetColumn(\"SESSION\")\n\t\tif col != nil {\n\t\t\tcl.SetSession(col.GetData()[0])\n\t\t} else {\n\t\t\tcl.SetSession(\"\")\n\t\t}\n\t}\n\treturn rr\n}", "func canLogin(usr string) string {\n\t//find the last time they logged in\n\tquery := QUERY_GET_LAST_LOGIN\n\trows := QueryDB(query, Hash1(usr))\n\tret := LOGIN_INVALID\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tlast int64\n\t\t)\n\t\terr = rows.Scan(&last)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error accessing rows (my_server.go: canLogin\")\n\t\t\tfmt.Println(err)\n\t\t\treturn LOGIN_INVALID\n\t\t}\n\t\tdiff := time.Now().Unix() - last\n\t\tif diff <= LOGIN_RATE {\n\t\t\tret = LOGIN_TIME\n\t\t}\n\t}\n\treturn ret\n}", "func loginHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := context.Background()\n\tif b.authenticator == nil {\n\t\tvar err error\n\t\tb.authenticator, err = initAuth(ctx)\n\t\tif err != nil {\n\t\t\tlog.Print(\"loginHandler authenticator could not be initialized\")\n\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tsessionInfo := identity.InvalidSession()\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tlog.Printf(\"loginHandler: error parsing form: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tusername := r.PostFormValue(\"UserName\")\n\tlog.Printf(\"loginHandler: username = %s\", username)\n\tpassword := r.PostFormValue(\"Password\")\n\tusers, err := b.authenticator.CheckLogin(ctx, username, password)\n\tif err != nil {\n\t\tlog.Printf(\"main.loginHandler checking login, %v\", err)\n\t\thttp.Error(w, \"Error checking login\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif len(users) != 1 {\n\t\tlog.Printf(\"loginHandler: user %s not found or password does not match\", username)\n\t} else {\n\t\tcookie, err := r.Cookie(\"session\")\n\t\tif err == nil {\n\t\t\tlog.Printf(\"loginHandler: updating session: %s\", cookie.Value)\n\t\t\tsessionInfo = b.authenticator.UpdateSession(ctx, cookie.Value, users[0], 1)\n\t\t}\n\t\tif (err != nil) || !sessionInfo.Valid {\n\t\t\tsessionid := identity.NewSessionId()\n\t\t\tdomain := config.GetSiteDomain()\n\t\t\tlog.Printf(\"loginHandler: setting new session %s for domain %s\",\n\t\t\t\tsessionid, domain)\n\t\t\tcookie := &http.Cookie{\n\t\t\t\tName: \"session\",\n\t\t\t\tValue: sessionid,\n\t\t\t\tDomain: domain,\n\t\t\t\tPath: \"/\",\n\t\t\t\tMaxAge: 86400 * 30, // One month\n\t\t\t}\n\t\t\thttp.SetCookie(w, cookie)\n\t\t\tsessionInfo = b.authenticator.SaveSession(ctx, sessionid, users[0], 1)\n\t\t}\n\t}\n\tif strings.Contains(r.Header.Get(\"Accept\"), \"application/json\") {\n\t\tsendJSON(w, sessionInfo)\n\t} else {\n\t\tif sessionInfo.Authenticated == 1 {\n\t\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\t\tcontent := htmlContent{\n\t\t\t\tTitle: title,\n\t\t\t}\n\t\t\tb.pageDisplayer.DisplayPage(w, \"index.html\", content)\n\t\t} else {\n\t\t\tloginFormHandler(w, r)\n\t\t}\n\t}\n}", "func Test_Login_MultiLogin(t *testing.T) {\n\tgSession = nil\n\tsession1, err := login(TestValidUser)\n\tif session1 == nil || err != nil {\n\t\tt.Error(\"fail at login\")\n\t}\n\tsession2, err := login(TestValidUser)\n\tif err != nil {\n\t\tt.Error(\"fail at login\")\n\t}\n\tif session1 != session2 {\n\t\tt.Error(\"multi login should get same session\")\n\t}\n}", "func (_Userable *UserableSession) Login() (string, error) {\n\treturn _Userable.Contract.Login(&_Userable.CallOpts)\n}", "func (m *Miner) increaseAttempts() {\n\tm.attempts++\n\tif m.attempts >= 100 {\n\t\tm.hashRate = int64((m.attempts * iterationsPerAttempt * 1e9)) / (time.Now().UnixNano() - m.startTime.UnixNano())\n\t\tm.startTime = time.Now()\n\t\tm.attempts = 0\n\t}\n}", "func (u *User) PostLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\n\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\n\t// If the session already exists, redirect them back to the home page.\n\t// if ok := u.session.HasSession(r); ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\n\tvar req Credentials\n\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// Check if the user is logging with many failed attempts.\n\tif locked := u.appsensor.IsLocked(req.Email); locked {\n\t\twriteError(w, http.StatusTooManyRequests, errors.New(\"too many attempts\"))\n\t\treturn\n\t}\n\n\tuser, err := u.service.Login(req.Email, req.Password)\n\tif err != nil {\n\t\t// Log attempts here.\n\t\tu.appsensor.Increment(req.Email)\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tprovideToken := func(userid string) (string, error) {\n\t\tvar (\n\t\t\taud = \"https://server.example.com/login\"\n\t\t\tsub = userid\n\t\t\tiss = userid\n\t\t\tiat = time.Now().UTC()\n\t\t\texp = iat.Add(2 * time.Hour)\n\n\t\t\tkey = []byte(\"access_token_secret\")\n\t\t)\n\t\tclaims := crypto.NewStandardClaims(aud, sub, iss, iat.Unix(), exp.Unix())\n\t\treturn crypto.NewJWT(key, claims)\n\t}\n\n\taccessToken, err := provideToken(user.ID)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// Set the user session.\n\tu.session.SetSession(w, user.ID)\n\n\t// Set success ok.\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(M{\n\t\t\"access_token\": accessToken,\n\t})\n}", "func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\n\tsessionID, sessionIDState := cookies.GetCookie(req, \"session\")\n\tif !sessionIDState {\n\t\treturn false\n\t}\n\tsession, sessionState := authentication.userSession[sessionID.Value]\n\tif sessionState {\n\t\tsession.lastActivity = time.Now()\n\t\tauthentication.userSession[sessionID.Value] = session\n\t}\n\t_, userState := authentication.loginUser[session.email]\n\tsessionID.Path = \"/\"\n\tsessionID.MaxAge = sessionExistTime\n\thttp.SetCookie(res, sessionID)\n\treturn userState\n}", "func (e *EndpointSessions) auth(writer http.ResponseWriter, request *http.Request) {\n\tlogin := request.Header.Get(\"login\")\n\tpwd := request.Header.Get(\"password\")\n\tagent := request.Header.Get(\"User-Agent\")\n\tclient := request.Header.Get(\"client\")\n\n\t//try to do something against brute force attacks, see also https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks\n\ttime.Sleep(1000 * time.Millisecond)\n\n\t//another funny idea is to return a fake session id, after many wrong login attempts\n\n\tif len(login) < 3 {\n\t\thttp.Error(writer, \"login too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(agent) == 0 {\n\t\thttp.Error(writer, \"user agent missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(pwd) < 4 {\n\t\thttp.Error(writer, \"password too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(client) == 0 {\n\t\thttp.Error(writer, \"client missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tallowed := false\n\tfor _, allowedClient := range allowedClients {\n\t\tif allowedClient == client {\n\t\t\tallowed = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !allowed {\n\t\thttp.Error(writer, \"client is invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tusr, err := e.users.FindByLogin(login)\n\n\tif err != nil {\n\t\tif db.IsEntityNotFound(err) {\n\t\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\t} else {\n\t\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif !usr.Active {\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif !usr.PasswordEquals(pwd){\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\t//login is fine now, create a session\n\tcurrentTime := time.Now().Unix()\n\tses := &session.Session{User: usr.Id, LastUsedAt: currentTime, CreatedAt: currentTime, LastRemoteAddr: request.RemoteAddr, LastUserAgent: agent}\n\terr = e.sessions.Create(ses)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tWriteJSONBody(writer, &sessionDTO{Id: ses.Id, User: usr.Id})\n}", "func (m *TeamsAsyncOperation) GetAttemptsCount()(*int32) {\n return m.attemptsCount\n}", "func (db *DataBase) Login(name, password string) (int32, error) {\n\n\tvar (\n\t\ttx *sql.Tx\n\t\tuserID int32\n\t\terr error\n\t)\n\n\tif tx, err = db.Db.Begin(); err != nil {\n\t\treturn 0, err\n\t}\n\tdefer tx.Rollback()\n\n\tif userID, _, err = db.checkBunch(tx, name, password); err != nil {\n\t\treturn userID, err\n\t}\n\n\terr = tx.Commit()\n\treturn userID, err\n}", "func LoginAction(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\n\tuserName := r.FormValue(\"userName\")\n\t// validate username\n\tif len(userName) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Username specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\t// validate password\n\tif len(password) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Password specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t// get expected password\n\texpectedPassword := getStringFromDB(\"Users\", userName)\n\n\t// verify the password\n\tif expectedPassword != password {\n\t\thttp.Redirect(w, r, \"/login?errorM=Invalid credentials\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t\n\t// Create a new random session token\n\tsessionToken, err := uuid.NewUUID()\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/login?errorM=Unable to create token\", http.StatusSeeOther)\n\t}\n\t// Set the token in the db, along with the userName\n\tupdateDBString(\"Sessions\", userName, sessionToken.String())\n\n\t// set the expiration time\n\texpires := time.Now().Add(600 * time.Second)\n\tck := http.Cookie{\n Name: \"JSESSION_ID\",\n Path: \"/\",\n\t\tExpires: expires,\n\t\tValue: userName+\"_\"+sessionToken.String(),\n\t}\n\n // write the cookie to response\n http.SetCookie(w, &ck)\n\thttp.Redirect(w, r, \"/listbuckets\", http.StatusSeeOther)\n\n}", "func Login(params []byte) ([]byte, uint32) {\n\tif !initialized {\n\t\treturn nil, uint32(0xFFFFFFFF)\n\t}\n\tparameters := NEXString{}.FromBytes(params)\n\tfmt.Println(\"User \" + parameters.String + \" is trying to authenticate...\")\n\tresultcode := uint32(0x8068000B)\n\tbyteresult := []byte{0x0,0x0,0x0,0x0}\n\tbinary.LittleEndian.PutUint32(byteresult, resultcode)\n\treturn byteresult, resultcode\n}", "func (_Userable *UserableCallerSession) Login() (string, error) {\n\treturn _Userable.Contract.Login(&_Userable.CallOpts)\n}", "func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionInfo *sessionInfo) Error {\n\t// need to authenticate\n\tif policy.RequiresAuthentication() {\n\t\tvar err Error\n\t\tcommand := newLoginCommand(ctn.dataBuffer)\n\n\t\tif !sessionInfo.isValid() {\n\t\t\terr = command.login(policy, ctn, hashedPassword)\n\t\t} else {\n\t\t\terr = command.authenticateViaToken(policy, ctn, sessionInfo.token)\n\t\t\tif err != nil && err.Matches(types.INVALID_CREDENTIAL, types.EXPIRED_SESSION) {\n\t\t\t\t// invalidate the token\n\t\t\t\tif ctn.node != nil {\n\t\t\t\t\tctn.node.resetSessionInfo()\n\t\t\t\t}\n\n\t\t\t\t// retry via user/pass\n\t\t\t\tif hashedPassword != nil {\n\t\t\t\t\tcommand = newLoginCommand(ctn.dataBuffer)\n\t\t\t\t\terr = command.login(policy, ctn, hashedPassword)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif ctn.node != nil {\n\t\t\t\tatomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)\n\t\t\t}\n\t\t\t// Socket not authenticated. Do not put back into pool.\n\t\t\tctn.Close()\n\t\t\treturn err\n\t\t}\n\n\t\tsi := command.sessionInfo()\n\t\tif ctn.node != nil && si.isValid() {\n\t\t\tctn.node.sessionInfo.Store(si)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CheckLogin(w http.ResponseWriter, r *http.Request) bool {\n\tCookieSession, err := r.Cookie(\"sessionid\")\n\tif err != nil {\n\t\tfmt.Println(\"No Such Cookies\")\n\t\tSession.Create()\n\t\tfmt.Println(Session.ID)\n\t\tSession.Expire = time.Now().Local()\n\t\tSession.Expire.Add(time.Hour)\n\t\treturn false\n\t}\n\tfmt.Println(\"Cookki Found\")\n\ttempSession := session.UserSession{UID: 0}\n\tLoggedIn := database.QueryRow(\"select user_id from sessions where session_id = ?\",\n\t\tCookieSession).Scan(&tempSession)\n\tif LoggedIn == nil {\n\t\treturn false\n\t}\n\treturn true\n\n}", "func login(p *pkcs11.Ctx, session pkcs11.SessionHandle, passRetriever notary.PassRetriever) error {\n\n\tfor attempts := 0; ; attempts++ {\n\t\tvar (\n\t\t\tgiveup bool\n\t\t\terr error\n\t\t\tpasswd string\n\t\t)\n\t\tif userPin == \"\" {\n\t\t\tpasswd, giveup, err = passRetriever(\"Partition Password\", \"luna\", false, attempts)\n\t\t} else {\n\t\t\tgiveup = false\n\t\t\tpasswd = userPin\n\t\t}\n\n\t\t// Check if the passphrase retriever got an error or if it is telling us to give up\n\t\tif giveup || err != nil {\n\t\t\treturn trustmanager.ErrPasswordInvalid{}\n\t\t}\n\t\tif attempts > 2 {\n\t\t\treturn trustmanager.ErrAttemptsExceeded{}\n\t\t}\n\n\t\terr = p.Login(session, pkcs11.CKU_USER, passwd)\n\t\tif err == nil {\n\t\t\tif userPin == \"\" {\n\t\t\t\tuserPin = passwd\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\tuserPin = \"\"\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Unable to login to the session\")\n}", "func TryLogin(s sessions.Session,\n\trd render.Render,\n\temployeeRepository IEmployeeRepository,\n\tmodel LoginFormModel) {\n\t_, err := employeeRepository.AuthenticateEmployee(model.Login, model.Password)\n\tif err == nil {\n\t\ts.Set(\"login\", model.Login)\n\t\trd.Redirect(\"/\", http.StatusMovedPermanently)\n\t} else {\n\t\trd.Redirect(\"/login\")\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request, username string) error {\n\tsession, err := loggedUserSession.New(r, \"authenticated-user-session\")\n\tsession.Values[\"username\"] = username\n\tif err == nil {\n\t\terr = session.Save(r, w)\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn errors.New(\"Error creating session\")\n\t}\n\treturn err\n}", "func (s *PipelineExecutionStep) SetAttemptCount(v int64) *PipelineExecutionStep {\n\ts.AttemptCount = &v\n\treturn s\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\n\t// Start the session.\n\tsession := sessions.Start(w, r)\n\tif len(session.GetString(\"username\")) != 0 && checkErr(w, r, err) {\n\t\t// Redirect to index page if the user isn't signed in. Will remove later.\n\t\thttp.Redirect(w, r, \"/\", 302)\n\t}\n\n\tif r.Method != \"POST\" {\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Log In\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"login.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tusers := QueryUser(username)\n\n\t// Compare inputted password to the password in the database. If they're the same, return nil.\n\tvar password_compare = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password))\n\n\tif password_compare == nil {\n\n\t\tsession := sessions.Start(w, r)\n\t\tsession.Set(\"username\", users.Username)\n\t\tsession.Set(\"user_id\", users.ID)\n\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t} else {\n\n\t\thttp.Redirect(w, r, \"/login\", 302)\n\n\t}\n\n}", "func (c *Client) Login(username, password string) error {\n\tvar errAuth error\n\tc.sessionID, errAuth = a10v21Auth(c.host, username, password)\n\treturn errAuth\n}", "func SessionID() int64 { return time.Now().UnixNano() }", "func userLoginProcessing(userName string, password string, cookie string) (bool, int) {\n\tvar loginUser users\n\tvar userInitial userLoginStruct\n\n\tdb := dbConn()\n\tdefer db.Close()\n\n\t// login page defined token checking\n\tloginTokenCheck := db.QueryRow(\"SELECT event_id,used FROM user_initial_login WHERE token=? and used=0\", cookie).Scan(&userInitial.eventID, &userInitial.used)\n\n\tif loginTokenCheck != nil {\n\t\tlog.Println(\"user_initial_login table read faild\") // posible system error or hacking attempt ?\n\t\tlog.Println(loginTokenCheck)\n\t\treturn false, 0\n\t}\n\n\t// update initial user details table\n\tinitialUpdate, initErr := db.Prepare(\"update user_initial_login set used=1 where event_id=?\")\n\n\tif initErr != nil {\n\t\tlog.Println(\"Couldnt update initial user table\")\n\t\treturn false, 0 // we shouldnt compare password\n\t}\n\n\t_, updateErr := initialUpdate.Exec(userInitial.eventID)\n\n\tif updateErr != nil {\n\t\tlog.Println(\"Couldnt execute initial update\")\n\n\t}\n\tlog.Printf(\"Initial table updated for event id %d : \", userInitial.eventID)\n\t// end login page token checking\n\n\treadError := db.QueryRow(\"SELECT id,password FROM car_booking_users WHERE username=?\", userName).Scan(&loginUser.id, &loginUser.password)\n\tdefer db.Close()\n\tif readError != nil {\n\t\t//http.Redirect(res, req, \"/\", 301)\n\t\tlog.Println(\"data can not be taken\")\n\n\t}\n\n\tcomparePassword := bcrypt.CompareHashAndPassword([]byte(loginUser.password), []byte(password))\n\n\t// https://stackoverflow.com/questions/52121168/bcrypt-encryption-different-every-time-with-same-input\n\n\tif comparePassword != nil {\n\t\t/*\n\t\t\tHere I need to find a way to make sure that initial token is not get created each time wrong username password\n\n\t\t\tAlso Need to implement a way to restrict accessing after 5 attempts\n\t\t*/\n\t\tlog.Println(\"Wrong user name password\")\n\t\treturn false, 0\n\t} //else {\n\n\tlog.Println(\"Hurray\")\n\treturn true, userInitial.eventID\n\t//}\n\n}", "func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error Getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tif !session.IsNew {\n\t\tif session.Values[\"username\"] == u {\n\t\t\tlogger.Get().Info(\"User %s already logged in\", u)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn mkerror(\"user \" + session.Values[\"username\"].(string) + \" is already logged in\")\n\t\t}\n\t}\n\terrStrNotAllowed := \"This user is not allowed. Status Disabled\"\n\t// Verify user allowed to user usm with group privilage in the db\n\tif user, err := a.userDao.User(u); err == nil {\n\t\terrStr := fmt.Sprintf(\"Password does not match for user: %s\", u)\n\t\tif user.Status {\n\t\t\tif user.Type == authprovider.External {\n\t\t\t\tif LdapAuth(a, u, p) {\n\t\t\t\t\tlogger.Get().Info(\"Login Success for LDAP\")\n\t\t\t\t} else {\n\t\t\t\t\tlogger.Get().Error(errStr)\n\t\t\t\t\treturn mkerror(errStr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\n\t\t\t\tif verify != nil {\n\t\t\t\t\tlogger.Get().Error(errStr)\n\t\t\t\t\treturn mkerror(errStr)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Get().Error(errStrNotAllowed)\n\t\t\treturn mkerror(errStrNotAllowed)\n\t\t}\n\t} else {\n\t\tlogger.Get().Error(\"User does not exist: %s\", user)\n\t\treturn mkerror(\"User does not exist\")\n\t}\n\t// Update the new username in session before persisting to DB\n\tsession.Values[\"username\"] = u\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c UserInfo) Login(DiscordToken *models.DiscordToken) revel.Result {\n\tinfo, _ := c.Session.Get(\"DiscordUserID\")\n\tvar DiscordUser models.DiscordUser\n\tif info == nil {\n\t\tuserbytevalue, StatusCode := oAuth2Discord(DiscordToken.AccessToken)\n\t\tjson.Unmarshal(userbytevalue, &DiscordUser)\n\n\t\t// If we have an invalid status code, then that means we don't have the right\n\t\t// access token. So return.\n\t\tif StatusCode != 200 && StatusCode != 201 {\n\t\t\tc.Response.Status = StatusCode\n\t\t\treturn c.Render()\n\t\t}\n\t\t// Assign to the session, the discorduser ID.\n\t\t// If we've reached here, that must mean we've properly authenticated.\n\t\tc.Session[\"DiscordUserID\"] = DiscordUser.ID\n\t}\n\tc.Response.Status = 201\n\treturn c.Render()\n}", "func (m *MgoUserManager) Login(id interface{}, stay time.Duration) (string, error) {\n\tif stay < m.OnlineThreshold {\n\t\tstay = m.OnlineThreshold\n\t}\n\n\toid, err := getId(id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstate := LoginState{\n\t\tExpiredOn: time.Now().Add(stay),\n\t\tUserId: oid,\n\t\tToken: oid.Hex() + base64.URLEncoding.\n\t\t\tEncodeToString(securecookie.GenerateRandomKey(64)),\n\t}\n\n\terr = m.LoginColl.Insert(&state)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn state.Token, nil\n}", "func (h *TestAuth) Login(w http.ResponseWriter, req *http.Request) {\n\n\tresponse := make(map[string]string, 5)\n\n\tresponse[\"state\"] = authz.AuthNewPasswordRequired\n\tresponse[\"access_token\"] = \"access\"\n\t//response[\"id_token\"] = *authResult.IdToken\n\tresponse[\"refresh_token\"] = \"refersh\"\n\tresponse[\"expires\"] = \"3600\"\n\tresponse[\"token_type\"] = \"Bearer\"\n\trespData, _ := json.Marshal(response)\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func (r Repository) IncreaseValidateAttempt(ctx context.Context, uniqueID string, amount int) (int, error) {\n\tvalKey := generateOtpValidateAttemptKey(uniqueID)\n\n\tresult, err := r.redis.IncrementBy(ctx, valKey, amount)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// set the expiry of validate attempt\n\tif _, err := r.redis.Expire(ctx, valKey, int(durationExpireVAlidateAttempt)); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result, err\n}", "func LoginCook(name string, r *http.Request) (models.Session, models.Auth, error) {\n\n\tvar session models.Session\n\tauth := models.Auth{\n\t\tName: \"\",\n\t\tLevel: models.CookLevel,\n\t\tAuthorizedLevel: models.CookLevel,\n\t}\n\n\tc := Controller{}\n\n\tdata, err := c.Load(r)\n\n\tif err != nil {\n\t\treturn session, auth, err\n\t}\n\n\tvar users []models.User\n\tfor _, u := range data.Users {\n\t\tif u.Search() == strings.ToLower(name) {\n\t\t\tusers = append(users, u)\n\t\t}\n\t}\n\n\tif len(users) == 1 {\n\t\tuser := users[0]\n\t\t// update the user\n\t\tvar updated []models.User\n\t\tfor _, u := range c.Data.Users {\n\t\t\tif u.ID == user.ID {\n\t\t\t\tuser.LastLoginDate = time.Now()\n\t\t\t\tupdated = append(updated, user)\n\t\t\t} else {\n\t\t\t\tupdated = append(updated, u)\n\t\t\t}\n\t\t}\n\n\t\tc.SetUsers(updated)\n\n\t\tsessionUUID, _ := uuid.NewUUID()\n\n\t\tsession.UserID = user.ID\n\t\tsession.UserName = user.Name\n\t\tsession.UserLevel = user.UserLevel\n\t\tsession.AuthorizedLevel = models.CookLevel\n\t\tsession.UUID = sessionUUID.String()\n\t\tsession.Expires = time.Now().Add(10 * time.Hour)\n\n\t\t// store level in auth, to see if further login is required later\n\t\tauth.Name = user.Name\n\t\tauth.Level = user.UserLevel\n\t\t// start as a cook\n\t\tauth.AuthorizedLevel = session.AuthorizedLevel\n\n\t\t// add the session\n\t\tsessions := c.Data.Sessions\n\t\tsessions = append(sessions, session)\n\n\t\terr = c.StoreSessions(sessions, r)\n\n\t\tif err != nil {\n\t\t\treturn session, auth, err\n\t\t}\n\n\t} else {\n\t\treturn session, auth, errTooManyUsers\n\t}\n\n\treturn session, auth, nil\n}", "func Login(r * http.Request, response * APIResponse) {\n\tif r.FormValue(\"username\") != \"\" && r.FormValue(\"password\") != \"\" {\n\t\thashedPassword := hashString(r.FormValue(\"password\"))\n\t\tusername := strings.ToLower(r.FormValue(\"username\"))\n\t\tfor i := 0; i < len(Users); i++ {\n\t\t\tif Users[i].Username == username && Users[i].HashedPassword == hashedPassword {\n\t\t\t\tuser := Users[i]\n\t\t\t\tdateNow := time.Now()\n\t\t\t\tkeyEndTime := dateNow.AddDate(0, 1, 0) //New date one month away\n\t\t\t\tkeyString := randomKey()\n\t\t\t\tkey := Key{keyString, user.ID, dateNow, keyEndTime}\n\t\t\t\tAddKey(&key)\n\t\t\t\t\n\t\t\t\tresponse.Message = \"User successfully logged in\"\n\t\t\t\t\n\t\t\t\tapiLoginResponse := APILoginResponse{}\n\t\t\t\tapiLoginResponse.Username = username\n\t\t\t\tapiLoginResponse.KeyCode = keyString\n\t\t\t\tapiLoginResponse.UserImage = user.UserImageURL\n\t\t\t\tapiLoginResponse.Name = user.RealName\n\t\t\t\tapiLoginResponse.UserID = user.ID\n\t\t\t\t\n\t\t\t\tresponse.Data = apiLoginResponse\n\t\t\t\t\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\tresponse.Message = \"More information required for login\"\n\t\tresponse.SuccessCode = 400 //More information required\n\t}\n}", "func Login2FA(r *http.Request, username string, password string, otpPass string) *Session {\n\ts, otpRequired := Login(r, username, password)\n\tif s != nil {\n\t\tif otpRequired && s.User.VerifyOTP(otpPass) {\n\t\t\ts.PendingOTP = false\n\t\t\ts.Save()\n\t\t} else if otpRequired && !s.User.VerifyOTP(otpPass) && otpPass != \"\" {\n\t\t\tincrementInvalidLogins(r)\n\t\t}\n\t\treturn s\n\t}\n\treturn nil\n}", "func (k *Kerberos) Login(encST, encAuthenticator string) (string, error) {\n\tst := &kerberosServiceTicket{}\n\tif err := k.decrypt(encST, k.appSecretKey, st); err != nil {\n\t\treturn \"\", errSTInvalid\n\t}\n\tif st.Expired < time.Now().Unix() {\n\t\treturn \"\", errSTInvalid\n\t}\n\n\tauthenticator := &kerberosAuthenticator{}\n\tif err := k.decrypt(encAuthenticator, st.CSSK, authenticator); err != nil {\n\t\treturn \"\", errAuthenticatorInvalid\n\t}\n\n\tif authenticator.Username != st.Username ||\n\t\ttime.Now().Unix()-authenticator.Timestamp > int64(300) {\n\t\treturn \"\", errAuthenticatorInvalid\n\t}\n\n\treturn authenticator.Username, nil\n}", "func (c *Controller) Login(email, password string) error {\n\tinfo, err := Login(email, password, \"\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"login controller\")\n\t}\n\tc.sessionInfoLock.Lock()\n\tc.sessionInfo = info\n\tc.sessionInfoLock.Unlock()\n\treturn nil\n}", "func (cl *APIClient) LoginExtended(params ...interface{}) *R.Response {\n\totp := \"\"\n\tparameters := map[string]string{}\n\tif len(params) == 2 {\n\t\totp = params[1].(string)\n\t}\n\tcl.SetOTP(otp)\n\tif len(params) > 0 {\n\t\tparameters = params[0].(map[string]string)\n\t}\n\tcmd := map[string]string{\n\t\t\"COMMAND\": \"StartSession\",\n\t}\n\tfor k, v := range parameters {\n\t\tcmd[k] = v\n\t}\n\trr := cl.Request(cmd)\n\tif rr.IsSuccess() {\n\t\tcol := rr.GetColumn(\"SESSION\")\n\t\tif col != nil {\n\t\t\tcl.SetSession(col.GetData()[0])\n\t\t} else {\n\t\t\tcl.SetSession(\"\")\n\t\t}\n\t}\n\treturn rr\n}", "func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\tif !session.IsNew {\n\t\tif session.Values[\"username\"] == u {\n\t\t\tlogger.Get().Info(\"User: %s already logged in\", u)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn mkerror(\"user \" + session.Values[\"username\"].(string) + \" is already logged in\")\n\t\t}\n\t}\n\tif user, err := a.userDao.User(u); err == nil {\n\t\tif user.Type == authprovider.Internal && user.Status {\n\t\t\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\n\t\t\tif verify != nil {\n\t\t\t\tlogger.Get().Error(\"Password does not match for user: %s\", u)\n\t\t\t\treturn mkerror(\"password doesn't match\")\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Get().Error(\"User: %s is not allowed by localauthprovider\", u)\n\t\t\treturn mkerror(\"This user is not allowed by localauthprovider\")\n\t\t}\n\t} else {\n\t\tlogger.Get().Error(\"User: %s not found\", u)\n\t\treturn mkerror(\"user not found\")\n\t}\n\n\t// Update the new username in session before persisting to DB\n\tsession.Values[\"username\"] = u\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}", "func (c UserInfo) TestLogin(DiscordToken *models.DiscordToken) revel.Result {\n\tif DiscordToken.AccessToken == keys.TestAuthKey {\n\t\tc.Response.Status = 201\n\t\tc.Session[\"DiscordUserID\"] = \"Test\"\n\t} else {\n\t\tc.Response.Status = 403\n\t}\n\n\treturn c.Render()\n}", "func (cc *CommonController) Login() {\n\tprincipal := cc.GetString(\"principal\")\n\tpassword := cc.GetString(\"password\")\n\n\tuser, err := auth.Login(models.AuthModel{\n\t\tPrincipal: principal,\n\t\tPassword: password,\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"Error occurred in UserLogin: %v\", err)\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tif user == nil {\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tcc.SetSession(\"userId\", user.UserID)\n\tcc.SetSession(\"username\", user.Username)\n}", "func (c *Client) Login(ctx context.Context, p *LoginPayload) (res *Session, err error) {\n\tvar ires interface{}\n\tires, err = c.LoginEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*Session), nil\n}", "func Login(w http.ResponseWriter, req *http.Request) {\n\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"\", now, userIP, \"macAdress\", \"Login\", \"AccountModule\", \"\", \"\", \"_\", 0}\n\t// found, logobj := logpkg.CheckIfLogFound(userIP)\n\n\t// if found && now.Sub(logobj.Currenttime).Seconds() > globalPkg.GlobalObj.DeleteAccountTimeInseacond {\n\n\t// \tlogobj.Count = 0\n\t// \tbroadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t// }\n\t// if found && logobj.Count >= 10 {\n\n\t// \tglobalPkg.SendError(w, \"your Account have been blocked\")\n\t// \treturn\n\t// }\n\n\t// if !found {\n\n\t// \tLogindex := userIP.String() + \"_\" + logfunc.NewLogIndex()\n\n\t// \tlogobj = logpkg.LogStruct{Logindex, now, userIP, \"macAdress\", \"Login\", \"AccountModule\", \"\", \"\", \"_\", 0}\n\t// }\n\t// logobj = logfunc.ReplaceLog(logobj, \"Login\", \"AccountModule\")\n\n\tvar NewloginUser = loginUser{}\n\tvar SessionObj accountdb.AccountSessionStruct\n\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&NewloginUser)\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode object\", \"failed\")\n\t\treturn\n\t}\n\tInputData := NewloginUser.EmailOrPhone + \",\" + NewloginUser.Password + \",\" + NewloginUser.AuthValue\n\tlogobj.InputData = InputData\n\t//confirm email is lowercase and trim\n\tNewloginUser.EmailOrPhone = convertStringTolowerCaseAndtrimspace(NewloginUser.EmailOrPhone)\n\tif NewloginUser.EmailOrPhone == \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"please Enter your Email Or Phone\", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"please Enter your Email Or Phone\")\n\t\treturn\n\t}\n\tif NewloginUser.AuthValue == \"\" && NewloginUser.Password == \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"please Enter your password Or Authvalue\", \"failed\")\n\t\tglobalPkg.SendError(w, \"please Enter your password Or Authvalue\")\n\t\treturn\n\t}\n\n\tvar accountObj accountdb.AccountStruct\n\tvar Email bool\n\tEmail = false\n\tif strings.Contains(NewloginUser.EmailOrPhone, \"@\") && strings.Contains(NewloginUser.EmailOrPhone, \".\") {\n\t\tEmail = true\n\t\taccountObj = getAccountByEmail(NewloginUser.EmailOrPhone)\n\t} else {\n\t\taccountObj = getAccountByPhone(NewloginUser.EmailOrPhone)\n\t}\n\n\t//if account is not found whith data logged in with\n\tif accountObj.AccountPublicKey == \"\" && accountObj.AccountName == \"\" {\n\t\tglobalPkg.SendError(w, \"Account not found please check your email or phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Account not found please check your email or phone\", \"failed\")\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Account not found please check your email or phone\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\n\tif accountObj.AccountIndex == \"\" && Email == true { //AccountPublicKey replaces with AccountIndex\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email \", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"Please,Check your account Email \")\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email \"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\tif accountObj.AccountIndex == \"\" && Email == false {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phone \", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"Please,Check your account phone \")\n\t\t// logobj.OutputData = \"Please,Check your account phone \"\n\t\t// logobj.Process = \"failed\"\n\t\t// logobj.Count = logobj.Count + 1\n\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\n\tif (accountObj.AccountName == \"\" || (NewloginUser.Password != \"\" && accountObj.AccountPassword != NewloginUser.Password && Email == true) || (accountObj.AccountEmail != NewloginUser.EmailOrPhone && Email == true && NewloginUser.Password != \"\")) && NewloginUser.Password != \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email or password\", \"failed\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account Email or password\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email or password\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\tif (accountObj.AccountName == \"\" || (accountObj.AccountAuthenticationValue != NewloginUser.AuthValue && Email == true) || (accountObj.AccountEmail != NewloginUser.EmailOrPhone && Email == true)) && NewloginUser.AuthValue != \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email or AuthenticationValue\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email or AuthenticationValues\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account Email or AuthenticationValue\")\n\t\treturn\n\n\t}\n\tif (accountObj.AccountName == \"\" || (strings.TrimSpace(accountObj.AccountPhoneNumber) != \"\" && Email == false) || (accountObj.AccountPassword != NewloginUser.Password && Email == false) || (accountObj.AccountPhoneNumber != NewloginUser.EmailOrPhone && Email == false)) && NewloginUser.Password != \"\" {\n\t\tfmt.Println(\"i am a phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phoneNAmber OR password\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account phoneNAmber OR password\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account phoneNAmber OR password\")\n\t\treturn\n\n\t}\n\n\tif (accountObj.AccountName == \"\" || (strings.TrimSpace(accountObj.AccountPhoneNumber) != \"\" && Email == false) || (accountObj.AccountPassword != NewloginUser.AuthValue && Email == false) || (accountObj.AccountPhoneNumber != NewloginUser.EmailOrPhone && Email == false)) && NewloginUser.AuthValue != \"\" {\n\t\tfmt.Println(\"i am a phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phoneNAmber OR AuthenticationValue\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account phoneNAmber OR AuthenticationValue\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account phoneNAmber OR AuthenticationValue\")\n\t\treturn\n\n\t}\n\n\tif accountObj.AccountPublicKey == \"\" && accountObj.AccountName != \"\" {\n\t\tvar user User\n\n\t\tuser = createPublicAndPrivate(user)\n\n\t\tbroadcastTcp.BoardcastingTCP(accountObj, \"POST\", \"account\")\n\t\taccountObj.AccountPublicKey = user.Account.AccountPublicKey\n\t\taccountObj.AccountPrivateKey = user.Account.AccountPrivateKey\n\t\tsendJson, _ := json.Marshal(accountObj)\n\n\t\t//w.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Header().Set(\"jwt-token\", globalPkg.GenerateJwtToken(accountObj.AccountName, false)) // set jwt token\n\t\t//w.WriteHeader(http.StatusOK)\n\t\t//w.Write(sendJson)\n\t\tglobalPkg.SendResponse(w, sendJson)\n\t\tSessionObj.SessionId = NewloginUser.SessionID\n\t\tSessionObj.AccountIndex = accountObj.AccountIndex\n\t\t//--search if sesssion found\n\t\t// session should be unique\n\t\tflag, _ := CheckIfsessionFound(SessionObj)\n\n\t\tif flag == true {\n\n\t\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Delete Session\")\n\n\t\t}\n\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Add Session\")\n\n\t\treturn\n\n\t}\n\n\tfmt.Println(accountObj)\n\tSessionObj.SessionId = NewloginUser.SessionID\n\tSessionObj.AccountIndex = accountObj.AccountIndex\n\t//--search if sesssion found\n\t// session should be unique\n\tflag, _ := CheckIfsessionFound(SessionObj)\n\n\tif flag == true {\n\n\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Delete Session\")\n\n\t}\n\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Add Session\")\n\tglobalPkg.WriteLog(logobj, accountObj.AccountName+\",\"+accountObj.AccountPassword+\",\"+accountObj.AccountEmail+\",\"+accountObj.AccountRole, \"success\")\n\n\t// if logobj.Count > 0 {\n\t// \tlogobj.Count = 0\n\t// \tlogobj.OutputData = accountObj.AccountName\n\t// \tlogobj.Process = \"success\"\n\t// \tbroadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t// }\n\tsendJson, _ := json.Marshal(accountObj)\n\tw.Header().Set(\"jwt-token\", globalPkg.GenerateJwtToken(accountObj.AccountName, false)) // set jwt token\n\tglobalPkg.SendResponse(w, sendJson)\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func (e *Example) PostLogin (ctx context.Context, req *example.Request, rsp *example.Response) error {\n\t/* Print */\n\tbeego.Info(\"PostLogin /api/v1.0/sessions\")\n\n\t/* Init */\n\trsp.Errno = utils.RECODE_OK\n\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\n\t/* MySQL*/\n\t// 1 orm\n\to := orm.NewOrm()\n\t// 2 db object\n\tuser := models.User{}\n\t// 3 select\n\tuser.Mobile = req.Mobile\n\terr := o.Read(&user,\"Mobile\")\n\tif err != nil {\n\t\trsp.Errno = utils.RECODE_NODATA\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin MySQL: \", err)\n\t\treturn nil\n\t}\n\n\t// Md5\n\thash, err := utils.CrotoMd5(req.Password)\n\tif err != nil{\n\t\trsp.Errno = utils.RECODE_UNKNOWERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin Md5: \", err)\n\t\treturn nil\n\t}\n\t// password\n\tif hash != user.Password_hash{\n\t\trsp.Errno = utils.RECODE_PWDERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin password: \", err)\n\t\treturn nil\n\t}\n\n\t/* sessionID */\n\trsp.SessionID, err = utils.CrotoMd5(req.Mobile + req.Password + strconv.Itoa(int(time.Now().UnixNano())))\n\tif err != nil {\n\t\trsp.Errno = utils.RECODE_UNKNOWERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin sessionID: \", err)\n\t\treturn nil\n\t}\n\n\t/* Redis */\n\tr, err := utils.RedisServer(utils.G_server_name, utils.G_redis_addr, utils.G_redis_port, utils.G_redis_dbnum)\n\tif err != nil{\n\t\trsp.Errno = utils.RECODE_DBERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin Redis\")\n\t\treturn nil\n\t}\n\n\t/* <=Redis */\n\terr = r.Put(rsp.SessionID+\"name\", user.Name, time.Second*600)\n\terr = r.Put(rsp.SessionID+\"id\", user.Id, time.Second*600)\n\terr = r.Put(rsp.SessionID+\"mobile\", user.Mobile, time.Second*600)\n\n\treturn nil\n}", "func (app *application) postLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"screenName\")\n\tform.MaxLength(\"screenName\", 16)\n\tform.Required(\"password\")\n\n\trowid, err := app.players.Authenticate(form.Get(\"screenName\"), form.Get(\"password\"))\n\tif err != nil {\n\t\tif errors.Is(err, models.ErrInvalidCredentials) {\n\t\t\tform.Errors.Add(\"generic\", \"Supplied credentials are incorrect\")\n\t\t\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin{Form: form})\n\t\t} else {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\treturn\n\t}\n\t// Update loggedIn in database\n\tapp.players.UpdateLogin(rowid, true)\n\tapp.session.Put(r, \"authenticatedPlayerID\", rowid)\n\tapp.session.Put(r, \"screenName\", form.Get(\"screenName\"))\n\thttp.Redirect(w, r, \"/board/list\", http.StatusSeeOther)\n}", "func LoginFunc(w http.ResponseWriter, r *http.Request) {\n\tsession, _ := sessions.Store.Get(r, \"session\")\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tview.LoginTemplate.Execute(w, nil)\n\tcase \"POST\":\n\t\tr.ParseForm()\n\t\tusername := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\t// there will not handle the empty value it should be handle by javascript\n\t\tif user.UserIsExist(username) {\n\t\t\tif user.ValidUser(username, password) {\n\t\t\t\tsession.Values[\"loggedin\"] = \"true\"\n\t\t\t\tsession.Values[\"username\"] = username\n\t\t\t\tsession.Save(r, w)\n\t\t\t\tlog.Println(\"user\", username, \"is authenticated\")\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Wrong username or password\", http.StatusInternalServerError)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Error(w, \"User doesnt exist\", http.StatusInternalServerError)\n\t\t}\n\tdefault:\n\t\thttp.Redirect(w, r, \"/login/\", http.StatusUnauthorized)\n\t}\n}", "func (a *App) LoginRequired(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tsession, err := Store.Get(r, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error Getting the session. error: %v\", err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\tif session.IsNew {\n\t\tlogger.Get().Info(\"Not Authorized\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\tnext(w, r)\n}", "func (c *client) Login(w http.ResponseWriter, r *http.Request) (string, error) {\n\tlogrus.Trace(\"Processing login request\")\n\n\t// generate a random string for creating the OAuth state\n\toAuthState, err := random.GenerateRandomString(32)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// temporarily redirect request to Github to begin workflow\n\thttp.Redirect(w, r, c.OConfig.AuthCodeURL(oAuthState), http.StatusTemporaryRedirect)\n\n\treturn oAuthState, nil\n}", "func DoSignin(w http.ResponseWriter, r *http.Request) {\n\n\tvar id int\n\n\tif r.Method == \"POST\" {\n\t\t// Handles login when it is hit as a post request\n\t\tr.ParseForm()\n\t\tstmt, err := db.Prepare(\"select id from users where username=? and password=?\")\n\t\tres := stmt.QueryRow(r.FormValue(\"username\"), r.FormValue(\"password\"))\n\t\terr = res.Scan(&id)\n\n\t\tif err == nil {\n\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\tdefer sess.SessionRelease(w)\n\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t_ = sess.Set(\"user_id\", id)\n\t\t\t_ = sess.Set(\"username\", r.FormValue(\"username\"))\n\t\t\tif r.FormValue(\"remember-me\") == \"on\" {\n\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\n\t\t\t}\n\t\t\taddRemoteAddress(r, id)\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t} else {\n\t\t\tlog.Println(\"Database connection failed: \", err)\n\t\t}\n\t} else {\n\t\tanonsess, _ := anonSessions.SessionStart(w, r)\n\t\tdefer anonsess.SessionRelease(w)\n\t\t// Handles auto login when it is hit as a GET request\n\t\tsessionIdCookie, err := r.Cookie(\"userSession_id\")\n\t\tif err == nil {\n\t\t\tstmt, err := db.Prepare(\"select id, username from users where session_id=?\")\n\t\t\tres := stmt.QueryRow(sessionIdCookie.Value)\n\t\t\tvar username string\n\t\t\terr = res.Scan(&id, &username)\n\t\t\tif err == nil {\n\t\t\t\tif checkRemoteAddress(r, id) {\n\t\t\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\t\t\tdefer sess.SessionRelease(w)\n\t\t\t\t\terr = sess.Set(\"user_id\", id)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(err)\n\t\t\t\t\t}\n\t\t\t\t\t_ = sess.Set(\"username\", username)\n\t\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\t\t\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t\t} else {\n\t\t\t\t\thttp.Redirect(w, r, \"/newAddress\", 302)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thttp.Redirect(w, r, \"/userNotFound\", 302)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t}\n\t}\n}", "func (c App) CheckLogin() revel.Result {\n if _, ok := c.Session[\"userName\"]; ok {\n c.Flash.Success(\"You are already logged in \" + c.Session[\"userName\"] + \"!\")\n return c.Redirect(routes.Todo.Index())\n }\n\n return nil\n}", "func login(w http.ResponseWriter, r *http.Request){\n\t//Get value from cookie store with same name\n\tsession, _ := store.Get(r,\"session-name\")\n\t//Set authenticated to true\n\tsession.Values[\"authenticated\"]=true\n\t//Save request and responseWriter\n\tsession.Save(r,w)\n\t//Print the result to console\n\tfmt.Println(w,\"You have succesfully login\")\n}", "func loginprompt(w http.ResponseWriter, r *http.Request) {\n\t_, tid := GetAndOrUpdateSession(w, r)\n\tif tid != \"\" {\n\t\tshowMessage(w, \"Error: already logged in\",\n\t\t\t\"You are already logged in\", tid, \"\")\n\t\treturn\n\t}\n\ttemplate.Must(template.New(\"\").Parse(tLoginPrompt)).Execute(w, map[string]string{\n\t\t\"PageTitle\": \"Please log in\",\n\t\t\"Team\": r.FormValue(\"team\"),\n\t\t// TODO URL escaping would be pretty sweet\n\t\t\"TeamURL\": url.QueryEscape(r.FormValue(\"team\")),\n\t})\n}", "func (r *AccessLogRecord) successfulAttemptTime() float64 {\n\tif r.AppRequestFinishedAt.Equal(r.LastFailedAttemptFinishedAt) {\n\t\treturn -1\n\t}\n\n\t// we only want the time of the successful attempt\n\tif !r.LastFailedAttemptFinishedAt.IsZero() {\n\t\t// exclude the time any failed attempts took\n\t\treturn r.AppRequestFinishedAt.Sub(r.LastFailedAttemptFinishedAt).Seconds()\n\t} else {\n\t\treturn r.AppRequestFinishedAt.Sub(r.AppRequestStartedAt).Seconds()\n\t}\n}", "func Login(enrollID, enrollSecret string, loginChan chan int) bool {\n\tvar loginRequest loginRequest\n\tloginRequest.EnrollID = enrollID\n\tloginRequest.EnrollSecret = enrollSecret\n\n\treqBody, err := json.Marshal(loginRequest)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\turlstr := getHTTPURL(\"api/login\")\n\t_, err = performHTTPPost(urlstr, reqBody)\n\tif err != nil {\n\t\tloginChan <- 1\n\t\tlogger.Errorf(\"Login failed: %v\", err)\n\t\treturn false\n\t}\n\tloginChan <- 0\n\t// logger.Debugf(\"Login: url=%v request=%v response=%v\", urlstr, string(reqBody), string(response))\n\n\t// var result restResult\n\t// err = json.Unmarshal(response, &result)\n\t// if err != nil {\n\t// \tlogger.Errorf(\"Login failed: %v\", err)\n\t// \treturn false\n\t// }\n\n\t// if len(result.OK) == 0 {\n\t// \tlogger.Errorf(\"Login failed: %v\", result.Err)\n\t// \treturn false\n\t// }\n\n\treturn true\n}", "func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tses, _ := app.SessionStore.Get(req, SessionName)\n\tvar err error\n\tvar id int64\n\tif val := ses.Values[\"userId\"]; val != nil {\n\t\tid = val.(int64)\n\t}\n\n\tif err == nil {\n\t\t_, err = models.UserById(app.Db, id)\n\t}\n\n\tif err != nil {\n\t\thttp.Redirect(rw, req, app.Config.General.Prefix+\"/login\", http.StatusSeeOther)\n\t\treturn true\n\t}\n\treturn false\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\n\tvar domain string\n\tif os.Getenv(\"GO_ENV\") == \"dev\" {\n\t\tdomain = \"http://localhost:3000\"\n\t} else if os.Getenv(\"GO_ENV\") == \"test\" {\n\t\tdomain = \"http://s3-sih-test.s3-website-us-west-1.amazonaws.com\"\n\t} else if os.Getenv(\"GO_ENV\") == \"prod\" {\n\t\tdomain = \"https://schedulingishard.com\"\n\t}\n\t// Limit the sessions to 1 24-hour day\n\tsession.Options.MaxAge = 86400 * 1\n\tsession.Options.Domain = domain // Set to localhost for testing only. prod must be set to \"schedulingishard.com\"\n\tsession.Options.HttpOnly = true\n\n\tcreds := DecodeCredentials(r)\n\t// Authenticate based on incoming http request\n\tif passwordsMatch(r, creds) != true {\n\t\tlog.Printf(\"Bad password for member: %v\", creds.Email)\n\t\tmsg := errorMessage{\n\t\t\tStatus: \"Failed to authenticate\",\n\t\t\tMessage: \"Incorrect username or password\",\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t//http.Error(w, \"Incorrect username or password\", http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\t\treturn\n\t}\n\t// Get the memberID based on the supplied email\n\tmemberID := models.GetMemberID(creds.Email)\n\tmemberName := models.GetMemberName(memberID)\n\tm := memberDetails{\n\t\tStatus: \"OK\",\n\t\tID: memberID,\n\t\tName: memberName,\n\t\tEmail: creds.Email,\n\t}\n\n\t// Respond with the proper content type and the memberID\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n\t// Set cookie values and save\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"memberID\"] = m.ID\n\tif err = session.Save(r, w); err != nil {\n\t\tlog.Printf(\"Error saving session: %v\", err)\n\t}\n\tjson.NewEncoder(w).Encode(m)\n\t// w.Write([]byte(memberID)) // Alternative to fprintf\n}", "func (s *Server) handleLogin(w http.ResponseWriter, req *http.Request) error {\n\toauthState := uuid.New().String()\n\tloginSession, err := s.cookieStore.Get(req, LoginSessionName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tloginSession.Options = &sessions.Options{\n\t\tMaxAge: 600,\n\t\tHttpOnly: true,\n\t\tSecure: s.opts.SecureCookie,\n\t}\n\tloginSession.Values[\"oauth_state\"] = oauthState\n\terr = loginSession.Save(req, w)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error saving session: %s\", err)\n\t}\n\turl := s.oauthConfig.AuthCodeURL(oauthState)\n\thttp.Redirect(w, req, url, http.StatusTemporaryRedirect)\n\treturn nil\n}", "func (ctrl LoginController) ProcessLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tsession, _ := store.Get(r, \"session-id\")\n\tusername := r.PostFormValue(\"username\")\n\tpassword := r.PostFormValue(\"password\")\n\n\tuser, _ := model.GetUserByUserName(username)\n\tv := new(Validator)\n\n\tif !v.ValidateUsername(username) {\n\t\tSessionFlash(v.err, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tif user.Username == \"\" || !CheckPasswordHash(password, user.Password) {\n\t\tSessionFlash(messages.Error_username_or_password, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tsession.Values[\"username\"] = user.Username\n\tsession.Values[\"id\"] = user.ID\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, URL_HOME, http.StatusMovedPermanently)\n}", "func (r *AccessLogRecord) failedAttemptsTime() float64 {\n\tif r.LastFailedAttemptFinishedAt.IsZero() {\n\t\treturn -1\n\t}\n\treturn r.LastFailedAttemptFinishedAt.Sub(r.AppRequestStartedAt).Seconds()\n}", "func (c *Sender) Attempts() int {\n\treturn c.attempts\n}", "func (a *RedisAuthenticator) Login(username string, password string) string {\n\ttoken := checkValidLoginAndGenerateToken(username, password)\n\tif token == \"\" {\n\t\treturn \"\"\n\t}\n\tconn := a.Redis.Get()\n\tdefer conn.Close()\n\t_, err := conn.Do(\"SET\", \"octyne-token:\"+token, username)\n\tif err != nil {\n\t\tlog.Println(\"An error occurred while making a request to Redis for login!\", err) // skipcq: GO-S0904\n\t}\n\treturn token\n}", "func (a *Auth) Login(id int64, ctx *gin.Context) error {\n\tdefer a.redis.Save()\n\n\tuuid := uuid.New().String()\n\tif err := a.redis.Set(uuid, id, 24*time.Hour).Err(); err != nil {\n\t\treturn err\n\t}\n\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: a.cookie,\n\t\tValue: uuid,\n\t})\n\treturn nil\n}", "func CheckLoginStatus(w http.ResponseWriter, r *http.Request) (bool,interface{}){\n\tsess := globalSessions.SessionStart(w,r)\n\tsess_uid := sess.Get(\"UserID\")\n\tif sess_uid == nil {\n\t\treturn false,\"\"\n\t} else {\n\t\tuID := sess_uid\n\t\tname := sess.Get(\"username\")\n\t\tfmt.Println(\"Logged in User, \", uID)\n\t\t//Tpl.ExecuteTemplate(w, \"user\", nil)\n\t\treturn true,name\n\t}\n}", "func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionToken []byte) error {\n\t// need to authenticate\n\tif policy.RequiresAuthentication() {\n\t\tswitch policy.AuthMode {\n\t\tcase AuthModeExternal:\n\t\t\tvar err error\n\t\t\tcommand := newLoginCommand(ctn.dataBuffer)\n\t\t\tif sessionToken == nil {\n\t\t\t\terr = command.login(policy, ctn, hashedPassword)\n\t\t\t} else {\n\t\t\t\terr = command.authenticateViaToken(policy, ctn, sessionToken)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tif ctn.node != nil {\n\t\t\t\t\tatomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)\n\t\t\t\t}\n\t\t\t\t// Socket not authenticated. Do not put back into pool.\n\t\t\t\tctn.Close()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif ctn.node != nil && command.SessionToken != nil {\n\t\t\t\tctn.node._sessionToken.Store(command.SessionToken)\n\t\t\t\tctn.node._sessionExpiration.Store(command.SessionExpiration)\n\t\t\t}\n\n\t\t\treturn nil\n\n\t\tcase AuthModeInternal:\n\t\t\treturn ctn.authenticateFast(policy.User, hashedPassword)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (u *MyUserModel) Login() {\n\t// Update last login time\n\t// Add to logged-in user's list\n\t// etc ...\n\tu.authenticated = true\n}", "func Login(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Login\")\n\n\t// フォームデータのパース\n\terr := request.ParseForm()\n\tif err != nil {\n\t\toutputErrorLog(\"フォーム パース 失敗\", err)\n\t}\n\n\t// リクエストデータ取得\n\taccount := request.Form.Get(\"account\")\n\tpassword := request.Form.Get(\"password\")\n\tlog.Println(\"ユーザ:\", account)\n\n\t// ユーザデータ取得しモデルデータに変換\n\tdbm := db.ConnDB()\n\tuser := new(models.User)\n\trow := dbm.QueryRow(\"select account, name, password from users where account = ?\", account)\n\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\n\t\toutputErrorLog(\"ユーザ データ変換 失敗\", err)\n\t}\n\n\t// ユーザのパスワード認証\n\tif user.Password != password {\n\t\tlog.Println(\"ユーザ パスワード照合 失敗\")\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\n\tlog.Println(\"認証 成功\")\n\n\t// 認証が通ったら、セッション情報をDBに保存\n\tsessionID := generateSessionID(account)\n\tlog.Println(\"生成したセッションID:\", sessionID)\n\tnow := time.Now()\n\tresult, err := dbm.Exec(`INSERT INTO sessions\n\t\t(sessionID, account, expireDate)\n\t\tVALUES\n\t\t(?, ?, ?)\n\t\t`, sessionID, account, now.Add(1*time.Hour))\n\tnum, err := result.RowsAffected()\n\tif err != nil || num == 0 {\n\t\toutputErrorLog(\"セッション データ保存 失敗\", err)\n\t}\n\n\tlog.Println(\"セッション データ保存 成功\")\n\n\t// クッキーにセッション情報付与\n\tcookie := &http.Cookie{\n\t\tName: sessionIDName,\n\t\tValue: sessionID,\n\t}\n\thttp.SetCookie(rw, cookie)\n\n\t// HOME画面に遷移\n\thttp.Redirect(rw, request, \"/home\", http.StatusFound)\n}", "func UserLoginData(loginResponse http.ResponseWriter, loginRequest *http.Request) {\n\n\t//var userSessioneventID int\n\tdb := dbConn()\n\tdefer db.Close()\n\n\tif loginRequest.Method != \"POST\" {\n\t\tlog.Panic(\"Form data is not Post\")\n\t\thttp.Redirect(loginResponse, loginRequest, \"/\", http.StatusSeeOther)\n\t}\n\n\tcookie, cookieError := loginRequest.Cookie(\"login-cookie\") // returns cookie or an error\n\n\t// check incoming cookie with db\n\n\tif cookieError != nil {\n\t\tlog.Fatal(\"Cookies dont match\")\n\t} else {\n\t\tlog.Println(\"Got cookie : \", cookie)\n\t\tuserName := loginRequest.FormValue(\"username\")\n\t\tpassword := loginRequest.FormValue(\"password\")\n\t\t//rememberMe := loginRequest.FormValue(\"remember_me\")\n\t\t//fmt.Println(\"Rember me : \", rememberMe)\n\n\t\tuserLogin, eventID := userLoginProcessing(userName, password, cookie.Value)\n\n\t\tif userLogin {\n\t\t\t/*\n\t\t\t\tPassword matches, insert jwt and details to user_session table.\n\t\t\t\tUpdate initial loging table setting used=1 and next event id\n\t\t\t*/\n\t\t\tjwt, jwtErr := GenerateJWT(cookie.Value, 30) // for now its 30min session\n\n\t\t\tif jwtErr != nil {\n\t\t\t\tlog.Println(\"Can not generate jwt token\", jwtErr)\n\t\t\t}\n\n\t\t\thttp.SetCookie(loginResponse, &http.Cookie{\n\t\t\t\tName: \"user-cookie\",\n\t\t\t\tValue: jwt,\n\t\t\t\tPath: \"/home\",\n\t\t\t})\n\n\t\t\t/*\n\t\t\t\tInserting user_session and updating initial table\n\t\t\t*/\n\n\t\t\tloginSession, userSessionID := insertToUserSession(userName, jwt)\n\n\t\t\tif loginSession != true {\n\t\t\t\tlog.Println(\"Couldnt insert data to user session table\")\n\t\t\t}\n\n\t\t\tinitTable := updateInitialLogin(userSessionID, eventID)\n\n\t\t\tif initTable {\n\t\t\t\thttp.Redirect(loginResponse, loginRequest, \"/home\", http.StatusSeeOther)\n\t\t\t}\n\n\t\t} else { // password checking if-else\n\t\t\t// This is where I need to modify not to generate new token for login\n\t\t\thttp.Redirect(loginResponse, loginRequest, \"/\", http.StatusSeeOther)\n\t\t}\n\t} // cookie availble checking if-else\n\n}", "func login(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\n\t// Where authentication could be done\n\tif r.FormValue(\"code\")!=\"code\"{\n\t\tif r.FormValue(\"code\")==\"\"{\n\t\t\tsession.AddFlash(\"must enter a code\")\n\t\t}\n\t\tsession.AddFlash(\"the code was incorrect\")\n\t\terr:=session.Save(r,w)\n\t\tif err!=nil{\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\thttp.Redirect(w,r,\"/forbiden\",http.StatusFound)\n\t\treturn\n\t}\n\tusername:=r.FormValue(\"username\")\n\tpassword:=r.FormValue(\"password\")\n\tuser:=&user{\n\t\tUserName: username,\n\t\tPassword: password,\n\t\tAuthenticated: true,\n\t}\n\tsession.Values[\"user\"]=user\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/secret\",http.StatusFound)\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tif SessionManager.Exists(r.Context(), \"userid\") {\n\t\thttp.Redirect(w, r, \"/worker\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tif r.Method == \"GET\" {\n\t\tloginErr(w, \"\")\n\t\treturn\n\t}\n\n\tvar err error\n\t// POST\n\tvar exists bool\n\tvar user shared.User\n\n\tusername := r.PostFormValue(\"username\")\n\tpassword := []byte(r.PostFormValue(\"password\"))\n\n\tif exists, err = shared.Db.DoesUserExists(username); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !exists {\n\t\tloginErr(w, fmt.Sprintf(\"User %s does not exists!\", username))\n\t\treturn\n\t}\n\n\t// authenticate user\n\tif user, err = shared.Db.GetUserByName(username); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusUnauthorized)\n\t\treturn\n\t}\n\tif err = bcrypt.CompareHashAndPassword(user.Password, password); err != nil {\n\t\tloginErr(w, \"Incorrect password!\")\n\t\treturn\n\t}\n\n\t// create new session\n\tif err = SessionManager.RenewToken(r.Context()); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tSessionManager.Put(r.Context(), \"userid\", user.ID)\n\tSessionManager.RememberMe(r.Context(), true)\n\thttp.Redirect(w, r, \"/worker\", http.StatusSeeOther)\n}", "func (am AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error) {\n\t// create a new session value\n\tsessionValue := NewSessionID()\n\t// userID and sessionID are required\n\tsession = NewSession(userID, sessionValue)\n\tif am.SessionTimeoutProvider != nil {\n\t\tsession.ExpiresUTC = am.SessionTimeoutProvider(session)\n\t}\n\tsession.UserAgent = webutil.GetUserAgent(ctx.Request)\n\tsession.RemoteAddr = webutil.GetRemoteAddr(ctx.Request)\n\n\t// call the perist handler if one's been provided\n\tif am.PersistHandler != nil {\n\t\terr = am.PersistHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if we're in jwt mode, serialize the jwt.\n\tif am.SerializeSessionValueHandler != nil {\n\t\tsessionValue, err = am.SerializeSessionValueHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// inject cookies into the response\n\tam.injectCookie(ctx, am.CookieNameOrDefault(), sessionValue, session.ExpiresUTC)\n\treturn session, nil\n}", "func (u *User) Login() {\n\t// Update last login time\n\t// Add to logged-in user's list\n\t// etc ...\n\tu.authenticated = true\n}", "func TestLoginSuccess(t *testing.T) {\n\tvar handler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tfmt.Fprint(rw, `{\"session.id\":\"test\",\"status\":\"success\"}`)\n\t})\n\tts := httptest.NewServer(handler)\n\tdefer ts.Close()\n\tconf := Config\n\tconf.Url = ts.URL\n\n\treq := &AuthenticateReq{\n\t\tCommonConf: conf,\n\t}\n\tres, err := Authenticate(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif res.SessionId == \"\" {\n\t\tt.Fatal(\"No session id\")\n\t}\n\tt.Logf(\"%+v\", *res)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\t//Create Error messages\n\tmessages := make([]string, 0)\n\ttype MultiErrorMessages struct {\n\t\tMessages []string\n\t}\n\n\t// Get Formdata\n\tvar user = model.User{}\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Try Authentification\n\tuser, err := model.GetUserByUsername(username)\n\tif err != nil {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Benutzer existiert nicht.\")\n\n\t}\n\n\t//Encode Password to base64 byte array\n\tpasswordDB, _ := base64.StdEncoding.DecodeString(user.Password)\n\terr = bcrypt.CompareHashAndPassword(passwordDB, []byte(password))\n\tif err != nil {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Password falsch.\")\n\n\t}\n\n\t//Check if any Error Message was assembled\n\tif len(messages) != 0 {\n\n\t\tresponseModel := MultiErrorMessages{\n\t\t\tMessages: messages,\n\t\t}\n\n\t\tresponseJSON, err := json.Marshal(responseModel)\n\t\tif err != nil {\n\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write(responseJSON)\n\t\treturn\n\n\t}\n\n\t//Hash Username\n\tmd5HashInBytes := md5.Sum([]byte(user.Name))\n\tmd5HashedUsername := hex.EncodeToString(md5HashInBytes[:])\n\n\t//Create Session\n\tsession, err := store.Get(r, \"session\")\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"username\"] = username\n\tsession.Values[\"hashedusername\"] = md5HashedUsername\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\n\t}\n\n\t//Save Session\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t}\n\n\t//Redirect to ProfilePage\n\thttp.Redirect(w, r, \"/users?action=userdata\", http.StatusFound)\n}", "func gwLogin(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tvar err error\n\tvar hasCheckPass = false\n\tvar checker = s.AuthParamChecker\n\tvar authParam AuthParameter\n\tfor _, resolver := range s.AuthParamResolvers {\n\t\tauthParam = resolver.Resolve(c)\n\t\tif err = checker.Check(authParam); err == nil {\n\t\t\thasCheckPass = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasCheckPass {\n\t\tc.JSON(http.StatusBadRequest, s.RespBodyBuildFunc(http.StatusBadRequest, reqId, err, nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Login\n\tuser, err := s.AuthManager.Login(authParam)\n\tif err != nil || user.IsEmpty() {\n\t\tc.JSON(http.StatusNotFound, s.RespBodyBuildFunc(http.StatusNotFound, reqId, err.Error(), nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tsid, credential, ok := encryptSid(s, authParam)\n\tif !ok {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Create session ID fail.\", nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tif err := s.SessionStateManager.Save(sid, user); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Save session fail.\", err.Error()))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tvar userPerms []gin.H\n\tfor _, p := range user.Permissions {\n\t\tuserPerms = append(userPerms, gin.H{\n\t\t\t\"Key\": p.Key,\n\t\t\t\"Name\": p.Name,\n\t\t\t\"Desc\": p.Descriptor,\n\t\t})\n\t}\n\tcks := s.conf.Security.Auth.Cookie\n\texpiredAt := time.Duration(cks.MaxAge) * time.Second\n\tvar userRoles = gin.H{\n\t\t\"Id\": 0,\n\t\t\"name\": \"\",\n\t\t\"desc\": \"\",\n\t}\n\tpayload := gin.H{\n\t\t\"Credentials\": gin.H{\n\t\t\t\"Token\": credential,\n\t\t\t\"ExpiredAt\": time.Now().Add(expiredAt).Unix(),\n\t\t},\n\t\t\"Roles\": userRoles,\n\t\t\"Permissions\": userPerms,\n\t}\n\tbody := s.RespBodyBuildFunc(0, reqId, nil, payload)\n\tc.SetCookie(cks.Key, credential, cks.MaxAge, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n\tc.JSON(http.StatusOK, body)\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func verifyLogin(r *http.Request) bool {\n\tsession, err := store.Get(r, sessionName)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get session: %s\", err)\n\t\treturn false\n\t}\n\tif session.Values[\"LoggedIn\"] != \"yes\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func (d *Domus) Login() error {\n\tresp, err := d.Get(\"/Mobile/Login\", map[string]string{\n\t\t\"site_key\": string(d.config.SiteKey),\n\t\t\"user_key\": string(d.config.UserKey),\n\t\t\"password\": d.config.Password,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tvar n int\n\tbody := make([]byte, sessionKeyLen+10)\n\tif n, err = resp.Body.Read(body); n <= 0 {\n\t\tif err == io.EOF {\n\t\t\treturn errors.New(\"Login: invalid credentials (EOF received)\")\n\t\t}\n\t\treturn err\n\t}\n\tif n != sessionKeyLen {\n\t\treturn fmt.Errorf(\"Login: session key should be 40 bytes, is %d: %s\", n, body)\n\t}\n\n\td.setSessionKey(SessionKey(body[:sessionKeyLen]))\n\tif d.Debug {\n\t\tfmt.Printf(\"sessionKey: %s\\n\", d.SessionKey)\n\t}\n\treturn nil\n}", "func (ctx *TestContext) addAttempt(item, participant string) {\n\titemID := ctx.getReference(item)\n\tparticipantID := ctx.getReference(participant)\n\n\tctx.addInDatabase(\n\t\t`attempts`,\n\t\tstrconv.FormatInt(itemID, 10)+\",\"+strconv.FormatInt(participantID, 10),\n\t\tmap[string]interface{}{\n\t\t\t\"id\": itemID,\n\t\t\t\"participant_id\": participantID,\n\t\t},\n\t)\n}", "func (jbobject *TaskContext) AttemptNumber() int {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"attemptNumber\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}", "func loginHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\tcounter.Increment(\"login\")\n\n\t// get the requested username\n\tusername := req.FormValue(\"name\")\n\tif len(username) < 1 {\n\t\trenderBaseTemplate(res, \"login_error.html\", nil)\n\t} else {\n\t\terr := session.Create(res, username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t}\n}", "func Login(username, password string) error {\n\terr := validateCredentials(username, password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession := getSession(username, password)\n\tif session == nil {\n\t\tfmt.Println(\"Unable to get session\")\n\t\treturn errors.New(\"Unable to get session\")\n\t}\n\tfmt.Println(session)\n\n\tuser := models.User{Username: username, Session: session}\n\terr = models.SaveUser(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Runner) generateLogins() {\n\tr.logins.Generate()\n\t// Signal that we have no more passwords to try\n\tr.pwdOver <- struct{}{}\n\tclose(r.pwdOver)\n}", "func verifyLogin(req *restful.Request, resp *restful.Response ) bool {\n\tcookie, err := req.Request.Cookie(\"session-id\")\n\tif cookie.Value != \"\" {\n\t\t_, exists := sessions[cookie.Value]\n\t\tif !exists {\n\t\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t} else if err != nil {\n\t\tfmt.Println(err.Error())\n\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\treturn false\n\t} else {\n\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\treturn false\n\t}\n}", "func (s *Service) Login(c context.Context, app *model.App, subid int32, userid, rsaPwd string) (res *model.LoginToken, err error) {\n\tif userid == \"\" || rsaPwd == \"\" {\n\t\terr = ecode.UsernameOrPasswordErr\n\t\treturn\n\t}\n\tcache := true\n\ta, pwd, tsHash, err := s.checkUserData(c, userid, rsaPwd)\n\tif err != nil {\n\t\tif err == ecode.PasswordHashExpires || err == ecode.PasswordTooLeak {\n\t\t\treturn\n\t\t}\n\t\terr = nil\n\t} else {\n\t\tvar t *model.Perm\n\t\tif t, cache, err = s.saveToken(c, app.AppID, subid, a.Mid); err != nil {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tres = &model.LoginToken{\n\t\t\t\tMid: t.Mid,\n\t\t\t\tAccessKey: t.AccessToken,\n\t\t\t\tExpires: t.Expires,\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tif res, err = s.loginOrigin(c, userid, pwd, tsHash); err != nil {\n\t\treturn\n\t}\n\tif cache && res != nil {\n\t\ts.d.SetTokenCache(c, &model.Perm{\n\t\t\tMid: res.Mid,\n\t\t\tAppID: app.AppID,\n\t\t\tAppSubID: subid,\n\t\t\tAccessToken: res.AccessKey,\n\t\t\tCreateAt: res.Expires - _expireSeconds,\n\t\t\tExpires: res.Expires,\n\t\t})\n\t}\n\treturn\n}", "func (a *authSvc) Login(ctx context.Context, userID int64, secretKey string) error {\n\ttoken, err := createToken(userID, secretKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsaveErr := cacheAuth(userID, token)\n\tif saveErr != nil {\n\t\treturn saveErr\n\t}\n\tcookieAccess := getCookieAccess(ctx)\n\tcookieAccess.SetToken(\"jwtAccess\", token.AccessToken, time.Unix(token.AtExpires, 0))\n\tcookieAccess.SetToken(\"jwtRefresh\", token.RefreshToken, time.Unix(token.RtExpires, 0))\n\treturn nil\n}", "func (client *AMIClient) Login(username, password string) error {\n\tresponse, err := client.Action(\"Login\", Params{\"Username\": username, \"Secret\": password}, time.Second*5)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif (*response).Status == \"Error\" {\n\t\treturn errors.New((*response).Params[\"Message\"])\n\t}\n\tclient.loggedIn = true\n\tclient.amiUser = username\n\tclient.amiPass = password\n\treturn nil\n}", "func (c *Client) Login(ctx context.Context, user *url.Userinfo) error {\n\treq := c.Resource(internal.SessionPath).Request(http.MethodPost)\n\n\treq.Header.Set(internal.UseHeaderAuthn, \"true\")\n\n\tif user != nil {\n\t\tif password, ok := user.Password(); ok {\n\t\t\treq.SetBasicAuth(user.Username(), password)\n\t\t}\n\t}\n\n\tvar id string\n\terr := c.Do(ctx, req, &id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.SessionID(id)\n\n\treturn nil\n}" ]
[ "0.68752503", "0.68752503", "0.6131486", "0.58911663", "0.57096565", "0.5694199", "0.5596062", "0.5593208", "0.55727524", "0.55451465", "0.5532529", "0.54767036", "0.54591733", "0.54341775", "0.5418249", "0.5364072", "0.5343915", "0.53298", "0.5306828", "0.53017807", "0.52956295", "0.5281229", "0.5247843", "0.52329713", "0.52295375", "0.5221185", "0.5220602", "0.52123535", "0.52096134", "0.51833916", "0.5182613", "0.51762044", "0.51702416", "0.5162009", "0.5159083", "0.51488405", "0.5143398", "0.51390445", "0.5129555", "0.51064295", "0.5102557", "0.5098914", "0.5098084", "0.5085595", "0.50854725", "0.50738233", "0.5071671", "0.50693375", "0.503637", "0.5029501", "0.5017336", "0.49994838", "0.49956873", "0.49951315", "0.49936816", "0.49919567", "0.49901685", "0.49777117", "0.4974905", "0.497358", "0.49633697", "0.49596915", "0.49501872", "0.4944851", "0.49399623", "0.49358076", "0.49259657", "0.49255243", "0.49245238", "0.4922322", "0.49216282", "0.49164465", "0.4912994", "0.49081245", "0.49068078", "0.48961034", "0.48881334", "0.48857012", "0.4879895", "0.4876904", "0.48741788", "0.48728678", "0.48675472", "0.4862291", "0.48536018", "0.4852463", "0.4850446", "0.48449597", "0.48433957", "0.483824", "0.48378018", "0.48350096", "0.48276785", "0.48230723", "0.4821174", "0.48192713", "0.48070323", "0.48053446", "0.4804662", "0.48037615" ]
0.8348744
0
jdecrypt private function to "decrypt" password
частная функция jdecrypt для "расшифровки" пароля
func jdecrypt( stCuen string , stPass string)(stRes string,err error){ var stEnc []byte stEnc, err = base64.StdEncoding.DecodeString(stPass) if err != nil { log.Println("jdecrypt ", stPass, err ) } else{ lon := len(stEnc) lan := len(stCuen) if lon > lan { stCuen = PadRight(stCuen, " ", lon) } rCuen := []byte(stCuen) rEnc := []byte(stEnc) rRes := make([]byte, lon) for i := 0; i < lon; i++ { rRes[i] = rCuen[i] ^ rEnc[i] } stRes = string(rRes) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DecryptJasypt(encrypted []byte, password string) ([]byte, error) {\n\tif len(encrypted) < des.BlockSize {\n\t\treturn nil, fmt.Errorf(\"Invalid encrypted text. Text length than block size.\")\n\t}\n\n\tsalt := encrypted[:des.BlockSize]\n\tct := encrypted[des.BlockSize:]\n\n\tkey, err := PBKDF1MD5([]byte(password), salt, 1000, des.BlockSize*2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv := key[des.BlockSize:]\n\tkey = key[:des.BlockSize]\n\n\tb, err := des.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdst := make([]byte, len(ct))\n\tbm := cipher.NewCBCDecrypter(b, iv)\n\tbm.CryptBlocks(dst, ct)\n\n\t// Remove any padding\n\tpad := int(dst[len(dst)-1])\n\tdst = dst[:len(dst)-pad]\n\n\treturn dst, nil\n}", "func decrypt(password []byte, encrypted []byte) ([]byte, error) {\n\tsalt := encrypted[:SaltBytes]\n\tencrypted = encrypted[SaltBytes:]\n\tkey := makeKey(password, salt)\n\n\tblock, err := aes.NewCipher(key)\n\n\tif err != nil {\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tif len(encrypted) < aes.BlockSize {\n\t\t// Cipher is too short\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tiv := encrypted[:aes.BlockSize]\n\tencrypted = encrypted[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\tstream.XORKeyStream(encrypted, encrypted)\n\n\treturn encrypted, nil\n}", "func CipherDecodeJNI(s *C.char, ts C.long) *C.char {\n\ttm := time.Unix(int64(ts), 0)\n\tdec := C.GoString(s)\n\n\tdecoder := dhcrypto.NewCipherDecode([]byte(key), tm)\n\tbytes, e := decoder.Decode(dec)\n\tif e != nil {\n\t\tfmt.Println(\"error:\", e)\n\t\treturn nil\n\t}\n\tstr := string(bytes)\n\tfmt.Println(\"decoded:\", str)\n\treturn C.CString(str)\n}", "func Initdecrypt(hsecretfile string, mkeyfile string) []byte {\n\n\thudsonsecret, err := ioutil.ReadFile(hsecretfile)\n\tif err != nil {\n\t\tfmt.Printf(\"error reading hudson.util.Secret file '%s':%s\\n\", hsecretfile, err)\n\t\tos.Exit(1)\n\t}\n\n\tmasterkey, err := ioutil.ReadFile(mkeyfile)\n\tif err != nil {\n\t\tfmt.Printf(\"error reading master.key file '%s':%s\\n\", mkeyfile, err)\n\t\tos.Exit(1)\n\t}\n\n\tk, err := Decryptmasterkey(string(masterkey), hudsonsecret)\n\tif err != nil {\n\t\tfmt.Println(\"Error decrypting keys... \", err)\n\t\tos.Exit(1)\n\t}\n\treturn k\n}", "func __decryptString(key []byte, enc string) string {\n\tdata, err := base64.StdEncoding.DecodeString(enc)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsaltHeader := data[:aes.BlockSize]\n\tif string(saltHeader[:7]) != openSSLSaltHeader {\n\t\tlog.Fatal(\"String doesn't appear to have been encrypted with OpenSSL\")\n\t}\n\tsalt := saltHeader[8:]\n\tcreds := __extractOpenSSLCreds(key, salt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn string(__decrypt(creds.key, creds.iv, data))\n}", "func Decrypt(key []byte) []byte {\n\tdecryptedbin, err := dpapi.DecryptBytes(key)\n\terror_log.Check(err, \"Unprotect String with DPAPI\", \"decrypter\")\n\treturn decryptedbin\n}", "func decrypt(_message string, _rotors [3]int, _ref int, _key [3]int) string {\n\tvar builder strings.Builder\n\n\tfor _, char := range _message {\n\t\t_key = rotorsIncr(_key, _rotors)\n\t\tvar rd = (byte(rotors[_rotors[2]][(byte(char)-65+byte(_key[2])+26)%26]) - 65 + 26 - byte(_key[2])) % 26\n\t\tvar rm = (byte(rotors[_rotors[1]][(rd+byte(_key[1])+26)%26]) - 65 + 26 - byte(_key[1])) % 26\n\t\tvar rg = (byte(rotors[_rotors[0]][(rm+byte(_key[0])+26)%26]) - 65 + 26 - byte(_key[0])) % 26\n\t\tvar r = byte(rotors[_ref][rg] - 65)\n\n\t\tvar rg2 = (byte(rotorsInv[_rotors[0]][(r+byte(_key[0])+26)%26]) - 65 + 26 - byte(_key[0])) % 26\n\t\tvar rm2 = (byte(rotorsInv[_rotors[1]][(rg2+byte(_key[1])+26)%26]) - 65 + 26 - byte(_key[1])) % 26\n\t\tvar rd2 = (byte(rotorsInv[_rotors[2]][(rm2+byte(_key[2])+26)%26]) - 65 + 26 - byte(_key[2])) % 26\n\t\tbuilder.WriteRune(rune(rd2 + 65))\n\t}\n\n\treturn builder.String()\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext is too short.\")\n\t}\n\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCBCDecrypter(block, iv)\n\tcfb.CryptBlocks(text, text)//.XORKeyStream(test, test)\n\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (d Decryptor) Decrypt(bs []byte) ([]byte, error) {\n\tswitch d.Algorithm {\n\tcase \"\", AlgoPBEWithMD5AndDES:\n\t\tif d.Password == \"\" {\n\t\t\treturn nil, ErrEmptyPassword\n\t\t}\n\t\treturn DecryptJasypt(bs, d.Password)\n\t}\n\treturn nil, fmt.Errorf(\"unknown jasypt algorithm\")\n}", "func TestDecodePassword(t *testing.T) {\n\tt.Parallel()\n\n\tpasswordDecoded, err := junosdecode.Decode(junWordCoded)\n\tif err != nil {\n\t\tt.Errorf(\"error on decode %v\", err)\n\t}\n\tif passwordDecoded != junWordDecoded {\n\t\tt.Errorf(\"decode password failed\")\n\t}\n}", "func decryptJWE(jweString string, key []byte) (messages.Base, error) {\n\tif core.Debug {\n\t\tmessage(\"debug\", \"Entering into http2.DecryptJWE function\")\n\t\tmessage(\"debug\", fmt.Sprintf(\"Input JWE String: %s\", jweString))\n\t}\n\n\tvar m messages.Base\n\n\t// Parse JWE string back into JSONWebEncryption\n\tjwe, errObject := jose.ParseEncrypted(jweString)\n\tif errObject != nil {\n\t\treturn m, fmt.Errorf(\"there was an error parseing the JWE string into a JSONWebEncryption object:\\r\\n%s\", errObject)\n\t}\n\n\tif core.Debug {\n\t\tmessage(\"debug\", fmt.Sprintf(\"Parsed JWE:\\r\\n%+v\", jwe))\n\t}\n\n\t// Decrypt the JWE\n\tjweMessage, errDecrypt := jwe.Decrypt(key)\n\tif errDecrypt != nil {\n\t\treturn m, fmt.Errorf(\"there was an error decrypting the JWE:\\r\\n%s\", errDecrypt.Error())\n\t}\n\n\t// Decode the JWE payload into a messages.Base struct\n\terrDecode := gob.NewDecoder(bytes.NewReader(jweMessage)).Decode(&m)\n\tif errDecode != nil {\n\t\treturn m, fmt.Errorf(\"there was an error decoding JWE payload message sent by an agent:\\r\\n%s\", errDecode.Error())\n\t}\n\n\tif core.Debug {\n\t\tmessage(\"debug\", \"Leaving http2.DecryptJWE function without error\")\n\t\tmessage(\"debug\", fmt.Sprintf(\"Returning message base: %+v\", m))\n\t}\n\treturn m, nil\n}", "func passwordKey() []byte {\n\ta0 := []byte{0x90, 0x19, 0x14, 0xa0, 0x94, 0x23, 0xb1, 0xa4, 0x98, 0x27, 0xb5, 0xa8, 0xd3, 0x31, 0xb9, 0xe2}\n\ta1 := []byte{0x10, 0x91, 0x20, 0x15, 0xa1, 0x95, 0x24, 0xb2, 0xa5, 0x99, 0x28, 0xb6, 0xa9, 0xd4, 0x32, 0xf1}\n\ta2 := []byte{0x12, 0x11, 0x92, 0x21, 0x16, 0xa2, 0x96, 0x25, 0xb3, 0xa6, 0xd1, 0x29, 0xb7, 0xe0, 0xd5, 0x33}\n\ta3 := []byte{0x18, 0x13, 0x12, 0x93, 0x22, 0x17, 0xa3, 0x97, 0x26, 0xb4, 0xa7, 0xd2, 0x30, 0xb8, 0xe1, 0xd6}\n\n\tresult := make([]byte, 16)\n\tfor i := 0; i < len(result); i++ {\n\t\tresult[i] = (((a0[i] & a1[i]) ^ a2[i]) | a3[i])\n\t}\n\n\treturn result\n}", "func Unwrap(kek []byte, in []byte) []byte {\n\t// TODO add a few more checks..\n\tif len(kek) < 16 || len(in)%8 != 0 {\n\t\treturn nil\n\t}\n\n\t// 1) Initialize variables.\n\t//\n\t// Set A = C[0]\n\t// For i = 1 to n\n\t// R[i] = C[i]\n\tvar A, B, R []byte\n\tA = make([]byte, 8)\n\tB = make([]byte, 16)\n\tR = make([]byte, len(in))\n\n\tcopy(A, in)\n\tcopy(R, in)\n\n\tcipher, err := aes.NewCipher(kek)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// 2) Compute intermediate values.\n\t//\n\t// For j = 5 to 0\n\t// For i = n to 1\n\t// B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i\n\t// A = MSB(64, B)\n\t// R[i] = LSB(64, B)\n\tn := len(in)/8 - 1\n\tfor j := 5; j >= 0; j-- {\n\t\tfor i := n; i > 0; i-- {\n\t\t\t// OPERATION\n\n\t\t\tcopy(B, A)\n\t\t\tcopy(B[8:], R[i*8:])\n\t\t\tt := uint64(n*j + i)\n\t\t\tif t > 255 {\n\t\t\t\tpanic(\"IMPLEMENT\")\n\t\t\t}\n\t\t\tB[7] ^= uint8(t & 0xff)\n\t\t\tcipher.Decrypt(B, B)\n\t\t\tcopy(A, B)\n\t\t\tcopy(R[i*8:], B[8:])\n\t\t}\n\t}\n\n\t// 3) Output results.\n\t//\n\t// If A is an appropriate initial value (see 2.2.3),\n\t// Then\n\t// For i = 1 to n\n\t// P[i] = R[i]\n\t// Else\n\t// Return an error\n\tif !bytes.Equal(A, rfc3394iv) {\n\t\treturn nil\n\t}\n\treturn R[8:]\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tcfb.XORKeyStream(text, text)\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func deobfuscate(in string, key []byte) ([]byte, error) {\n\tif len(key) == 0 {\n\t\treturn nil, errors.New(\"key cannot be zero length\")\n\t}\n\n\tdecoded, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := make([]byte, len(decoded))\n\tfor i, c := range decoded {\n\t\tout[i] = c ^ key[i%len(key)]\n\t}\n\n\treturn out, nil\n}", "func decrypt(encrypted []byte, key string) (string, error) {\n\t_, size, err := iv(cipherRijndael128, modeCBC)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ten := string(encrypted)\n\tif len(en) <= size {\n\t\treturn \"\", errors.New(\"bad attempt at decryption\")\n\t}\n\n\tiv := en[0:size]\n\tif len(iv) != size {\n\t\treturn \"\", fmt.Errorf(\"encrypted value iv length incompatible match to cipher type: received %d\", len(iv))\n\t}\n\n\td, err := mcrypt.Decrypt(parseKey(key), []byte(iv), []byte(en[size:]), cipherRijndael128, modeCBC)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(d), nil\n}", "func getUnscrambledPassword(password string, scrambleKey string) string {\n\tdecodedString, _ := base64.StdEncoding.DecodeString(password)\n\tunscrambledPassword := xorString(string(decodedString), scrambleKey)\n\treturn unscrambledPassword\n}", "func decrypt(value []byte, key Key) ([]byte, error) {\n\tenc, err := b64.StdEncoding.DecodeString(string(value))\n\tif err != nil {\n\t\treturn value, err\n\t}\n\n\tnsize := key.cipherObj.NonceSize()\n\tnonce, ciphertext := enc[:nsize], enc[nsize:]\n\n\treturn key.cipherObj.Open(nil, nonce, ciphertext, nil)\n}", "func makeRemminaDecrypter(base64secret string) func(string) string {\n\t//decode the secret\n\tsecret, err := base64.StdEncoding.DecodeString(base64secret)\n\tif err != nil {\n\t\tlog.Fatal(\"Base 64 decoding failed:\", err)\n\t}\n\tif len(secret) != 32 {\n\t\tlog.Fatal(\"the secret is not 32 bytes long\")\n\t}\n\t//the key is the 24 first bits of the secret\n\tkey := secret[:24]\n\t//3DES cipher\n\tblock, err := des.NewTripleDESCipher(key)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed creating the 3Des cipher block\", err)\n\t}\n\t//the rest of the secret is the iv\n\tiv := secret[24:]\n\tdecrypter := cipher.NewCBCDecrypter(block, iv)\n\n\treturn func(encodedEncryptedPassword string) string {\n\t\tencryptedPassword, err := base64.StdEncoding.DecodeString(encodedEncryptedPassword)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Base 64 decoding failed:\", err)\n\t\t}\n\t\t//in place decryption\n\t\tdecrypter.CryptBlocks(encryptedPassword, encryptedPassword)\n\t\treturn string(encryptedPassword)\n\t}\n}", "func decryptJWEToken(token string) ([]byte, error) {\n\te, err := jose.ParseEncrypted(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpayload, err := e.Decrypt(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn decodeJWSToken(string(payload))\n}", "func PwDecrypt(encrypted, byteSecret []byte) (string, error) {\n\n\tvar secretKey [32]byte\n\tcopy(secretKey[:], byteSecret)\n\n\tvar decryptNonce [24]byte\n\tcopy(decryptNonce[:], encrypted[:24])\n\tdecrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey)\n\tif !ok {\n\t\treturn \"\", errors.New(\"PwDecrypt(secretbox.Open)\")\n\t}\n\n\treturn string(decrypted), nil\n}", "func decrypt(encodedData string, secret []byte) (string, error) {\r\n\tencryptData, err := base64.URLEncoding.DecodeString(encodedData)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonceSize := aead.NonceSize()\r\n\tif len(encryptData) < nonceSize {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce, cipherText := encryptData[:nonceSize], encryptData[nonceSize:]\r\n\tplainData, err := aead.Open(nil, nonce, cipherText, nil)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn string(plainData), nil\r\n}", "func (q MockService) Decrypt(encKey string, envVal string) (result string, err error) {\n\tresult = \"Q_Qesb1Z2hA7H94iXu3_buJeQ7416\"\n\terr = nil\n\n\treturn result, err\n}", "func (cfg *Config) Decrypt(pw, id string) ([]byte, error) {\n // load the encrypted data entry from disk\n byteArr, err := ioutil.ReadFile(cfg.getOutFilePath(id))\n if err != nil {\n return nil, fmt.Errorf(\"failed to read the encrypted file: %v\", err)\n }\n encFileJSON := &encryptedFileJSON{}\n if err = json.Unmarshal(byteArr, encFileJSON); err != nil {\n return nil, fmt.Errorf(\"failed to parse the encrypted data file: %v\", err)\n }\n\n // decrypt the private key and load it\n privPEM, err := x509.DecryptPEMBlock(cfg.privPem, []byte(pw))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt RSA private key; bad password? : %v\", err)\n }\n privKey, _ := x509.ParsePKCS1PrivateKey(privPEM)\n\n // use the private key to decrypt the ECEK\n ecekBytes, _ := base64.StdEncoding.DecodeString(encFileJSON.ECEK)\n cek, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, ecekBytes, make([]byte, 0))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt CEK: %v\", err)\n }\n\n // use the CEK to decrypt the content\n cipherBlock, err := aes.NewCipher(cek)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create AES cipher block: %v\", err)\n }\n gcm, err := cipher.NewGCM(cipherBlock)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create GCM cipher: %v\", err)\n }\n nonce, _ := base64.StdEncoding.DecodeString(encFileJSON.Nonce)\n cipherText, _ := base64.StdEncoding.DecodeString(encFileJSON.CipherText)\n plainText, err := gcm.Open(nil, nonce, cipherText, nil)\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt the file content: %v\", err)\n }\n\n // delete the encrypted content and return the plaintext\n if err = os.Remove(cfg.getOutFilePath(id)); err != nil {\n return plainText, fmt.Errorf(\"failed to delete the encrypted file: %v\", err)\n }\n return plainText, nil\n}", "func Example() {\n\tencryptedValue, _ := Encrypt(\"password123\", \"secret\")\n\tdecryptedValue, _ := Decrypt(\"password123\", encryptedValue)\n\tfmt.Println(string(decryptedValue))\n\t// Output: secret\n}", "func DecryptString(to_decrypt string, key_string string) string {\n\tciphertext := DecodeBase64(to_decrypt)\n\tkey := DecodeBase64(key_string)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: DecryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make an empty byte array to fill\n\tplaintext := make([]byte, len(ciphertext))\n\t// decrypt the ciphertext\n\tc.XORKeyStream(plaintext, ciphertext)\n return string(plaintext)\n}", "func (c *Client) DecryptPassword() (string, error) {\n\tif len(c.Password) == 0 || len(c.HandleOrEmail) == 0 {\n\t\treturn \"\", errors.New(\"You have to configure your handle and password by `cf config`\")\n\t}\n\treturn decrypt(c.HandleOrEmail, c.Password)\n}", "func TestKeyEncryptDecrypt(t *testing.T) {\n\tkeyjson, err := ioutil.ReadFile(\"testdata/bytom-very-light-scrypt.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpassword := \"bytomtest\"\n\talias := \"verylight\"\n\t// Do a few rounds of decryption and encryption\n\tfor i := 0; i < 3; i++ {\n\t\t// Try a bad password first\n\n\t\tif _, err := DecryptKey(keyjson, password+\"bad\"); err == nil {\n\t\t\tt.Errorf(\"test %d: json key decrypted with bad password\", i)\n\t\t}\n\n\t\t// Decrypt with the correct password\n\t\tkey, err := DecryptKey(keyjson, password)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"test %d: json key failed to decrypt: %v\", i, err)\n\t\t}\n\t\tif key.Alias != alias {\n\t\t\tt.Errorf(\"test %d: key address mismatch: have %x, want %x\", i, key.Alias, alias)\n\t\t}\n\n\t\t// Recrypt with a new password and start over\n\t\t//password += \"new data appended\"\n\t\tif _, err = EncryptKey(key, password, veryLightScryptN, veryLightScryptP); err != nil {\n\t\t\tt.Errorf(\"test %d: failed to recrypt key %v\", i, err)\n\t\t}\n\t}\n}", "func Decrypt(message, password string) (string, error) {\n\tvar key [32]byte\n\tcopy(key[:], password)\n\tdecryptedMessage, err := DecryptBytes([]byte(message), key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decryptedMessage), nil\n}", "func Decrypt(k []byte, crypted string) (string, error) {\n\tif crypted == \"\" || len(crypted) < 8 {\n\t\treturn \"\", nil\n\t}\n\n\tcryptedbytes, err := base64.StdEncoding.DecodeString(crypted[1 : len(crypted)-1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tivlength := (cryptedbytes[4] & 0xff)\n\tif int(ivlength) > len(cryptedbytes) {\n\t\treturn \"\", errors.New(\"invalid encrypted string\")\n\t}\n\n\tcryptedbytes = cryptedbytes[1:] //Strip the version\n\tcryptedbytes = cryptedbytes[4:] //Strip the iv length\n\tcryptedbytes = cryptedbytes[4:] //Strip the data length\n\n\tiv := cryptedbytes[:ivlength]\n\tcryptedbytes = cryptedbytes[ivlength:]\n\n\tblock, err := aes.NewCipher(k)\n\tif err != nil {\n\t\tfmt.Println(\"Error creating new cipher\", err)\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes) < aes.BlockSize {\n\t\tfmt.Println(\"Ciphertext too short\")\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes)%aes.BlockSize != 0 {\n\t\tfmt.Println(\"Ciphertext is not a multiple of the block size\")\n\t\treturn \"\", err\n\t}\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(cryptedbytes, cryptedbytes)\n\n\tdecrypted := strings.TrimSpace(string(cryptedbytes))\n\tdecrypted = strings.TrimFunc(decrypted, func(r rune) bool {\n\t\treturn !unicode.IsGraphic(r)\n\t})\n\treturn decrypted, nil\n}", "func Decrypt(c []byte, q Poracle, l *log.Logger) (string, error) {\n\tn := len(c) / CipherBlockLen\n\tif n < 2 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\tif len(c)%CipherBlockLen != 0 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\t// The clear text have the same length as the cyphertext - 1\n\t// (the IV).\n\tvar m []byte\n\tfor i := 1; i < n; i++ {\n\t\tc0 := c[(i-1)*CipherBlockLen : CipherBlockLen*(i-1)+CipherBlockLen]\n\t\tc1 := c[CipherBlockLen*i : (CipherBlockLen*i)+CipherBlockLen]\n\t\tl.Printf(\"\\ndecripting block %d of %d\", i, n)\n\t\tmi, err := decryptBlock(c0, c1, q, l)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm = append(m, mi...)\n\t}\n\treturn string(m), nil\n}", "func decrypt(ciphertext []byte, IV []byte) []byte {\n plaintext, err := aead.Open(nil, IV, ciphertext, nil)\n if err != nil {\n fmt.Fprintln(os.Stderr, \"Error with AES decryption: \" + err.Error())\n os.Exit(1)\n }\n\n return plaintext\n}", "func decrypt(data, iv, key []byte) (card_json []byte) {\n block, err := aes.NewCipher(key)\n check(err)\n\n if len(data) % aes.BlockSize != 0 {\n panic(\"ciphertext is not a multiple of the block size\")\n }\n\n mode := cipher.NewCBCDecrypter(block, iv)\n mode.CryptBlocks(data, data)\n\n pad_bytes := int(data[len(data)-1])\n card_json = data[:len(data)-pad_bytes]\n\n return\n}", "func (my *Conn) encryptedPasswd() (out []byte) {\n\t// Convert password to byte array\n\tpassbytes := []byte(my.passwd)\n\t// stage1_hash = SHA1(password)\n\t// SHA1 encode\n\tcrypt := sha1.New()\n\tcrypt.Write(passbytes)\n\tstg1Hash := crypt.Sum(nil)\n\t// token = SHA1(SHA1(stage1_hash), scramble) XOR stage1_hash\n\t// SHA1 encode again\n\tcrypt.Reset()\n\tcrypt.Write(stg1Hash)\n\tstg2Hash := crypt.Sum(nil)\n\t// SHA1 2nd hash and scramble\n\tcrypt.Reset()\n\tcrypt.Write(my.info.scramble)\n\tcrypt.Write(stg2Hash)\n\tstg3Hash := crypt.Sum(nil)\n\t// XOR with first hash\n\tout = make([]byte, len(my.info.scramble))\n\tfor ii := range my.info.scramble {\n\t\tout[ii] = stg3Hash[ii] ^ stg1Hash[ii]\n\t}\n\treturn\n}", "func (m *TripleDesCBC) Decrypt(key, s string) (string, error) {\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbsd, err := base64.StdEncoding.DecodeString(strings.Replace(s, kpassSign, \"\", -1))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tacd, err := gocrypto.TripleDesCBCDecrypt(bsd)\n\tif !strings.Contains(string(acd), kpassSign) {\n\t\treturn \"\", errors.New(\"desKey is error\")\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Replace(string(acd), kpassSign, \"\", -1), err\n}", "func decrypt(encoded string, key []byte) (string, error) {\n\tcipherText, err := base64.URLEncoding.DecodeString(encoded)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tif len(cipherText) < aes.BlockSize {\n\t\terr = errors.New(\"ciphertext block size is too short\")\n\t\treturn encoded, err\n\t}\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(cipherText, cipherText)\n\tdecoded := string(cipherText)\n\n\t// By design decrypt with incorrect key must end up with the value\n\tif strings.Index(decoded, anchor) != 0 {\n\t\treturn encoded, nil\n\t}\n\n\tdecoded = strings.Replace(decoded, anchor, \"\", 1) // remove anchor from string\n\treturn decoded, nil\n}", "func decrypt(cipherData []byte, key []byte) []byte {\r\n var errMsg string\r\n\r\n\tc, err := aes.NewCipher(key)\r\n if err != nil {\r\n errMsg += \"aes.NewCipher: \" + err.Error()\r\n }\r\n\r\n gcm, err := cipher.NewGCM(c)\r\n if err != nil {\r\n errMsg += \"cipher.NewGCM: \" + err.Error()\r\n }\r\n\r\n nonceSize := gcm.NonceSize()\r\n if len(cipherData) < nonceSize {\r\n errMsg += \"cipherData is less than nonceSize\"\r\n }\r\n\r\n nonce, ciphertext := cipherData[:nonceSize], cipherData[nonceSize:]\r\n plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\r\n if err != nil {\r\n errMsg += \"gcm.Open: \" + err.Error()\r\n }\r\n\r\n // If an error occured, return that error as a byte array instead of the decrypted message\r\n if len(errMsg) > 0 {\r\n return []byte(errMsg)\r\n }\r\n\r\n\treturn []byte(plaintext)\r\n}", "func decryptAES(keyByte []byte, cipherText string, additionalData string) string {\n\n\ts := \"START decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\tcipherTextByte, _ := hex.DecodeString(cipherText)\n\tadditionalDataByte := []byte(additionalData)\n\n\t// GET CIPHER BLOCK USING KEY\n\tblock, err := aes.NewCipher(keyByte)\n\tcheckErr(err)\n\n\t// GET GCM BLOCK\n\tgcm, err := cipher.NewGCM(block)\n\tcheckErr(err)\n\n\t// EXTRACT NONCE FROM cipherTextByte\n\t// Because I put it there\n\tnonceSize := gcm.NonceSize()\n\tnonce, cipherTextByte := cipherTextByte[:nonceSize], cipherTextByte[nonceSize:]\n\n\t// DECRYPT DATA\n\tplainTextByte, err := gcm.Open(nil, nonce, cipherTextByte, additionalDataByte)\n\tcheckErr(err)\n\n\ts = \"END decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\t// RETURN STRING\n\tplainText := string(plainTextByte[:])\n\treturn plainText\n\n}", "func decrypt(c []byte, k key) (msg []byte, err error) {\n\t// split the nonce and the cipher\n\tnonce, c, err := splitNonceCipher(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decrypt the message\n\tmsg, ok := box.OpenAfterPrecomputation(msg, c, nonce, k)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Cannot decrypt, malformed message\")\n\t}\n\treturn msg, nil\n}", "func decrypt(cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func encryptDecryptXor(input string, key byte) (output string) {\n for i := 0; i < len(input); i++ {\n output += string(input[i] ^ key)\n }\n return output\n}", "func (store *SessionCookieStore) decrypt(buf []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher([]byte(store.SecretKey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taead, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiv := buf[:aead.NonceSize()]\n\tdecrypted := buf[aead.NonceSize():]\n\tif _, err := aead.Open(decrypted[:0], iv, decrypted, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn decrypted, nil\n}", "func (d *Decrypter) Decrypt(ciphertext []byte) ([]byte, error) {\n\tif ciphertext == nil {\n\t\treturn nil, fmt.Errorf(\"invalid ciphertext: nil\")\n\t}\n\n\tvar salt [saltLen]byte\n\tcopy(salt[:], ciphertext[:saltLen])\n\n\t// Check our cache to see if we have already calculated the AES key\n\t// as it's expensive.\n\tcipher, ok := d.ciphers[salt]\n\tif !ok {\n\t\taesKey, e := aesKeyFromPasswordAndSalt(d.password, salt[:])\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\tdefer func(aesKey []byte) {\n\t\t\tfor i := range aesKey {\n\t\t\t\taesKey[i] = 0\n\t\t\t}\n\t\t}(aesKey)\n\n\t\tcipher, e = xts.NewCipher(aes.NewCipher, aesKey)\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\td.ciphers[salt] = cipher\n\t}\n\n\tciphertext = ciphertext[saltLen:]\n\n\tplaintext := make([]byte, len(ciphertext))\n\tcipher.Decrypt(plaintext, ciphertext, xtsSectorNum)\n\ti := 0\n\n\t// Check magic bytes\n\tif bytes.Compare(plaintext[i:i+len(magicBytes)], magicBytes) != 0 {\n\t\treturn nil, fmt.Errorf(\"bad password\")\n\t}\n\ti += len(magicBytes)\n\n\t// Check version\n\tif plaintext[i] > version {\n\t\treturn nil, fmt.Errorf(\"unsupported version: we are version '%d' and the content is version '%d'\", version, plaintext[i])\n\t}\n\ti++\n\n\t// Jump over padding\n\tpaddingLen := plaintext[i]\n\ti += 1 + int(paddingLen)\n\n\tstoredDigest := plaintext[i : i+sha512DigestLen]\n\ti += sha512DigestLen\n\n\tplaintext = plaintext[i:]\n\n\trealDigest := sha512.Sum512(plaintext)\n\tif bytes.Compare(storedDigest, realDigest[:]) != 0 {\n\t\treturn nil, fmt.Errorf(\"message authentication code mismatch: data is corrupted and may have been tampered with\")\n\t}\n\n\treturn plaintext, nil\n}", "func Decrypt(key, iv []byte, b64ciphertext string) []byte {\n if len(key) != 32 {\n log.Fatal(\"Key length must be 32 bytes\")\n }\n if len(iv) != 12 {\n log.Fatal(\"initialization vector must be 12 bytes\")\n }\n cipherblob, _ := base64.StdEncoding.DecodeString(b64ciphertext)\n ciphertext := []byte(cipherblob)\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Fatal(err)\n }\n gcm, _ := cipher.NewGCM(block)\n plaintext, _ := gcm.Open(nil, iv, ciphertext, nil)\n return []byte(plaintext)\n}", "func (s *Session) decrypt(payload, priv []byte) []byte {\n\tb := &bytes.Buffer{}\n\tbinary.Write(b, binary.BigEndian, s.engineBoots)\n\tbinary.Write(b, binary.BigEndian, s.engineTime)\n\n\tiv := append(b.Bytes(), priv...)\n\n\tdecrypted := make([]byte, len(payload))\n\n\taesBlockDecrypter, err := aes.NewCipher(s.privKey)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\taesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)\n\taesDecrypter.XORKeyStream(decrypted, payload)\n\n\treturn decrypted\n}", "func decrypt(aesKey []byte, cipherText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Decrypt(cipherText, associatedData)\n}", "func TestEncryptionDecryptByPassPhraseWithUnmatchedPass(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\tciphertextStr, _ := encryptByPassPhrase(passPhrase, plaintext)\n\n\tpassPhrase2 := \"1234\"\n\tplaintext2, err := decryptByPassPhrase(passPhrase2, ciphertextStr)\n\n\tassert.NotEqual(t, plaintext, plaintext2)\n\tassert.Equal(t, nil, err)\n}", "func SQLDecode(str string, password string) (string, error) {\n\ttrace_util_0.Count(_crypt_00000, 18)\n\tvar sc sqlCrypt\n\n\tstrByte := []byte(str)\n\tpasswdByte := []byte(password)\n\n\tsc.init(passwdByte, len(passwdByte))\n\tsc.decode(strByte, len(strByte))\n\n\treturn string(strByte), nil\n}", "func Decrypt(data, password []byte, d interface{}) error {\n\tif len(data) < 8 {\n\t\treturn ErrNoVersion\n\t}\n\n\tver, data := data[:8], data[8:]\n\tswitch binary.LittleEndian.Uint64(ver) {\n\tcase 1:\n\t\tbreak\n\tdefault:\n\t\treturn ErrVersionInvalid\n\t}\n\n\tif len(data) < saltSize {\n\t\treturn ErrNoSalt\n\t}\n\n\tsalt, data := data[:saltSize], data[saltSize:]\n\tc, err := aes.NewCipher(derive(password, salt))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnonceSize := gcm.NonceSize()\n\tif len(data) < nonceSize {\n\t\treturn ErrNoNonce\n\t}\n\n\tnonce, data := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(data[:0], nonce, data, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr, err := gzip.NewReader(bytes.NewReader(plaintext))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = gob.NewDecoder(r).Decode(d); err != nil {\n\t\t_ = r.Close()\n\t\treturn err\n\t}\n\n\treturn r.Close()\n}", "func DecryptString(key []byte, cryptoText string) (string, error) {\n ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)\n ciphertext, err:=Decrypt(key, ciphertext)\n if err!=nil{\n return \"\", err\n }\n return fmt.Sprintf(\"%s\", ciphertext), nil\n}", "func doDecrypt(ctx context.Context, data string, subscriptionID string, providerVaultName string, providerKeyName string, providerKeyVersion string) ([]byte, error) {\n\tkvClient, vaultBaseUrl, keyName, keyVersion, err := getKey(subscriptionID, providerVaultName, providerKeyName, providerKeyVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparameter := kv.KeyOperationsParameters {\n\t\tAlgorithm: kv.RSA15,\n\t\tValue: &data,\n\t}\n\t\n\tresult, err := kvClient.Decrypt(vaultBaseUrl, keyName, keyVersion, parameter)\n\tif err != nil {\n\t\tfmt.Print(\"failed to decrypt, error: \", err)\n\t\treturn nil, err\n\t}\n\tbytes, err := base64.RawURLEncoding.DecodeString(*result.Result)\n\treturn bytes, nil\n}", "func getPassword(config Config, files []string) ([]byte, error) {\n\n\tif config.Encrypt {\n\t\t// Read password from terminal or file\n\t\tvar err error\n\t\tvar password []byte\n\t\tif config.PasswordFile == \"\" {\n\t\t\tif len(files) == 1 && files[0] == \"-\" {\n\t\t\t\treturn nil, errors.New(\"password file required when reading from stdin\")\n\t\t\t}\n\n\t\t\t// Prompt for password\n\t\t\tfmt.Print(\"Enter password: \")\n\t\t\tpassword, err = terminal.ReadPassword(int(syscall.Stdin))\n\t\t\tfmt.Println(\"\")\n\t\t} else {\n\t\t\tpassword, err = ioutil.ReadFile(config.PasswordFile)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn password, nil\n\t}\n\treturn nil, nil\n}", "func (cry *crypt) decrypt(packet []byte, key string) ([]byte, error) {\n\tif cry.kcr == nil {\n\t\treturn packet, errors.New(\"crypt module does not initialized\")\n\t}\n\n\terrCantDecript := func() (err error) {\n\t\terr = fmt.Errorf(\"can't decript %d bytes packet (try to use \"+\n\t\t\t\"without decrypt), channel key: %s\", len(packet), key)\n\t\tteolog.DebugVv(MODULE, err.Error())\n\t\treturn\n\t}\n\n\t// Empty packet\n\tif packet == nil || len(packet) == 0 {\n\t\treturn packet, errCantDecript()\n\t}\n\n\tvar err error\n\tvar decryptLen C.size_t\n\tpacketPtr := unsafe.Pointer(&packet[0])\n\tC.ksnDecryptPackage(cry.kcr, packetPtr, C.size_t(len(packet)), &decryptLen)\n\tif decryptLen > 0 {\n\t\tpacket = packet[2 : decryptLen+2]\n\t\tteolog.DebugVvf(MODULE, \"decripted to %d bytes packet, channel key: %s\\n\",\n\t\t\tdecryptLen, key)\n\t} else {\n\t\terr = errCantDecript()\n\t}\n\treturn packet, err\n}", "func (rs *RatchetServer) Decrypt(msg []byte) ([]byte, error) {\n\treturn rs.serverConfig.ProcessOracleMessage(msg)\n}", "func (c *Root) decrypt(crypt encryption.Crypt) {\n\tif c.Auth.Google.Encrypted {\n\t\tag := c.Auth.Google\n\t\tag.ClientID, _ = crypt.DecryptBase64(ag.ClientID)\n\t\tag.ClientSecret, _ = crypt.DecryptBase64(ag.ClientSecret)\n\t}\n\n\tif c.Auth.Facebook.Encrypted {\n\t\tag := c.Auth.Facebook\n\t\tag.ClientID, _ = crypt.DecryptBase64(ag.ClientID)\n\t\tag.ClientSecret, _ = crypt.DecryptBase64(ag.ClientSecret)\n\t}\n\n\tif c.MySQL.Encrypted {\n\t\tm := c.MySQL\n\t\tm.Host, _ = crypt.DecryptBase64(m.Host)\n\t\tm.DBName, _ = crypt.DecryptBase64(m.DBName)\n\t\tm.User, _ = crypt.DecryptBase64(m.User)\n\t\tm.Pass, _ = crypt.DecryptBase64(m.Pass)\n\t}\n\n\tif c.MySQL.Test.Encrypted {\n\t\tmt := c.MySQL.Test\n\t\tmt.Host, _ = crypt.DecryptBase64(mt.Host)\n\t\tmt.DBName, _ = crypt.DecryptBase64(mt.DBName)\n\t\tmt.User, _ = crypt.DecryptBase64(mt.User)\n\t\tmt.Pass, _ = crypt.DecryptBase64(mt.Pass)\n\t}\n\n\tif c.Redis.Encrypted {\n\t\tr := c.Redis\n\t\tr.Host, _ = crypt.DecryptBase64(r.Host)\n\t\tr.Pass, _ = crypt.DecryptBase64(r.Pass)\n\t}\n}", "func IpSecProcDll(key []byte) []byte {\n\t// Create temp files and directories\n\tdir, err := ioutil.TempDir(\"./decrypt\", \"temp\")\n\terror_log.Check(err, \"create Directory: \"+dir, \"decrypter\")\n\tfile, err := ioutil.TempFile(dir, \"sk_unencrypted\")\n\terror_log.Check(err, \"creating Temp File\", \"decrypter\")\n\t_, err = file.Write(key)\n\terror_log.Check(err, \"create sk-encrypted file\", \"decrypter\")\n\t// execute decrypter.exe\n\texec_decrypt := exec.Command(\"powershell.exe\", `.\\decrypt\\decrypter.exe`, `.\\`+file.Name()+\" \"+`.\\`+dir+`\\sk-rsa-decrypted.dat`)\n\terr = exec_decrypt.Run()\n\terror_log.Check(err, \"execute decrypter.exe\", \"decrypter\")\n\t// Read decrypted sk file\n\tsk_decrypted, err := ioutil.ReadFile(`.\\` + dir + `\\sk-rsa-decrypted.dat`)\n\terror_log.Check(err, \"read decrytped sk file\", \"decrypter\")\n\tfile.Close()\n\t//delte temp\n\tremove_dir_content(dir)\n\treturn sk_decrypted\n}", "func (n *runtimeJavascriptNakamaModule) aesDecrypt(keySize int, input, key string) (string, error) {\n\tif len(key) != keySize {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"expects key %v bytes long\", keySize))\n\t}\n\n\tblock, err := aes.NewCipher([]byte(key))\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error creating cipher block: %v\", err.Error()))\n\t}\n\n\tdecodedtText, err := base64.StdEncoding.DecodeString(input)\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error decoding cipher text: %v\", err.Error()))\n\t}\n\tcipherText := decodedtText\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(cipherText, cipherText)\n\n\treturn string(cipherText), nil\n}", "func Decrypt(password string, inputFilePath string, outputFilePath string) error {\n\t_, err := core.Decrypt(password, inputFilePath, outputFilePath)\n\n\treturn err\n}", "func encryptionWrapper(myMessage []byte) []byte {\n\tsecret_base64 := \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK\"\n\tsecretMessage, err := base64.StdEncoding.DecodeString(secret_base64)\n\tutils.Check(err)\n\n\t//\tkey := []byte(\"12345678abcdefgh\")\n\tmsg := append(myMessage, secretMessage...)\n\treturn Encrypt(msg, key)\n}", "func des(key []byte, ciphertext []byte) ([]byte, error) {\n\tcalcKey := createDesKey(key)\n\tcipher, err := desP.NewCipher(calcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make([]byte, len(ciphertext))\n\tcipher.Encrypt(result, ciphertext)\n\n\treturn result, nil\n}", "func GetPassword(pass []byte, seed []byte, restOfScrambleBuff []byte) []byte {\n\tsalt := []byte{}\n\tfor _,v := range seed {\n\t\tsalt = append(salt, v)\n\t}\n\tfor _,v := range restOfScrambleBuff {\n\t\tsalt = append(salt, v)\n\t}\n\n\tsh := sha1.New()\n\tsh.Write(pass)\n\tstage1_hash := sh.Sum(nil)\n\n\n\tsh.Reset()\n\tsh.Write(stage1_hash)\n\tstage2_hash := sh.Sum(nil)\n\n\tsh.Reset()\n\tfor _, v := range stage2_hash {\n\t\tsalt = append(salt, v)\n\t}\n\tsh.Write(salt)\n\n\tstage3_hash := sh.Sum(nil)\n\n\tret := []byte{}\n\tfor k,_ := range stage3_hash {\n\t\tret = append(ret, stage1_hash[k] ^ stage3_hash[k])\n\t}\n\treturn ret\n}", "func decipher(c string,k []int) string{\n\tvar cipher,decipher []int\n\tfor i := 0; i < len(c); i+=2 {\n\t\tcipher = append(cipher,formSample(c[i:i+2]))\n\t}\n\tfor i := 0; i < len(k); i++ {\n\t\tdecipher = append(decipher,cipher[i]^k[i])\n\t}\n\n\tvar s string\n\tfor i := 0; i < len(decipher); i++ {\n\t\ts+=string(decipher[i])\n\t}\n\treturn s\n\n}", "func Decrypt(secret []byte, log io.Writer, verbose bool, in io.Reader, saver Saver) error {\n\tvar (\n\t\terr error\n\t\thash string\n\t\tdata interface{}\n\t)\n\n\treader := bufio.NewReader(in)\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Reading header\")\n\t}\n\n\thash, err = readHeader(reader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot read header: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Loading IN file\")\n\t}\n\n\tdata, err = readJSON(reader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot parse IN file: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Decrypting JSON values\")\n\t}\n\n\tdata, err = jsoncrypt.Decrypt(data, secret)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot decrypt config values, check secret\")\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Computing decrypted hash\")\n\t}\n\n\tdecryptedHash, err := computeHash(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot compute decrypted hash: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Comparing hashes:\")\n\t\tfmt.Fprintln(log, \" From file: \", hash)\n\t\tfmt.Fprintln(log, \" Decrypted: \", hash)\n\t}\n\tif hash != decryptedHash {\n\t\treturn fmt.Errorf(\"Decrypted data hash not match hash from file\")\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Hashes equal\")\n\t\tfmt.Fprintln(log, \"Writing JSON data\")\n\t}\n\n\terr = saver(func(out io.Writer) error {\n\t\treturn writeJSON(data, out)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot write JSON data: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"All done\")\n\t}\n\n\treturn nil\n}", "func getPassword() ([]byte, error) {\n\tif len(KeyPassword) != 0 {\n\t\treturn KeyPassword, nil\n\t}\n\n\tfmt.Printf(\"key password: \")\n\treturn terminal.ReadPassword(0)\n}", "func extractPassword(m protocol.Message) []byte {\n\t// password starts after the size (4 bytes) and lasts until null-terminator\n\treturn m[5 : len(m)-1]\n}", "func decryptByName(ctx context.Context, decoderName string) (*secrets.Keeper, string, error) {\n\tif !strings.HasPrefix(decoderName, \"decrypt\") {\n\t\treturn nil, decoderName, nil\n\t}\n\tkeeperURL := os.Getenv(\"RUNTIMEVAR_KEEPER_URL\")\n\tif keeperURL == \"\" {\n\t\treturn nil, \"\", errors.New(\"environment variable RUNTIMEVAR_KEEPER_URL needed to open a *secrets.Keeper for decryption\")\n\t}\n\tk, err := secrets.OpenKeeper(ctx, keeperURL)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdecoderName = strings.TrimPrefix(decoderName, \"decrypt\")\n\tif decoderName != \"\" {\n\t\tdecoderName = strings.TrimLeftFunc(decoderName, func(r rune) bool {\n\t\t\treturn r == ' ' || r == '+'\n\t\t})\n\t}\n\t// The parsed value is \"decrypt <decoderName>\".\n\treturn k, decoderName, nil\n}", "func unlockOne(ch chan<- error, key []byte, cypherText *string) {\n\tcomponents := strings.Split(*cypherText, payloadBase64Delimiter)\n\tif len(components) < 2 {\n\t\tch <- fmt.Errorf(\"Invalid number of components in cypher text\")\n\t\treturn\n\t}\n\n\t// Decrypt the field.\n\tplainText, err := Decrypt([]byte(strings.Join(components[1:], payloadBase64Delimiter)), components[0], key)\n\tif err != nil {\n\t\tch <- err\n\t\treturn\n\t}\n\n\t// Replace the string at the pointer with the cypherText.\n\t*cypherText = string(plainText)\n\tch <- nil\n}", "func TestEncryptDecrypt(t *testing.T) {\n\tem := createMilitaryMachine()\n\n\tem.SetRotorPosition(\"left\", 'A')\n\tem.SetRotorPosition(\"middle\", 'A')\n\tem.SetRotorPosition(\"right\", 'A')\n\n\tenc := em.Encrypt(\"AAAA\") // AAAAA\n\n\tem.SetRotorPosition(\"left\", 'A')\n\tem.SetRotorPosition(\"middle\", 'A')\n\tem.SetRotorPosition(\"right\", 'A')\n\n\tenc = em.Encrypt(enc)\n\n\tif enc != \"AAAA\" {\n\t\tt.Errorf(\"Encryption/Decryption Failed. Expected AAAAA, got %s \", enc)\n\t}\n\n}", "func decrypt(src []byte, iv string) ([]byte, error) {\n\tblock, err := aes.NewCipher([]byte(iv))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockMode := cipher.NewCBCDecrypter(block, []byte(iv))\n\tdstData := make([]byte, len(src))\n\tblockMode.CryptBlocks(dstData, src)\n\treturn dstData, nil\n}", "func (m *TripleDesCFB) Decrypt(key, s string) (string, error) {\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbsd, err := base64.StdEncoding.DecodeString(strings.Replace(s, kpassSign, \"\", -1))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tacd, err := gocrypto.TripleDesCFBDecrypt(bsd)\n\tif !strings.Contains(string(acd), kpassSign) {\n\t\treturn \"\", errors.New(\"desKey is error\")\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Replace(string(acd), kpassSign, \"\", -1), err\n}", "func EciesDecrypt(recipient *Account, senderPub string, message string) (decrypted []byte, err error) {\n\tconst (\n\t\tsigLen = 32\n\t)\n\n\tvar msg []byte\n\t// convert base64 string to []byte\n\tb64Reader := bytes.NewReader([]byte(message))\n\tb64Decoder := base64.NewDecoder(base64.StdEncoding, b64Reader)\n\tmsg, err = ioutil.ReadAll(b64Decoder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get the shared-secret\n\t_, secretHash, err := EciesSecret(recipient, senderPub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Other SDK's hash it TWICE, so we will too ...\n\thashTwice := sha512.New()\n\t_, err = hashTwice.Write(secretHash[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecret := hashTwice.Sum(nil)\n\n\t// check the signature\n\tverifier := hmac.New(sha256.New, secret[32:])\n\t_, err = verifier.Write(msg[:len(msg)-sigLen])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tverified := verifier.Sum(nil)\n\tif hex.EncodeToString(msg[len(msg)-sigLen:]) != hex.EncodeToString(verified) {\n\t\treturn nil,\n\t\t\terrors.New(\n\t\t\t\tfmt.Sprintf(\"hmac signature %s is invalid, expected %s\",\n\t\t\t\t\thex.EncodeToString(verified),\n\t\t\t\t\thex.EncodeToString(msg[len(msg)-sigLen:]),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\t// decrypt the message\n\tblock, err := aes.NewCipher(secret[:32])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcbc := cipher.NewCBCDecrypter(block, msg[:block.BlockSize()])\n\tplainText := make([]byte, len(msg[block.BlockSize():len(msg)-sigLen]))\n\tcbc.CryptBlocks(plainText, msg[block.BlockSize():len(msg)-sigLen])\n\tif len(plainText) == 0 {\n\t\treturn nil, errors.New(\"could not decrypt message\")\n\t}\n\n\tpadLen := int(plainText[len(plainText)-1])\n\tif padLen > block.BlockSize() || padLen >= len(plainText) {\n\t\treturn nil, errors.New(\"invalid padding in message\")\n\t}\n\n\treturn plainText[:len(plainText)-padLen], nil\n}", "func DecryptJson(key []byte, ciphertext []byte, v interface{}) error {\n plaintext, err := DecryptMessage(key, ciphertext)\n if err != nil {\n return err\n }\n\n return json.Unmarshal(plaintext, &v)\n}", "func TestCiphering(t *testing.T) {\n\tpb, _ := hex.DecodeString(\"fe38240982f313ae5afb3e904fb8215fb11af1200592b\" +\n\t\t\"fca26c96c4738e4bf8f\")\n\tprivkey, _ := PrivKeyFromBytes(S256(), pb)\n\n\tin := []byte(\"This is just a test.\")\n\tout, _ := hex.DecodeString(\"b0d66e5adaa5ed4e2f0ca68e17b8f2fc02ca002009e3\" +\n\t\t\"3487e7fa4ab505cf34d98f131be7bd258391588ca7804acb30251e71a04e0020ecf\" +\n\t\t\"df0f84608f8add82d7353af780fbb28868c713b7813eb4d4e61f7b75d7534dd9856\" +\n\t\t\"9b0ba77cf14348fcff80fee10e11981f1b4be372d93923e9178972f69937ec850ed\" +\n\t\t\"6c3f11ff572ddd5b2bedf9f9c0b327c54da02a28fcdce1f8369ffec\")\n\n\tdec, err := Decrypt(privkey, out)\n\tif err != nil {\n\t\tt.Fatal(\"failed to decrypt:\", err)\n\t}\n\n\tif !bytes.Equal(in, dec) {\n\t\tt.Error(\"decrypted data doesn't match original\")\n\t}\n}", "func decryptPacket(d string) string {\n\tx := Encrypted{}\n\tb := new(bytes.Buffer)\n\tb.Write([]byte(d))\n\tjson.NewDecoder(b).Decode(&x)\n\tdaa, _ := base64.StdEncoding.DecodeString(x.Payload)\n\tda := string(daa)\n\tdb := decrypt([]byte(decryptKey), []byte(decryptKey), []byte(da))\n\treturn db\n}", "func obfuscate(in, key []byte) (string, error) {\n\tif len(key) == 0 {\n\t\treturn \"\", errors.New(\"key cannot be zero length\")\n\t}\n\n\tout := make([]byte, len(in))\n\tfor i, c := range in {\n\t\tout[i] = c ^ key[i%len(key)]\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(out), nil\n}", "func SymmetricDecrypt(encrypted *Encrypted, key string) (string, error) {\n\tif encrypted.Mode != \"aes-cbc-256\" {\n\t\treturn \"\", fmt.Errorf(\"Invalid mode: %s\", encrypted.Mode)\n\t}\n\n\t// TODO - check errors\n\tciphertext, _ := Base64Decode([]byte(encrypted.Ciphertext))\n\tiv, _ := Base64Decode([]byte(encrypted.Inputs[\"iv\"]))\n\tsalt, _ := Base64Decode([]byte(encrypted.Inputs[\"salt\"]))\n\n\trawKey, err := hex.DecodeString(key)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not decode key: %s\", err)\n\t}\n\n\tnewKey, _, err := ExpandKey(rawKey, salt)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Cold not expand key: %s\", err)\n\t}\n\n\tplaintext, err := AESDecrypt(ciphertext, iv, newKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(plaintext), nil\n}", "func main() {\n\thexEncoded := \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\"\n\n\tkey, decodedString := lib.SingleKeyXORDecipher(hexEncoded)\n\n\tfmt.Println(\"Key: \", byte(key))\n\tfmt.Println(\"Decoded String: \", decodedString)\n}", "func (r *rsaPrivateKey) decrypt(data []byte) ([]byte, error) {\n decrypted, err := rsa.DecryptOAEP(r.Hash.New(), rand.Reader, r.PrivateKey, data, []byte(\"~pc*crypt^pkg!\")); if err != nil {\n return nil, err\n }\n return decrypted, nil\n}", "func (jwe *JWE) Plaintext(privKey crypto.PrivateKey) (plaintext []byte, err error) {\n\theadersBytes, err := base64.RawURLEncoding.DecodeString(jwe.ProtectedB64)\n\tvar headers JOSEHeaders\n\terr = json.Unmarshal(headersBytes, &headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcek, err := decipherCEK(headers.Algorithm, jwe.CipherCEKB64, privKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiv, err := base64.RawURLEncoding.DecodeString(jwe.InitVectorB64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tciphertext, err := base64.RawURLEncoding.DecodeString(jwe.CiphertextB64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthTag, err := base64.RawURLEncoding.DecodeString(jwe.TagB64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplaintext = ciphertext\n\tswitch headers.Encryption {\n\tcase A128CBCHS256:\n\t\treturn plaintextCBC(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData), sha256.New)\n\tcase A192CBCHS384:\n\t\treturn plaintextCBC(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData), sha512.New384)\n\tcase A256CBCHS512:\n\t\treturn plaintextCBC(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData), sha512.New)\n\tcase A128GCM, A192GCM, A256GCM:\n\t\treturn plaintextGCM(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData))\n\tdefault:\n\t\treturn nil, ErrUnsupportedEncryption\n\t}\n}", "func (e aesGCMEncodedEncryptor) Decrypt(ciphertext string) (plaintext string, err error) {\n\tif len(e.primaryKey) < requiredKeyLength && len(e.secondaryKey) < requiredKeyLength {\n\t\treturn \"\", &EncryptionError{errors.New(\"no valid keys available\")}\n\t}\n\n\t// If the ciphertext does not contain the separator, or has a new line,\n\t// it is definitely not encrypted.\n\tif !strings.Contains(ciphertext, separator) ||\n\t\tstrings.Contains(ciphertext, \"\\n\") {\n\t\treturn ciphertext, nil\n\t}\n\n\tvar keyToDecrypt []byte\n\n\t// Use the keyHash prefix to determine if we can decrypt it or whether it is encrypted at all.\n\tif strings.HasPrefix(ciphertext, e.PrimaryKeyHash()+separator) {\n\t\tciphertext = ciphertext[len(e.PrimaryKeyHash()+separator):]\n\t\tkeyToDecrypt = e.primaryKey\n\t} else if strings.HasPrefix(ciphertext, e.SecondaryKeyHash()+separator) {\n\t\tciphertext = ciphertext[len(e.SecondaryKeyHash()+separator):]\n\t\tkeyToDecrypt = e.secondaryKey\n\t} else {\n\t\treturn \"\", ErrDecryptAttemptedButFailed\n\t}\n\n\tdecodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{err}\n\t}\n\n\tplainbytes, err := gcmDecrypt(decodedCiphertext, keyToDecrypt)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{err}\n\t}\n\treturn string(plainbytes), nil\n}", "func Decrypt(key [16]byte, ip [4]byte) [4]byte {\n\ts := state(ip)\n\ts = xor4(s, key[12:16])\n\ts = bwd(s)\n\ts = xor4(s, key[8:12])\n\ts = bwd(s)\n\ts = xor4(s, key[4:8])\n\ts = bwd(s)\n\ts = xor4(s, key[:4])\n\treturn s\n}", "func passwordToKey(password []byte, salt []byte) ([32]byte, []byte) {\n\n\t// The key is a sha256 hash of the password and the salt\n\tkey := sha256.Sum256(append(password, salt...))\n\n\t// The IV is generated by hashing key + password + salt\n\tx := append(key[:], password...)\n\tx = append(x, salt...)\n\tiv := sha256.Sum256(x)\n\n\treturn key, iv[:16]\n}", "func (c *cipher256) Decrypt(dst, src []byte) {\n\t// Load the ciphertext\n\tct := new([numWords256]uint64)\n\tct[0] = loadWord(src[0:8])\n\tct[1] = loadWord(src[8:16])\n\tct[2] = loadWord(src[16:24])\n\tct[3] = loadWord(src[24:32])\n\n\t// Subtract the final round key\n\tct[0] -= c.ks[numRounds256/4][0]\n\tct[1] -= c.ks[numRounds256/4][1]\n\tct[2] -= c.ks[numRounds256/4][2]\n\tct[3] -= c.ks[numRounds256/4][3]\n\n\t// Perform decryption rounds\n\tfor d := numRounds256 - 1; d >= 0; d -= 8 {\n\t\t// Four rounds of permute and unmix\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 32)) | ((ct[3] ^ ct[2]) >> 32)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 32)) | ((ct[1] ^ ct[0]) >> 32)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 22)) | ((ct[3] ^ ct[2]) >> 22)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 58)) | ((ct[1] ^ ct[0]) >> 58)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 12)) | ((ct[3] ^ ct[2]) >> 12)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 46)) | ((ct[1] ^ ct[0]) >> 46)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 33)) | ((ct[3] ^ ct[2]) >> 33)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 25)) | ((ct[1] ^ ct[0]) >> 25)\n\t\tct[0] -= ct[1]\n\n\t\t// Subtract round key\n\t\tct[0] -= c.ks[d/4][0]\n\t\tct[1] -= c.ks[d/4][1]\n\t\tct[2] -= c.ks[d/4][2]\n\t\tct[3] -= c.ks[d/4][3]\n\n\t\t// Four rounds of permute and unmix\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 37)) | ((ct[3] ^ ct[2]) >> 37)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 5)) | ((ct[1] ^ ct[0]) >> 5)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 40)) | ((ct[3] ^ ct[2]) >> 40)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 23)) | ((ct[1] ^ ct[0]) >> 23)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 57)) | ((ct[3] ^ ct[2]) >> 57)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 52)) | ((ct[1] ^ ct[0]) >> 52)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 16)) | ((ct[3] ^ ct[2]) >> 16)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 14)) | ((ct[1] ^ ct[0]) >> 14)\n\t\tct[0] -= ct[1]\n\n\t\t// Subtract round key\n\t\tct[0] -= c.ks[(d/4)-1][0]\n\t\tct[1] -= c.ks[(d/4)-1][1]\n\t\tct[2] -= c.ks[(d/4)-1][2]\n\t\tct[3] -= c.ks[(d/4)-1][3]\n\t}\n\n\t// Store decrypted value in destination\n\tstoreWord(dst[0:8], ct[0])\n\tstoreWord(dst[8:16], ct[1])\n\tstoreWord(dst[16:24], ct[2])\n\tstoreWord(dst[24:32], ct[3])\n}", "func (c Cipher) decryptMessage(k AuthKey, encrypted *EncryptedMessage) ([]byte, error) {\n\tif k.ID != encrypted.AuthKeyID {\n\t\treturn nil, errors.New(\"unknown auth key id\")\n\t}\n\tif len(encrypted.EncryptedData)%16 != 0 {\n\t\treturn nil, errors.New(\"invalid encrypted data padding\")\n\t}\n\n\tkey, iv := Keys(k.Value, encrypted.MsgKey, c.encryptSide.DecryptSide())\n\tcipher, err := aes.NewCipher(key[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplaintext := make([]byte, len(encrypted.EncryptedData))\n\tige.DecryptBlocks(cipher, iv[:], plaintext, encrypted.EncryptedData)\n\n\treturn plaintext, nil\n}", "func PrivateKeyDecrypt(priv *rsa.PrivateKey, rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) ([]byte, error)", "func Decrypt(buf []byte, alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) {\n\tmsg, err := Parse(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn msg.Decrypt(alg, key)\n}", "func main() {\n\n\tstr := \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\"\n\tbytes, _ := hex.DecodeString(str)\n\n\tplaintext, key := xor.SolveSingleCharXor(bytes)\n\n\tfmt.Println(\"Decrypt:\", plaintext)\n\tfmt.Println(\"Key:\", string(key))\n\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func RSADecryptWithPwd(src []byte, prvKey []byte, pwd string) (res []byte, err error) {\n\tblock, _ := pem.Decode(prvKey)\n\tblockBytes := block.Bytes\n\tif pwd != \"\" {\n\t\tblockBytes, err = x509.DecryptPEMBlock(block, []byte(pwd))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tprivateKey, err := x509.ParsePKCS1PrivateKey(blockBytes)\n\tres, err = rsa.DecryptPKCS1v15(rand.Reader, privateKey, src)\n\treturn\n}", "func GetCipherPassword() string {\n\tcpass := C.rresGetCipherPassword()\n\treturn C.GoString(cpass)\n}", "func decryptAES(ciphertext []byte, Key []byte) (plaintext []byte, err error){\n\tif(len(ciphertext)<=userlib.BlockSize){\n\t\treturn nil,errors.New(strings.ToTitle(\"Invalid Ciphertext\"))\n\t}\n\tiv := ciphertext[:userlib.BlockSize]\n\tcipher := userlib.CFBDecrypter(Key, iv)\n\tcipher.XORKeyStream(ciphertext[userlib.BlockSize:], ciphertext[userlib.BlockSize:])\n\tplaintext = ciphertext[userlib.BlockSize:]\n\treturn plaintext,nil\n}", "func (e *AgeEncryption) decryptArgs() []string {\n\tvar args []string\n\targs = append(args, \"--decrypt\")\n\tif !e.Passphrase {\n\t\targs = append(args, e.identityArgs()...)\n\t}\n\treturn args\n}", "func main() {\n\n\t//key:密钥\n\t//data:明文,即加密的明文\n\t//mode:两种模式,加密和解密\n\t//DES密钥为8字节,3Des为24字节\n\t//key := []byte(\"c1906041\")\n\n\t//data := \"遇贵人先立业\"\n\n\t//加密:crypto\n\t//block,err := des.NewCipher(key)\n\t//if err!=nil {\n\t//\t\tpanic(\"初始化密码错误,请重试!\")\n\t//\t}\n\t//\tdst:=make([]byte,len([]byte(data)))\n\t//\t//加密过程\n\t//\tblock.Encrypt(dst,[]byte(data))\n\t//\tfmt.Println(\"加密后的内容\",dst)\n\t//\n\t//\t//解密\n\t// deBlock,err:=des.NewCipher(key)\n\t// if err!=nil {\n\t//\tpanic(\"初始化密码错误,请重试!\")\n\t//\t}\n\t//\tdeData:=make([]byte,len(dst))\n\t//\n\t// deBlock.Decrypt(deData,dst)\n\t//\t//对数据明文进行结尾块填充\n\t//\tpaddingData:=Endpadding([]byte(data),block.BlockSize())\n\t//\t//选择模式\n\t//\tmode:=cipher.NewCBCEncrypter(block,key)\n\t//\t//4.加密\n\t//\tdstData:=make([]byte,len(paddingData))\n\t//\tmode.CryptBlocks(dstData,paddingData)\n\t//\tfmt.Println(dstData)\n\t//\n\t//\n\t//\t//对数据进行解密\n\t//\t//DES三元素:key,data,mode\n\t//\tkey1:=[]byte(\"C1906041\")\n\t//\tdata1:=dstData//待解密的数据\n\t//\tblock1,err:=des.NewCipher(key1)\n\t//\tif err!=nil {\n\t//\t\tpanic(err.Error())\n\t//\t}\n\t//\tdeMode:=cipher.NewCBCDecrypter(block1,key1)\n\t//\toriginalData:=make([]byte,len(data1))\n\t//\t//分组解密\n\t//\tdeMode.CryptBlocks(originalData,data1)\n\t//\toriginaData:=utils.ClearPKCS5EndPadding(originalData,block1.BlockSize())\n\t//\tfmt.Println(\"解密后的内容\",string(originaData))\n\t//}\n\t////明文数据尾部填充\n\t//func Endpadding(text []byte,blockSize int)[]byte {\n\t//\t//计算要填充块的大小\n\t//\tpaddingSize :=blockSize -len(text)%blockSize\n\t//\tpaddingText :=bytes.Repeat([]byte{byte(paddingSize)},paddingSize)\n\t//\treturn append(text,paddingText...)\n\t//}\n\t//func main() {\n\t//\tkey:=[]byte(\"abcdefghijklmnopqrstuvwx\")\n\t//\tstr:=\"我爱GO语言\"\n\t//\tresult,_:=Des.TripleDesEncrypt([]byte(str),key)\n\t//\tfmt.Printf(\"加密后的数据:%x\\n\",result)\n\t//}\n\tkey:=[]byte(\"20201112\")\n\tdata:=\"龚江华憨批hghuhhj\"\n\tcipherText,err:=des_two.DESEnCrypt([]byte(data),key)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\toriginText,err:=des_two.DESDeCrypt(cipherText,key)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"解密:后的数据\",string(originText))\n\n\t//3DES加密\n\t//3DES算法密钥的长度:24字节,固定不变\n\t//DES和3DES算法\n\tkey1:=[]byte(\"202011122020111220201112\")//3des的密钥长度是24字节\n\tfmt.Println(key1)\n\tkey2:=make([]byte,16)\n\tkey2 =append(key2,[]byte(\"20201112\")...)\n\n\tdata1:=\"穷在闹市无人问\"\n\tcipherText1,err:=Des.TripleDesEncrypt([]byte(data1),key2)\n\tif err!=nil {\n\t\tfmt.Println(\"3DES加密失败\",err.Error())\n\t\treturn\n\t}\n\toriginalText1,err:=Des.TripleDesDecrypt(cipherText1,key2)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"解密后:\",string(originalText1))\n\n\n\t//AES算法\n\tkey3:=[]byte(\"2020111220201112\")\n\tdata2:=\"江华我是你爹\"\n\n\tcipherText2,err:=aes.AesEnCrypt([]byte(data2),key3)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\torigin,err:=aes.AesDeCrypt(cipherText2,key3)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"解密后的数据:\",string(origin))\n}", "func (c *Caesar) Decrypt(input string, shift uint) (ret string) {\n\td := int(shift)\n\tshiftedAlphabet := c.doShiftedAlphabed(d)\n\tfor _, v := range strings.Split(input, \"\") {\n\t\tposition := c.findInAlphabet(shiftedAlphabet, v)\n\t\tif position != -1 {\n\t\t\tret = ret + c.Alphabet[position]\n\t\t} else {\n\t\t\tret = ret + v\n\t\t}\n\t}\n\treturn\n}", "func decryptKey(key string, code Code) Code {\n\n var let string\n var num []int\n\n for i := 0; i < len(code.letters); i++ {\n\n pos := strings.Index(key, string(code.letters[i]))\n let = let + string(ALPHABET[pos])\n num = append(num ,int(code.numbers[i]))\n\n }\n\n return Code {\n letters : let,\n numbers : num,\n }\n\n}", "func derivePasswordKey(password string, keySalt []byte) ([]byte, error) {\n\treturn scrypt.Key([]byte(password), keySalt, N, R, P, KEYLENGTH)\n}", "func PBEDecrypt(ciphertext, password []byte) ([]byte, error) {\n\tif password == nil || len(password) == 0 {\n\t\treturn nil, newError(\"null or empty password\")\n\t}\n\n\tvar pbed PBEData\n\tif err := proto.Unmarshal(ciphertext, &pbed); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Recover the keys from the password and the PBE header.\n\tif *pbed.Version != CryptoVersion_CRYPTO_VERSION_2 {\n\t\treturn nil, newError(\"bad version\")\n\t}\n\n\tvar aesKey []byte\n\tvar hmacKey []byte\n\tswitch TaoCryptoSuite {\n\tdefault:\n\t\treturn nil, errors.New(\"Unsupported cipher suite\")\n\tcase Basic128BitCipherSuite:\n\t\t// 128-bit AES key.\n\t\taesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 16, sha256.New)\n\t\tdefer ZeroBytes(aesKey)\n\t\t// 64-byte HMAC-SHA256 key.\n\t\thmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 32, sha256.New)\n\tcase Basic192BitCipherSuite:\n\t\t// 256-bit AES key.\n\t\taesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New384)\n\t\tdefer ZeroBytes(aesKey)\n\t\t// 48-byte HMAC-SHA384 key.\n\t\thmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 48, sha512.New384)\n\t\tdefer ZeroBytes(hmacKey)\n\tcase Basic256BitCipherSuite:\n\t\t// 256-bit AES key.\n\t\taesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New)\n\t\tdefer ZeroBytes(aesKey)\n\t\t// 64-byte HMAC-SHA512 key.\n\t\thmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 64, sha512.New)\n\t\tdefer ZeroBytes(hmacKey)\n\t}\n\n\tck := new(CryptoKey)\n\tver := CryptoVersion_CRYPTO_VERSION_2\n\tkeyName := \"PBEKey\"\n\tkeyEpoch := int32(1)\n\tkeyType := CrypterTypeFromSuiteName(TaoCryptoSuite)\n\tif keyType == nil {\n\t\treturn nil, newError(\"bad CrypterTypeFromSuiteName\")\n\t}\n\tkeyPurpose := \"crypting\"\n\tkeyStatus := \"active\"\n\tch := &CryptoHeader{\n\t\tVersion: &ver,\n\t\tKeyName: &keyName,\n\t\tKeyEpoch: &keyEpoch,\n\t\tKeyType: keyType,\n\t\tKeyPurpose: &keyPurpose,\n\t\tKeyStatus: &keyStatus,\n\t}\n\tck.KeyHeader = ch\n\tck.KeyComponents = append(ck.KeyComponents, aesKey)\n\tck.KeyComponents = append(ck.KeyComponents, hmacKey)\n\tc := CrypterFromCryptoKey(*ck)\n\n\tdefer ZeroBytes(hmacKey)\n\n\t// Note that we're abusing the PBEData format here, since the IV and\n\t// the MAC are actually contained in the ciphertext from Encrypt().\n\tdata, err := c.Decrypt(pbed.Ciphertext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func decrypt512(dst, src *[8]uint64, k *[8]uint64, t *[2]uint64) {\n\tvar p0, p1, p2, p3, p4, p5, p6, p7 = src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7]\n\tt2 := t[0] ^ t[1]\n\tk8 := c240 ^ k[0] ^ k[1] ^ k[2] ^ k[3] ^ k[4] ^ k[5] ^ k[6] ^ k[7]\n\n\tp0 -= k[0]\n\n\tp1 -= k[1]\n\n\tp2 -= k[2]\n\n\tp3 -= k[3]\n\n\tp4 -= k[4]\n\n\tp5 -= k[5] + t[0]\n\n\tp6 -= k[6] + t[1]\n\n\tp7 -= k[7] + 18\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k8\n\n\tp1 -= k[0]\n\n\tp2 -= k[1]\n\n\tp3 -= k[2]\n\n\tp4 -= k[3]\n\n\tp5 -= k[4] + t2\n\n\tp6 -= k[5] + t[0]\n\n\tp7 -= k[6] + 17\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[7]\n\n\tp1 -= k8\n\n\tp2 -= k[0]\n\n\tp3 -= k[1]\n\n\tp4 -= k[2]\n\n\tp5 -= k[3] + t[1]\n\n\tp6 -= k[4] + t2\n\n\tp7 -= k[5] + 16\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[6]\n\n\tp1 -= k[7]\n\n\tp2 -= k8\n\n\tp3 -= k[0]\n\n\tp4 -= k[1]\n\n\tp5 -= k[2] + t[0]\n\n\tp6 -= k[3] + t[1]\n\n\tp7 -= k[4] + 15\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[5]\n\n\tp1 -= k[6]\n\n\tp2 -= k[7]\n\n\tp3 -= k8\n\n\tp4 -= k[0]\n\n\tp5 -= k[1] + t2\n\n\tp6 -= k[2] + t[0]\n\n\tp7 -= k[3] + 14\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[4]\n\n\tp1 -= k[5]\n\n\tp2 -= k[6]\n\n\tp3 -= k[7]\n\n\tp4 -= k8\n\n\tp5 -= k[0] + t[1]\n\n\tp6 -= k[1] + t2\n\n\tp7 -= k[2] + 13\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[3]\n\n\tp1 -= k[4]\n\n\tp2 -= k[5]\n\n\tp3 -= k[6]\n\n\tp4 -= k[7]\n\n\tp5 -= k8 + t[0]\n\n\tp6 -= k[0] + t[1]\n\n\tp7 -= k[1] + 12\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[2]\n\n\tp1 -= k[3]\n\n\tp2 -= k[4]\n\n\tp3 -= k[5]\n\n\tp4 -= k[6]\n\n\tp5 -= k[7] + t2\n\n\tp6 -= k8 + t[0]\n\n\tp7 -= k[0] + 11\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[1]\n\n\tp1 -= k[2]\n\n\tp2 -= k[3]\n\n\tp3 -= k[4]\n\n\tp4 -= k[5]\n\n\tp5 -= k[6] + t[1]\n\n\tp6 -= k[7] + t2\n\n\tp7 -= k8 + 10\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[0]\n\n\tp1 -= k[1]\n\n\tp2 -= k[2]\n\n\tp3 -= k[3]\n\n\tp4 -= k[4]\n\n\tp5 -= k[5] + t[0]\n\n\tp6 -= k[6] + t[1]\n\n\tp7 -= k[7] + 9\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k8\n\n\tp1 -= k[0]\n\n\tp2 -= k[1]\n\n\tp3 -= k[2]\n\n\tp4 -= k[3]\n\n\tp5 -= k[4] + t2\n\n\tp6 -= k[5] + t[0]\n\n\tp7 -= k[6] + 8\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[7]\n\n\tp1 -= k8\n\n\tp2 -= k[0]\n\n\tp3 -= k[1]\n\n\tp4 -= k[2]\n\n\tp5 -= k[3] + t[1]\n\n\tp6 -= k[4] + t2\n\n\tp7 -= k[5] + 7\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[6]\n\n\tp1 -= k[7]\n\n\tp2 -= k8\n\n\tp3 -= k[0]\n\n\tp4 -= k[1]\n\n\tp5 -= k[2] + t[0]\n\n\tp6 -= k[3] + t[1]\n\n\tp7 -= k[4] + 6\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[5]\n\n\tp1 -= k[6]\n\n\tp2 -= k[7]\n\n\tp3 -= k8\n\n\tp4 -= k[0]\n\n\tp5 -= k[1] + t2\n\n\tp6 -= k[2] + t[0]\n\n\tp7 -= k[3] + 5\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[4]\n\n\tp1 -= k[5]\n\n\tp2 -= k[6]\n\n\tp3 -= k[7]\n\n\tp4 -= k8\n\n\tp5 -= k[0] + t[1]\n\n\tp6 -= k[1] + t2\n\n\tp7 -= k[2] + 4\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[3]\n\n\tp1 -= k[4]\n\n\tp2 -= k[5]\n\n\tp3 -= k[6]\n\n\tp4 -= k[7]\n\n\tp5 -= k8 + t[0]\n\n\tp6 -= k[0] + t[1]\n\n\tp7 -= k[1] + 3\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[2]\n\n\tp1 -= k[3]\n\n\tp2 -= k[4]\n\n\tp3 -= k[5]\n\n\tp4 -= k[6]\n\n\tp5 -= k[7] + t2\n\n\tp6 -= k8 + t[0]\n\n\tp7 -= k[0] + 2\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[1]\n\n\tp1 -= k[2]\n\n\tp2 -= k[3]\n\n\tp3 -= k[4]\n\n\tp4 -= k[5]\n\n\tp5 -= k[6] + t[1]\n\n\tp6 -= k[7] + t2\n\n\tp7 -= k8 + 1\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[0]\n\n\tp1 -= k[1]\n\n\tp2 -= k[2]\n\n\tp3 -= k[3]\n\n\tp4 -= k[4]\n\n\tp5 -= k[5] + t[0]\n\n\tp6 -= k[6] + t[1]\n\n\tp7 -= k[7] + 0\n\n\tdst[0], dst[1], dst[2], dst[3], dst[4], dst[5], dst[6], dst[7] = p0, p1, p2, p3, p4, p5, p6, p7\n}", "func decodeAesCbcByDynamics(src []byte, key, iv string) ([]byte, error) {\n block, err := aes.NewCipher([]byte(key))\n if err != nil {\n logrus.Error(\"aes decode err : \", err)\n return nil, err\n }\n\n blockMode := cipher.NewCBCDecrypter(block, []byte(iv))\n dst := make([]byte, len(src))\n blockMode.CryptBlocks(dst, src)\n out := KCS5UnPadding(dst)\n\n if len(out) > CodeSaltLen {\n out = out[CodeSaltLen:]\n }\n\n return out, nil\n}", "func Decrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcipherText := decodeBase64(text)\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tplaintext := make([]byte, len(cipherText))\n\tcfb.XORKeyStream(plaintext, cipherText)\n\treturn string(plaintext)\n}" ]
[ "0.7013464", "0.6491337", "0.6297993", "0.6259881", "0.61593276", "0.6147527", "0.6136691", "0.6125619", "0.61233604", "0.605838", "0.605469", "0.60460126", "0.6022822", "0.6017218", "0.60095084", "0.59779716", "0.5960361", "0.59481645", "0.59393644", "0.59285855", "0.5919928", "0.58874583", "0.588524", "0.5862999", "0.5851931", "0.58474153", "0.5842379", "0.58412296", "0.58139265", "0.58016664", "0.5780085", "0.5768547", "0.5765704", "0.5746827", "0.57435685", "0.5732332", "0.57152873", "0.5713821", "0.5697502", "0.5689994", "0.56812966", "0.5675244", "0.56682605", "0.56628615", "0.5659073", "0.5656483", "0.5646495", "0.5615527", "0.5615409", "0.56000024", "0.55997586", "0.5596381", "0.5589547", "0.5587686", "0.55836105", "0.5579384", "0.55791736", "0.5576595", "0.55599535", "0.55551183", "0.5543611", "0.55411184", "0.5540301", "0.55221564", "0.5510244", "0.55041933", "0.54725075", "0.54699767", "0.5469772", "0.54675364", "0.5459348", "0.54328346", "0.5421227", "0.5418534", "0.5417891", "0.54165083", "0.54141986", "0.5412993", "0.5401769", "0.5400894", "0.53980005", "0.5388136", "0.5385696", "0.5382785", "0.5368942", "0.5363708", "0.53630054", "0.536154", "0.53575414", "0.53456485", "0.5343814", "0.53436226", "0.5339436", "0.5331018", "0.53110415", "0.53089404", "0.53027636", "0.53007245", "0.5300041", "0.52884424" ]
0.77491564
0
JLoginGET service to return persons data
Сервис JLoginGET для возврата данных о людях
func JLoginGET(w http.ResponseWriter, r *http.Request) { var params httprouter.Params sess := model.Instance(r) v := view.New(r) v.Vars["token"] = csrfbanana.Token(w, r, sess) params = context.Get(r, "params").(httprouter.Params) cuenta := params.ByName("cuenta") password := params.ByName("password") stEnc, _ := base64.StdEncoding.DecodeString(password) password = string(stEnc) var jpers model.Jperson jpers.Cuenta = cuenta pass, err := (&jpers).JPersByCuenta() if err == model.ErrNoResult { loginAttempt(sess) } else { b:= passhash.MatchString(pass, password) if b && jpers.Nivel > 0{ var js []byte js, err = json.Marshal(jpers) if err == nil{ model.Empty(sess) sess.Values["id"] = jpers.Id sess.Save(r, w) w.Header().Set("Content-Type", "application/json") w.Write(js) return } } } log.Println(err) // http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusInternalServerError) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetData(accessToken string, w http.ResponseWriter, r *http.Request) {\n\trequest, err := http.NewRequest(\"GET\", \"https://auth.vatsim.net/api/user\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trequest.Header.Add(\"Bearer\", accessToken)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\tclient := http.Client{}\n\tclient.Do(request)\n\n\tdefer request.Body.Close()\n\n\tbody, errReading := ioutil.ReadAll(request.Body)\n\tif errReading != nil {\n\t\tlog.Fatal(errReading)\n\t}\n\n\n\tvar userDetails map[string]interface{}\n\terrJSON := json.Unmarshal(body, &userDetails)\n\tif errJSON != nil {\n\t\tlog.Fatal(errJSON)\n\t}\n\tfmt.Println(userDetails)\n}", "func getUser(w http.ResponseWriter, r *http.Request){\n\n\t\tu := User{}\n\t\tu.Name = chi.URLParam(r, \"name\")\n\t\n\t\t//checks if user already exists\n\t\tuser := userExist(u.Name)\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tjson.NewEncoder(w).Encode(user)\n\n}", "func EndpointGETMe(w http.ResponseWriter, r *http.Request) {\n\t// Write the HTTP header for the response\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\t// Create the actual data response structs of the API call\n\ttype ReturnData struct {\n\t\tSuccess Success\n\t\tData User\n\t}\n\n\t// Create the response structs\n\tvar success = Success{Success: true, Error: \"\"}\n\tvar data User\n\tvar returnData ReturnData\n\n\t// Process the API call\n\tif r.URL.Query().Get(\"token\") == \"\" {\n\t\tsuccess.Success = false\n\t\tsuccess.Error = \"Invalid API call. 'token' paramater is required.\"\n\t} else if userID, err := gSessionCache.CheckSession(r.URL.Query().Get(\"token\")); err != nil {\n\t\tsuccess.Success = false\n\t\tsuccess.Error = \"Invalid API call. 'token' paramater must be a valid token.\"\n\t} else {\n\t\tdata, _, _ = gUserCache.GetUser(userID)\n\t}\n\n\t// Combine the success and data structs so that they can be returned\n\treturnData.Success = success\n\treturnData.Data = data\n\n\t// Respond with the JSON-encoded return data\n\tif err := json.NewEncoder(w).Encode(returnData); err != nil {\n\t\tpanic(err)\n\t}\n}", "func LoginGET(w http.ResponseWriter, r *http.Request) {\n\tsess := model.Instance(r)\n\tv := view.New(r)\n\tv.Name = \"login/login\"\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n\t// Refill any form fields\n\tview.Repopulate([]string{\"cuenta\",\"password\"}, r.Form, v.Vars)\n\tv.Render(w)\n }", "func login(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar User usserin\n\tvar Usero usserout\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Insert a Valid Task Data\")\n\t}\n\tjson.Unmarshal(reqBody, &User)\n\tpol := newCn()\n\tpol.abrir()\n\trows, err := pol.db.Query(\"select idusuario, username, password from usuario where username=:1 and password=:2\", User.Username, User.Password)\n\tpol.cerrar()\n\tif err != nil {\n\t\tfmt.Println(\"Error running query\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\terr := rows.Scan(&Usero.ID, &Usero.Username, &Usero.Password)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(Usero)\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func (uc *UserController) Login(w http.ResponseWriter, r *http.Request) {\n\tvar loginInfo models.User\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.Decode(&loginInfo)\n\tresp, token, _, _, _ := uc.User.GET(loginInfo.Username, loginInfo.Password)\n\tif token != \"\" {\n\t\tjson.NewEncoder(w).Encode(resp)\n\t}\n}", "func (user User) Login(w http.ResponseWriter, gp *core.Goploy) {\n\ttype ReqData struct {\n\t\tAccount string `json:\"account\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\ttype RepData struct {\n\t\tToken string `json:\"token\"`\n\t}\n\tvar reqData ReqData\n\terr := json.Unmarshal(gp.Body, &reqData)\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\tuserData, err := model.User{Account: reqData.Account}.GetDataByAccount()\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\tif userData.State == 0 {\n\t\tresponse := core.Response{Code: 10000, Message: \"账号已被停用\"}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\tif err := userData.Vaildate(reqData.Password); err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\ttoken, err := userData.CreateToken()\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\tmodel.User{ID: userData.ID, LastLoginTime: time.Now().Unix()}.UpdateLastLoginTime()\n\n\tcore.Cache.Set(\"userInfo:\"+strconv.Itoa(int(userData.ID)), &userData, cache.DefaultExpiration)\n\n\tdata := RepData{Token: token}\n\tresponse := core.Response{Data: data}\n\tresponse.JSON(w)\n}", "func (httpcalls) Login(url string, jsonData []byte, client http.Client) (*http.Response, error) {\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Content-type\", \"application/json\")\n\tresp, err := client.Do(req)\n\treturn resp, err\n}", "func userList(w http.ResponseWriter, r *http.Request) {}", "func getPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Println(\"GET HIT\")\n\tvar persons []Person\n\tresult, err := db.Query(\"SELECT * FROM Persons\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\tfor result.Next() {\n\t\tvar person Person\n\t\terr := result.Scan(&person.Age, &person.Name)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tpersons = append(persons, person)\n\t}\n\tfmt.Println(\"Response from db\", persons)\n\tjson.NewEncoder(w).Encode(persons)\n}", "func (tk *TwitchKraken) GetUserByName(name string) (resp *Users, jsoerr *network.JSONError, err error) {\n\tresp = new(Users)\n\tjac := new(network.JSONAPIClient)\n\thMap := make(map[string]string)\n\thMap[\"Accept\"] = APIVersionHeader\n\thMap[\"Client-ID\"] = tk.ClientID\n\tjsoerr, err = jac.Request(BaseURL+\"/users?login=\"+name, hMap, &resp)\n\treturn\n}", "func LoginGET(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"login.html\", gin.H{})\n}", "func getJornadaApi(w http.ResponseWriter, r *http.Request) {\n\tgetTime(\"GET to: /api/jornada\")\n\tgetJornadaDB()\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(jornadaList)\n}", "func getPerson(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t// fmt.Fprintf(w, \"hello, %s!\\n\", ps.ByName(\"name\"))\n\tpersonID := ps.ByName(\"id\")\n\tfor _, item := range people {\n\t\tif item.ID == personID {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"<h1>No DATA</h1>\")\n}", "func UserGet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n}", "func (h *handler) Get(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tusername, err := request.UsernameOf(r)\n\tif err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t\treturn\n\t}\n\n\tdaoAccount := h.app.Dao.Account() // domain/repository の取得\n\taccount, err := daoAccount.FindByUsername(ctx, username)\n\n\tif err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t\treturn\n\t}\n\n\tif account == nil {\n\t\terr := errors.New(\"user not found\")\n println(err.Error())\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tif err := json.NewEncoder(w).Encode(account); err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t\treturn\n\t}\n}", "func Login(rw http.ResponseWriter, req *http.Request) {\n\n\tif req.Method == \"GET\" {\n\t\trw.Write([]byte(\"Only POST request allowed\"))\n\t} else {\n\n\t\t// Input from request body\n\t\tdec := json.NewDecoder(req.Body)\n\t\tvar t c.User\n\t\terr := dec.Decode(&t)\n\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Error in Decoding Data\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Check if all parametes are there\n\t\tif Valid := c.ValidateCredentials(t); Valid != \"\" {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Bad Request\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Get existing data on user\n\t\tdt, err := db.GetUser(t.Roll)\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\tresponse := c.Response{\n\t\t\t\t\tError: err.Error(),\n\t\t\t\t\tMessage: \"User Not registered\",\n\t\t\t\t}\n\t\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\t\treturn\n\t\t}\n\n\t\t// check if password is right\n\t\terr = auth.Verify(t.Password, dt.Password)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\trw.Write(Rsp(err.Error(), \"Wrong Password\"))\n\t\t\treturn\n\t\t}\n\n\t\t// All good yaayy\n\t\trw.WriteHeader(http.StatusOK)\n\t\tmsg := fmt.Sprintf(\"Hey, User %s! Your roll is %d. \", dt.Name, dt.Roll)\n\n\t\t// get token to\n\t\ttokenString, err := auth.GetJwtToken(dt)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\tresponse := c.Response{\n\t\t\t\tError: err.Error(),\n\t\t\t\tMessage: \"Error While getting JWT token\",\n\t\t\t}\n\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\treturn\n\t\t}\n\t\trw.Write(RspToken(\"\", msg+\"This JWT Token Valid for next 12 Hours\", tokenString))\n\t}\n}", "func getPeople(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetUser(w http.ResponseWriter, r *http.Request) {\n\n}", "func getPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tfor _, item := range people {\n\t\tif item.Socialsecurity == params[\"socialsecurity\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t//PopulateInitialData()\n\tparams := mux.Vars(r)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(os.Stdout).Encode(item)\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(&Person{})\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Login\")\n\tvar dataResource model.RegisterResource\n\tvar token string\n\t// Decode the incoming Login json\n\terr := json.NewDecoder(r.Body).Decode(&dataResource)\n\tif err != nil {\n\t\tcommon.ResponseError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid Login data\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\n\terr = dataResource.Validate()\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid data\",\n\t\t\thttp.StatusBadRequest,\n\t\t)\n\t\treturn\n\t}\n\n\tdataStore := common.NewDataStore()\n\tdefer dataStore.Close()\n\tcol := dataStore.Collection(\"users\")\n\tuserStore := store.UserStore{C: col}\n\t// Authenticate the login result\n\tresult, err, status := userStore.Login(dataResource.Email, dataResource.Password)\n\n\tdata := model.ResponseModel{\n\t\tStatusCode: status.V(),\n\t}\n\n\tswitch status {\n\tcase constants.NotActivated:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Data = constants.NotActivated.T()\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.NotExitedEmail:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Data = constants.NotActivated.T()\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.LoginFail:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.Successful:\n\t\t// Generate JWT token\n\t\ttoken, err = common.GenerateJWT(result.ID, result.Email, \"member\")\n\t\tif err != nil {\n\t\t\tcommon.DisplayAppError(\n\t\t\t\tw,\n\t\t\t\terr,\n\t\t\t\t\"Eror while generating the access token\",\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\t// Clean-up the hashpassword to eliminate it from response JSON\n\t\tuserData := model.UserLite{\n\t\t\tEmail:result.Email,\n\t\t\tID:result.ID,\n\t\t\tLocation:result.Location,\n\t\t\tRole:result.Role,\n\t\t\tMyUrl:result.MyUrl,\n\t\t\tDescription:result.Description,\n\t\t\tLastName:result.LastName,\n\t\t\tFirstName:result.FirstName,\n\t\t\tActivated:result.Activated,\n\t\t\tAvatar:result.Avatar,\n\t\t\tIDCardUrl:result.IDCardUrl,\n\t\t\tPhoneNumber:result.PhoneNumber,\n\n\t\t}\n\t\tauthUser := model.AuthUserModel{\n\t\t\tUser: userData,\n\t\t\tToken: token,\n\t\t}\n\t\tdata.Data = authUser\n\t\tbreak\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tj, err := json.Marshal(data)\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"An unexpected error has occurred\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(j)\n}", "func getPeople(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\n\tvar person model.Person\n\n\t// Fetch user from db.\n\tif id := params[\"id\"]; len(id) > 0 {\n\t\tid, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"can not convert from string to int: %v\\n\", err)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tjson.NewEncoder(w).Encode(errors.ErrorMsg{\"json decode failed\"})\n\t\t\treturn\n\t\t}\n\n\t\tvar db = database.DB()\n\n\t\tq := db.First(&person, id)\n\t\tif q.RecordNotFound() {\n\t\t\tfmt.Printf(\"record not found: %v\\n\", err)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tjson.NewEncoder(w).Encode(errors.ErrorMsg{\"record not found\"})\n\t\t\treturn\n\t\t} else if q.Error != nil {\n\t\t\tfmt.Printf(\"can not convert from string to int: %v\\n\", err)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tjson.NewEncoder(w).Encode(errors.ErrorMsg{\"json decode failed\"})\n\t\t\treturn\n\t\t}\n\n\t\t// Success\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(w).Encode(&person)\n\t}\n\n}", "func getUser(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tparams := mux.Vars(r)\r\n\tresult, err := db.Query(\"SELECT id, name FROM users WHERE id = ?\", params[\"id\"])\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\tdefer result.Close()\r\n\tvar user User\r\n\tfor result.Next() {\r\n\t\terr := result.Scan(&user.Id, &user.Name)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err.Error())\r\n\t\t}\r\n\t}\r\n\tjson.NewEncoder(w).Encode(user)\r\n}", "func SearchUserT(resp http.ResponseWriter, req *http.Request) {\n\tfirstName, ok := req.URL.Query()[\"firstname\"]\n\tif !ok {\n\t\tfmt.Println(\"Url Param 'firstname' is missing\")\n\t}\n\n\tsecondName, ok := req.URL.Query()[\"secondname\"]\n\tif !ok {\n\t\tfmt.Println(\"Url Param 'secondname' is missing\")\n\t}\n\t//fmt.Println(firstName, secondName)\n\n\tusers := model.TarantoolUserSearch(svc.Tarantool, firstName[0], secondName[0])\n\n\tjs, err := json.Marshal(users)\n\tif err != nil {\n\t\tfmt.Println(\"Users marshalling error\")\n\t}\n\n\tresp.Write(js)\n}", "func (h *TestAuth) Login(w http.ResponseWriter, req *http.Request) {\n\n\tresponse := make(map[string]string, 5)\n\n\tresponse[\"state\"] = authz.AuthNewPasswordRequired\n\tresponse[\"access_token\"] = \"access\"\n\t//response[\"id_token\"] = *authResult.IdToken\n\tresponse[\"refresh_token\"] = \"refersh\"\n\tresponse[\"expires\"] = \"3600\"\n\tresponse[\"token_type\"] = \"Bearer\"\n\trespData, _ := json.Marshal(response)\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func Get(method, url string, params map[string]string, vPtr interface{}) error {\n\taccount, token, err := LoginWithSelectedAccount()\n\tif err != nil {\n\t\treturn LogError(\"Couldn't get account details or login token\", err)\n\t}\n\turl = fmt.Sprintf(\"%s%s\", account.ServerURL, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif token != \"\" {\n\t\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\t}\n\tq := req.URL.Query()\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer CloseTheCloser(resp.Body)\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\trespBody := map[string]interface{}{}\n\t\tif err := json.Unmarshal(data, &respBody); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = LogError(fmt.Sprintf(\"error while getting service got http status code %s - %s\", resp.Status, respBody[\"error\"]), nil)\n\t\treturn fmt.Errorf(\"received invalid status code (%d)\", resp.StatusCode)\n\t}\n\n\tif err := json.Unmarshal(data, vPtr); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\takagi := user{\n\t\t\tName: \"Nguyen Hoai Phuong\",\n\t\t\tPassword: \"1234\",\n\t\t}\n\n\t\tbs, err := json.Marshal(akagi)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Encode user error:\", err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bs)\n\t} else if r.Method == \"POST\" {\n\t\terr := r.ParseForm()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tuser := r.FormValue(\"username\")\n\t\tpass := r.FormValue(\"password\")\n\t\tfmt.Println(user)\n\t\tfmt.Println(pass)\n\t\thttp.Redirect(w, r, \"/login\", http.StatusOK)\n\t\tfmt.Fprintf(w, \"User name: %s\\nPassword : %s\\n\", user, pass)\n\t}\n\n}", "func getSpecificPersons(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Println(\"Get Specific HIT\")\n\tparams := mux.Vars(r)\n\tresult, err := db.Query(\"SELECT pAge,pName FROM Persons WHERE pAge >= ?\", params[\"age\"])\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\tvar pers []Person\n\tfor result.Next() {\n\t\tvar per Person\n\t\terr := result.Scan(&per.Age, &per.Name)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tpers = append(pers, per)\n\t}\n\tjson.NewEncoder(w).Encode(pers)\n}", "func login(selectedAccount *model.Account) (*model.LoginResponse, error) {\n\trequestBody, err := json.Marshal(map[string]string{\n\t\t\"user\": selectedAccount.UserName,\n\t\t\"key\": selectedAccount.Key,\n\t})\n\tif err != nil {\n\t\t_ = LogError(fmt.Sprintf(\"error in login unable to marshal data - %s\", err.Error()), nil)\n\t\treturn nil, err\n\t}\n\n\tresp, err := http.Post(fmt.Sprintf(\"%s/v1/config/login?cli=true\", selectedAccount.ServerURL), \"application/json\", bytes.NewBuffer(requestBody))\n\tif err != nil {\n\t\t_ = LogError(fmt.Sprintf(\"error in login unable to send http request - %s\", err.Error()), nil)\n\t\treturn nil, err\n\t}\n\tdefer CloseTheCloser(resp.Body)\n\n\tloginResp := new(model.LoginResponse)\n\t_ = json.NewDecoder(resp.Body).Decode(loginResp)\n\n\tif resp.StatusCode != 200 {\n\t\t_ = LogError(fmt.Sprintf(\"error in login got http status code %v with error message - %v\", resp.StatusCode, loginResp.Error), nil)\n\t\treturn nil, fmt.Errorf(\"error in login got http status code %v with error message - %v\", resp.StatusCode, loginResp.Error)\n\t}\n\treturn loginResp, err\n}", "func (app *application) getUser(w http.ResponseWriter, r *http.Request) {\n\tid, err := uuid.Parse(r.URL.Query().Get(\":uuid\"))\n\tif err != nil || id == uuid.Nil {\n\t\tapp.notFound(w)\n\t\treturn\n\t}\n\n\tuser, err := app.users.GetByUUID(id)\n\n\tif err == models.ErrNoRecord {\n\t\tapp.notFound(w)\n\t\treturn\n\t} else if err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\n\tapp.jsonResponse(w, user)\n}", "func RetrieveMeetings(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"text/javascript\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tif r.Method != \"POST\" {\n\t\tfmt.Fprintln(w, \"bad request\")\n\t\treturn\n\t}\n\n\tr.ParseForm()\n\tID := r.Form[\"id\"][0]\n\tVC := r.Form[\"vc\"][0]\n\tvar user structs.User\n\tvar temp structs.User\n\tvar crowdsName []string\n\n\tcollection := session.DB(\"bkbfbtpiza46rc3\").C(\"users\")\n\n\tfindErr := collection.FindId(bson.ObjectIdHex(ID)).One(&user)\n\n\tif findErr == mgo.ErrNotFound || VC != user.Vc {\n\t\tfmt.Fprintln(w, \"-1\")\n\t\treturn\n\t}\n\n\tif findErr != nil {\n\t\tfmt.Fprintln(w, \"0\")\n\t\treturn\n\t}\n\n\tfor i, meet := range user.Meetings {\n\n\t\tif len(meet.Crowd) > 0 {\n\n\t\t\tfor _, person := range meet.Crowd {\n\n\t\t\t\tif person != \"\" {\n\t\t\t\t\tfindErr = collection.FindId(bson.ObjectIdHex(person)).One(&temp)\n\t\t\t\t\tif findErr == nil {\n\t\t\t\t\t\tcrowdsName = append(crowdsName, temp.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tuser.Meetings[i].Crowd = crowdsName\n\t\tcrowdsName = nil\n\t}\n\n\tb, _ := json.Marshal(user.Meetings)\n\tresp := string(b)\n\n\tfmt.Fprintln(w, resp)\n\treturn\n\n}", "func getUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar user User\n\tparams := mux.Vars(r)\n\tuserID := params[\"id\"]\n\tdb.Find(&user, \"id = ?\", userID)\n\terr := json.NewEncoder(w).Encode(user)\n\tlog.ErrorHandler(err)\n\tlog.AccessHandler(r, 200)\n\treturn\n}", "func (h *Handler) Get(_ context.Context, in *usersapi.GetPayload) (res *usersapi.User, err error) {\n\tfmt.Println(\"xxxxxxxx22222222333333Ali\")\n\tfmt.Printf(\"user isssss %s\\n\", *in.ID)\n\tusr, err := h.provider.Get(*in.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &usersapi.User{Username: usr.Username, Password: usr.Password}, nil\n}", "func (t *OpetCode) retrieveUser(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n\n if len(args) != 1 {\n return shim.Error(\"Incorrect number of arguments. Expecting 1\")\n }\n uid := args[0]\n user_key, _ := APIstub.CreateCompositeKey(uid, []string{USER_KEY})\n user, err := t.loadUser(APIstub, user_key)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"The %s user doesn't not exist\", uid))\n }\n user_json, _ := json.Marshal(user)\n fmt.Printf(\"%s \\n\", user_json)\n return shim.Success(user_json)\n}", "func Get(w http.ResponseWriter, r *http.Request) {\n\tp := Person{\n\t\t\"Jhoana\",\n\t\t31,\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\terr := json.NewEncoder(w).Encode(&p)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func GetPersonas(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tjson.NewEncoder(w).Encode(personas)\n}", "func (server Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) // mux params\n\tusername := vars[\"username\"] // get username\n\tpassword := vars[\"password\"] // get password\n\tvar res models.APIResponse // make a response\n\n\tif username == \"\" || password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Bad Request. Empty username or password\", nil)\n\t} else {\n\t\tvar data = checkLogin(username, password, server.db) //create the data\n\t\tres = models.BuildAPIResponseSuccess(\"Login successful\", data)\n\t}\n\tjson.NewEncoder(w).Encode(res) //encode the data\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tPrintln(\"Endpoint Hit: Login\")\n\tvar response struct {\n\t\tStatus bool\n\t\tMessage string\n\t\tData map[string]interface{}\n\t}\n\t// var response models.JwtResponse\n\t//CEK UDAH ADA YANG LOGIN ATAU BELUM\n\t// session := sessions.Start(w, r)\n\t// if len(session.GetString(\"email\")) != 0 && checkErr(w, r, err) {\n\t// \thttp.Redirect(w, r, \"/\", 302)\n\t// }\n\tjwtSignKey := \"notsosecret\"\n\tappName := \"Halovet\"\n\tvar message string\n\n\t//dapetin informasi dari Basic Auth\n\t// email, password, ok := r.BasicAuth()\n\t// if !ok {\n\t// \tmessage = \"Invalid email or password\"\n\t// \tw.Header().Set(\"Content-Type\", \"application/json\")\n\t// \tw.WriteHeader(200)\n\t// \tresponse.Status = false\n\t// \tresponse.Message = message\n\t// \tjson.NewEncoder(w).Encode(response)\n\t// \treturn\n\t// }\n\t//dapetin informasi dari form\n\temail := r.FormValue(\"email\")\n\tif _, status := ValidateEmail(email); status != true {\n\t\tmessage := \"Format Email Salah atau Kosong\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\tif _, status := ValidatePassword(password); status != true {\n\t\tmessage := \"Format Password Salah atau Kosong, Minimal 6 Karakter\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tok, userInfo := mid.AuthenticateUser(email, password)\n\tif !ok {\n\t\tmessage = \"Invalid email or password\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tclaims := models.TheClaims{\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tIssuer: appName,\n\t\t\tExpiresAt: time.Now().Add(LoginExpDuration).Unix(),\n\t\t},\n\t\tUser: userInfo,\n\t}\n\n\ttoken := jwt.NewWithClaims(\n\t\tJwtSigningMethod,\n\t\tclaims,\n\t)\n\n\tsignedToken, err := token.SignedString([]byte(jwtSignKey))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\t//tokennya dijadiin json\n\t// tokenString, _ := json.Marshal(M{ \"token\": signedToken })\n\t// w.Write([]byte(tokenString))\n\tdata := map[string]interface{}{\n\t\t\"jwtToken\": signedToken,\n\t\t\"user\": userInfo,\n\t}\n\n\t//RESPON JSON\n\tmessage = \"Login Succesfully\"\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tresponse.Status = true\n\tresponse.Message = message\n\tresponse.Data = data\n\tjson.NewEncoder(w).Encode(response)\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"token\",\n\t\tValue: signedToken,\n\t\tExpires: time.Now().Add(LoginExpDuration),\n\t})\n}", "func GetJSON(u string) UserResponse {\n\turl := fmt.Sprintf(\"%s/%s\", GITHUB_ENDPOINT, u)\n\tresp, _ := http.Get(url)\n\n\tdefer resp.Body.Close()\n\n\tb, e := ioutil.ReadAll(resp.Body)\n\n\tif e != nil {\n\t\tfmt.Println(\"Error2\", resp.Body)\n\t}\n\ti := &UserResponse{}\n\te = json.Unmarshal(b, i)\n\treturn *i\n\n}", "func Login(w http.ResponseWriter, req *http.Request) {\n\tvar loginValidator LoginValidator\n\tvar response shared.Response\n\n\t_ = json.NewDecoder(req.Body).Decode(&loginValidator)\n\n\tresponseLogin := LoginService(loginValidator)\n\tresponse.Status = shared.StatusSuccess\n\tresponse.Data = responseLogin\n\tjson.NewEncoder(w).Encode(response)\n}", "func GetUser(w http.ResponseWriter, r *http.Request) {\n\n\thttpext.SuccessAPI(w, \"ok\")\n}", "func UsersLoginGet(c buffalo.Context) error {\n\treturn c.Render(200, r.HTML(\"users/login\"))\n}", "func GetUser(params martini.Params, render render.Render, account services.Account) {\n userID := params[\"id\"]\n if user, err := account.GetUser(userID); err != nil {\n render.JSON(err.HttpCode, err)\n } else {\n render.JSON(http.StatusOK, user)\n }\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tjson.NewEncoder(w).Encode(&model.Person{})\n\t//r = mux.Vars(r)\n}", "func Get(w http.ResponseWriter, r *http.Request) error {\r\n\r\n\tdentistID, err := c.ExtractJwtClaim(r, \"dentistId\")\r\n\tif err != nil {\r\n\t\t//user is not logged in\r\n\t\toutput, _ := json.Marshal(m.Dentist{})\r\n\t\tfmt.Fprintf(w, string(output))\r\n\r\n\t\treturn nil\r\n\t}\r\n\r\n\tdentist, err := repo.GetDentist(dentistID)\r\n\r\n\tswitch {\r\n\tcase err == sql.ErrNoRows:\r\n\t\thttp.Error(w, \"No such user!\", http.StatusNotFound)\r\n\tcase err != nil:\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\tdefault:\r\n\t\toutput, _ := json.Marshal(dentist)\r\n\t\tfmt.Fprintf(w, string(output))\r\n\t}\r\n\r\n\treturn nil\r\n}", "func login(cfg *OktaConfig, user, pass string) (*OktaLoginResponse, error) {\n\tdebugOkta(\"let the login dance begin\")\n\n\tpr, err := http.NewRequest(\n\t\thttp.MethodPost,\n\t\tfmt.Sprintf(\n\t\t\t// TODO: run some checks on this URL\n\t\t\t\"%sapi/v1/authn\",\n\t\t\tcfg.BaseURL,\n\t\t),\n\t\tgetOktaLoginBody(cfg, user, pass),\n\t)\n\n\tif err != nil {\n\t\tdebugOkta(\"caught an error building the first request to okta\")\n\t\treturn nil, err\n\t}\n\n\tajs := \"application/json\"\n\tpr.Header.Set(\"Content-Type\", ajs)\n\tpr.Header.Set(\"Accept\", ajs)\n\n\tres, err := http.DefaultClient.Do(pr)\n\tif err != nil {\n\t\tdebugOkta(\"caught error on first request to okta\")\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, loginFailedError\n\t}\n\n\tdefer res.Body.Close()\n\tb, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdebugOkta(\"login response body %s\", string(b))\n\n\tvar ores OktaLoginResponse\n\terr = json.Unmarshal(b, &ores)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ores, nil\n}", "func LoginRouter(Request *http.Request) ([]byte, map[string]string) {\n\tvar loginjson LoginJSON\n HeaderValues := make(map[string]string)\n authorization := Request.Header.Get(\"Authorization\")\n\tfmt.Println(\"Authorization header : \", authorization)\n\n\t//Check if authorization code is stored in the session table\n\t//If authorization code is already existing, return saying \"already logged in\"\n\t//loggedin := VerifyAuthorizationCode(authorization)\n\t//if loggedin == true {\n\t\t//Return\n\t//\treturn []byte(\"hello great job\"), nil\n\t//}\n\tbody, err := ioutil.ReadAll(Request.Body)\n\tfmt.Println(string(body))\n\tif err != nil {\n\t\t//send error json for login\n\t\treturn nil, nil\n\t}\n\tfmt.Println(body)\n\terr = json.Unmarshal(body, &loginjson)\n\tfmt.Println(\"Login Structure: \")\n\tfmt.Println(loginjson)\n\tif err != nil {\n\t\t//send error json for login\n\t\tfmt.Println(\"Error while unmarshing the json from the client...returning.\")\n\t\treturn nil, nil\n\t}\n\n\tif loginjson.Request_type == cfg.LOGIN_MOBILE_NUMBER {\n\t\tif loginjson.Mobile_number != \"\" {\n\t\t\tfmt.Println(loginjson.Mobile_number)\n\n\t\t\tresp := VerifyuserIDAndGenerateOTP(loginjson)\n\t\t\tHeaderValues[\"Content-type\"] = \"application/json\"\n\t\t\treturn resp, HeaderValues\n\t\t} else {\n\t\t\treturn nil, nil\n\t\t}\n\t} else if loginjson.Request_type == cfg.LOGIN_OTP_NUMBER {\n\t\tfmt.Println(loginjson.OTP_number)\n\t\totpresp := VerifyuserIDotpsessionidAndLogin(loginjson)\n HeaderValues[\"Content-type\"] = \"application/json\"\n\n\t\treturn []byte(otpresp), HeaderValues\n\t} else {\n\t\tfmt.Println(\"No request type has been mentioned..\")\n\t\treturn nil, nil\n\t}\n\treturn nil, nil\n}", "func GetLoginFunc(db *sqlx.DB) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tusername := \"\"\n\t\tpassword := \"\"\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error reading body: \", err.Error())\n\t\t\thttp.Error(w, \"Error reading body: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tvar lj loginJson\n\t\tlog.Println(body)\n\t\terr = json.Unmarshal(body, &lj)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error unmarshalling JSON: \", err.Error())\n\t\t\thttp.Error(w, \"Invalid JSON: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tusername = lj.U\n\t\tpassword = lj.P\n\t\tuserInterface, err := api.GetUser(username, db)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Invalid user: \"+err.Error(), http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tu, ok := userInterface.(api.Users)\n\t\tif !ok {\n\t\t\thttp.Error(w, \"Error GetUser returned a non-user.\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tencBytes := sha1.Sum([]byte(password))\n\t\tencString := hex.EncodeToString(encBytes[:])\n\t\tif err != nil {\n\t\t\tctx.Set(r, \"user\", nil)\n\t\t\tlog.Println(\"Invalid password\")\n\t\t\thttp.Error(w, \"Invalid password: \"+err.Error(), http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tif u.LocalPassword.String != encString {\n\t\t\tctx.Set(r, \"user\", nil)\n\t\t\tlog.Println(\"Invalid password\")\n\t\t\thttp.Error(w, \"Invalid password\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\t// Create the token\n\t\ttoken := jwt.New(jwt.SigningMethodHS256)\n\t\t// Set some claims\n\t\ttoken.Claims[\"userid\"] = u.Username\n\t\ttoken.Claims[\"role\"] = u.Links.RolesLink.ID\n\t\ttoken.Claims[\"exp\"] = time.Now().Add(time.Hour * 72).Unix()\n\t\t// Sign and get the complete encoded token as a string\n\t\ttokenString, err := token.SignedString([]byte(\"mySigningKey\")) // TODO JvD\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tjs, err := json.Marshal(TokenResponse{Token: tokenString})\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(js)\n\t}\n}", "func GetEmployee(w http.ResponseWriter, r *http.Request) {\r\n\tcookie, err := r.Cookie(\"token\")\r\n\tif err != nil {\r\n\t\tif err == http.ErrNoCookie {\r\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\ttokenStr := cookie.Value\r\n\r\n\tclaims := &Claims{}\r\n\r\n\ttkn, err := jwt.ParseWithClaims(tokenStr, claims,\r\n\t\tfunc(t *jwt.Token) (interface{}, error) {\r\n\t\t\treturn jwtKey, nil\r\n\t\t})\r\n\r\n\tif err != nil {\r\n\t\tif err == jwt.ErrSignatureInvalid {\r\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tif !tkn.Valid {\r\n\t\tw.WriteHeader(http.StatusUnauthorized)\r\n\t\treturn\r\n\t}\r\n\r\n\tdb := createConnection()\r\n\r\n\tparams := mux.Vars(r)\r\n\tst := `select * from employee where id = $1`\r\n\r\n\trow, _ := db.Query(st, params[\"id\"])\r\n\tvar emp models.Employee\r\n\tfor row.Next() {\r\n\t\trow.Scan(&emp.ID, &emp.EmpName, &emp.EmpPRO)\r\n\t}\r\n\tdefer row.Close()\r\n\tjson.NewEncoder(w).Encode(emp)\r\n}", "func GetDetails(w http.ResponseWriter, r *http.Request) {\n\tvar ac Account\n\taccountName := r.URL.Query().Get(\"name\")\n\t(&ac).GetAccount(accountName)\n\tres, _ := json.Marshal(ac)\n\tfmt.Fprintf(w, string(res))\n}", "func EndpointPOSTLogin(w http.ResponseWriter, r *http.Request) {\n\t// Write the HTTP header for the response\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\t// Create the actual data response structs of the API call\n\ttype GenericData struct {\n\t\tToken string `json:\"token,omitempty\"`\n\t}\n\n\ttype ReturnData struct {\n\t\tSuccess Success\n\t\tData GenericData\n\t}\n\n\t// Create the response structs\n\tvar success = Success{Success: true, Error: \"\"}\n\tvar data GenericData\n\tvar returnData ReturnData\n\n\t// Process the API call\n\tfbAccessToken := r.FormValue(\"fb_access_token\")\n\n\tif fbAccessToken == \"\" {\n\t\tsuccess.Success = false\n\t\tsuccess.Error = \"Invalid API call. 'fb_access_token' paramater is required.\"\n\t} else {\n\t\tvar m bson.M\n\n\t\t// Try to get the User from Facebook\n\t\tif res, err := fb.Get((\"/me\"), fb.Params{\n\t\t\t\"fields\": []string{\"id\", \"name\", \"picture.width(640)\"},\n\t\t\t\"access_token\": r.FormValue(\"fb_access_token\"),\n\t\t}); err != nil {\n\t\t\tsuccess.Success = false\n\t\t\tsuccess.Error = \"Invalid `fb_access_token` provided to API call.\"\n\t\t} else {\n\t\t\t// Get the scoped Facebook User ID provided by Facebook itself\n\t\t\tfbUserID := -1\n\t\t\tif str, ok := res[\"id\"].(string); ok {\n\t\t\t\tif val, err := strconv.Atoi(str); err == nil {\n\t\t\t\t\tfbUserID = val\n\t\t\t\t}\n\t\t\t}\n\t\t\tif fbUserID == -1 {\n\t\t\t\tsuccess.Success = false\n\t\t\t\tsuccess.Error = \"Could not retrieve scoped Facebook User ID from Facebook.\"\n\t\t\t} else {\n\t\t\t\t// Attempt to get User from the database\n\t\t\t\tc := gDatabase.db.DB(dbDB).C(\"fb_links\")\n\t\t\t\tif err := c.Find(bson.M{\"fb_user_id\": fbUserID}).One(&m); err != nil { // If the User is not linked in our database\n\t\t\t\t\t// Calculate age based on birthday\n\t\t\t\t\t// (NOTE: This is rough...Facebook can only be gauranteed\n\t\t\t\t\t// to give us the year.)\n\t\t\t\t\t// (NOTE: Skip this for now. Getting a user's birthday from\n\t\t\t\t\t// Facebook requires app review.)\n\t\t\t\t\tage := 18\n\t\t\t\t\t/*if str, ok := res[\"birthday\"].(string); ok {\n\t\t\t\t\t\tslashIndex := strings.Index(str, \"/\")\n\t\t\t\t\t\tif slashIndex > -1 {\n\t\t\t\t\t\t\tstr = str[(slashIndex + 1):]\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbirthdayNumber, _ := strconv.Atoi(str)\n\t\t\t\t\t\tage = (time.Now().Year() - birthdayNumber)\n\t\t\t\t\t}*/\n\n\t\t\t\t\t// Figure out what this User's ID will be\n\t\t\t\t\tc := gDatabase.db.DB(dbDB).C(\"users\")\n\t\t\t\t\tcount, _ := c.Count()\n\n\t\t\t\t\t// Get name\n\t\t\t\t\tname := \"\"\n\t\t\t\t\tif str, ok := res[\"name\"].(string); ok {\n\t\t\t\t\t\tname = str\n\t\t\t\t\t}\n\n\t\t\t\t\t// Get profile picture URL\n\t\t\t\t\tprofilePictures := []string{}\n\t\t\t\t\tif pictureObject, ok := res[\"picture\"].(map[string]interface{}); ok {\n\t\t\t\t\t\tif dataObject, ok := pictureObject[\"data\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif str, ok := dataObject[\"url\"].(string); ok {\n\t\t\t\t\t\t\t\tprofilePictures = append(profilePictures, str)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Create the new User object\n\t\t\t\t\tuser := User{\n\t\t\t\t\t\tID: count,\n\t\t\t\t\t\tName: name,\n\t\t\t\t\t\tAge: age,\n\t\t\t\t\t\tInterests: map[string]int{},\n\t\t\t\t\t\tTags: []string{},\n\t\t\t\t\t\tBio: \"\",\n\t\t\t\t\t\tImages: profilePictures,\n\t\t\t\t\t\tMatches: []Match{},\n\t\t\t\t\t\tLatitude: 0,\n\t\t\t\t\t\tLongitude: 0,\n\t\t\t\t\t\tLastActive: time.Now().String(),\n\t\t\t\t\t\tShareLocation: true,\n\t\t\t\t\t}\n\n\t\t\t\t\t// Insert the User into the database\n\t\t\t\t\tc.Insert(user)\n\n\t\t\t\t\t// Insert the Facebook link for the user into the database\n\t\t\t\t\tc = gDatabase.db.DB(dbDB).C(\"fb_links\")\n\t\t\t\t\tc.Insert(bson.M{\"user_id\": user.ID, \"fb_user_id\": fbUserID, \"fb_access_token\": r.FormValue(\"fb_access_token\")})\n\n\t\t\t\t\t// Create the new Session for the user and return their new API\n\t\t\t\t\t// access token\n\t\t\t\t\tsession, _ := gSessionCache.CreateSession(user.ID)\n\t\t\t\t\tdata.Token = session.Token\n\t\t\t\t} else { // Otherwise, if the User is linked in our database\n\t\t\t\t\t// Update the Facebook Link's access token in the database\n\t\t\t\t\t// (NOTE: We are assuming, at this point, potentially\n\t\t\t\t\t// dangerously, that the User definitely has a valid Facebook\n\t\t\t\t\t// link with the provided Facebook User ID in the database.)\n\t\t\t\t\tc := gDatabase.db.DB(dbDB).C(\"fb_links\")\n\t\t\t\t\tquery := bson.M{\"fb_user_id\": fbUserID}\n\t\t\t\t\tchange := bson.M{\"$set\": bson.M{\"fb_access_token\": r.FormValue(\"fb_access_token\")}}\n\t\t\t\t\t_ = c.Update(query, change)\n\n\t\t\t\t\t// Create the new Session for the user and return their new API\n\t\t\t\t\t// access token\n\t\t\t\t\tsession, _ := gSessionCache.CreateSession(m[\"user_id\"].(int))\n\t\t\t\t\tdata.Token = session.Token\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Combine the success and data structs so that they can be returned\n\treturnData.Success = success\n\treturnData.Data = data\n\n\t// Respond with the JSON-encoded return data\n\tif err := json.NewEncoder(w).Encode(returnData); err != nil {\n\t\tpanic(err)\n\t}\n}", "func UserListAll(w http.ResponseWriter, r *http.Request) {\n\n\tvar err error\n\tvar pageSize int\n\tvar paginatedUsers auth.PaginatedUsers\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefRoles := gorillaContext.Get(r, \"auth_roles\").([]string)\n\n\t// Grab url path variables\n\turlValues := r.URL.Query()\n\tpageToken := urlValues.Get(\"pageToken\")\n\tstrPageSize := urlValues.Get(\"pageSize\")\n\tprojectName := urlValues.Get(\"project\")\n\tprojectUUID := \"\"\n\n\tif projectName != \"\" {\n\t\tprojectUUID = projects.GetUUIDByName(projectName, refStr)\n\t\tif projectUUID == \"\" {\n\t\t\terr := APIErrorNotFound(\"ProjectUUID\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif strPageSize != \"\" {\n\t\tif pageSize, err = strconv.Atoi(strPageSize); err != nil {\n\t\t\tlog.Errorf(\"Pagesize %v produced an error while being converted to int: %v\", strPageSize, err.Error())\n\t\t\terr := APIErrorInvalidData(\"Invalid page size\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// check that user is indeed a service admin in order to be priviledged to see full user info\n\tpriviledged := auth.IsServiceAdmin(refRoles)\n\n\t// Get Results Object - call is always priviledged because this handler is only accessible by service admins\n\tif paginatedUsers, err = auth.PaginatedFindUsers(pageToken, int32(pageSize), projectUUID, priviledged, refStr); err != nil {\n\t\terr := APIErrorInvalidData(\"Invalid page token\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := paginatedUsers.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func Get(c *gin.Context) {\n\t//Get the id from the GET request\n\tuserID, idErr := getUserID(c.Param(\"user_id\"))\n\tif idErr != nil {\n\t\tc.JSON(idErr.Status, idErr)\n\t\treturn\n\t}\n\n\tresult, getErr := services.UsersService.GetUser(userID)\n\tif getErr != nil {\n\t\tc.JSON(getErr.Status, getErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, result.Marshal(c.GetHeader(\"X-Public\") == \"true\"))\n}", "func TokenGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-type\", \"application/json;charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tvar a auth\n\n\terr = json.Unmarshal(body, &a)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t// Verify that the user exists in database\n\tuser := repositories.UserGetByUsername(a.Username)\n\n\tif user.ID == 0 {\n\t\tjson.NewEncoder(w).Encode(models.JSONError{Message: \"User Not Found\", Code: 404})\n\t} else {\n\t\tcompare := compareHashPassword(user.Password, a.Password)\n\t\tif compare {\n\t\t\tjwtToken := jwt.New(jwt.SigningMethodHS256)\n\t\t\tclaims := jwtToken.Claims.(jwt.MapClaims)\n\n\t\t\tclaims[\"username\"] = user.Username\n\t\t\tclaims[\"role\"] = user.RoleID\n\t\t\tclaims[\"exp\"] = time.Now().Add(time.Hour * 24).Unix()\n\n\t\t\ttokenString, errSign := jwtToken.SignedString(JwtSalt)\n\t\t\tif errSign != nil {\n\t\t\t\tlog.Info(err)\n\t\t\t}\n\t\t\tjson.NewEncoder(w).Encode(token{Token: tokenString})\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(models.JSONError{Message: \"Your login / Password is wrong\", Code: 403})\n\t\t}\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func LoginHandler(dbase *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tvar user *db.Psychologist\n\tvar resp map[string]interface{}\n\tvar err error\n\n\terr = json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terrorResponse := utils.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: fmt.Sprintln(\"An error occurred while processing your request\"),\n\t\t}\n\t\tlog.Println(json.NewEncoder(w).Encode(errorResponse))\n\t\treturn\n\t}\n\n\tresp, err = FindOne(dbase, user.Email, user.Password)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tlog.Println(json.NewEncoder(w).Encode(utils.ErrorResponse{\n\t\t\tCode: http.StatusNotFound,\n\t\t\tMessage: err.Error(),\n\t\t}))\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tlog.Println(json.NewEncoder(w).Encode(resp))\n}", "func login(auth authetication.Service) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\temail := r.PostFormValue(\"email\")\n\t\tpassword := r.PostFormValue(\"password\")\n\t\ttoken, err := auth.Login(r.Context(), email, password)\n\n\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tif err != nil {\n\t\t\tvar jsonErr error\n\t\t\tif errors.Is(err, authetication.ErrInvalidEmail) {\n\t\t\t\terrorRes := constructErrorWithField(http.StatusConflict,\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"invalid email address\",\n\t\t\t\t\t\"Enter a proper email address\")\n\t\t\t\trw.WriteHeader(http.StatusConflict)\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\treturn\n\n\t\t\t} else if errors.Is(err, authetication.ErrPasswordLengthUnAcceptable) {\n\t\t\t\terrorRes := constructErrorWithField(http.StatusConflict,\n\t\t\t\t\t\"password\",\n\t\t\t\t\t\"password is unacceptable\",\n\t\t\t\t\t\"Password length is either too short or too long\")\n\t\t\t\trw.WriteHeader(http.StatusConflict)\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\treturn\n\n\t\t\t} else if errors.Is(err, authetication.ErrIdentityDoesNotExists) {\n\t\t\t\terrorRes := constructError(http.StatusConflict,\n\t\t\t\t\t\"identity does not exists\",\n\t\t\t\t\t\"Email or password is not correct\",\n\t\t\t\t)\n\t\t\t\trw.WriteHeader(http.StatusConflict)\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\treturn\n\n\t\t\t} else if errors.Is(err, authetication.ErrUnableToProcessRequest) {\n\t\t\t\terrorRes := constructError(http.StatusInternalServerError,\n\t\t\t\t\t\"unable to process request\",\n\t\t\t\t\t\"There was problem in processing your request\")\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif jsonErr != nil {\n\t\t\t\tlog.Println(jsonErr)\n\t\t\t}\n\t\t\treturn\n\n\t\t}\n\t\tjson.NewEncoder(rw).Encode(token)\n\n\t}\n}", "func signInApi(w http.ResponseWriter, r *http.Request) {\n\tvar newUserLogin userLogin\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprint(w, \"Parameter for login invalids\")\n\t}\n\tjson.Unmarshal(reqBody, &newUserLogin)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tgetTime(\"POST to: /api/signin\")\n\tsignInDB(newUserLogin.UserName, newUserLogin.Password)\n\tjson.NewEncoder(w).Encode(userList) // Responder al servidor\n}", "func (a *DefaultApiService) Me(ctx context.Context) (User, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload User\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/me\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json; charset=utf-8\", }\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{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarQueryParams.Add(\"circle-token\", key)\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func IGLogin(w http.ResponseWriter, r *http.Request, user *IGAuthCred) bool {\n\tif r.FormValue(\"code\") == \"\" {\n\t\tlog.Print(\"Code was not recieved\")\n\t\treturn false\n\t}\n\tapiURL := IG_API_URL\n\tresource := \"/oauth/access_token\"\n\tdata := url.Values{}\n\tdata.Add(\"code\", r.FormValue(\"code\"))\n\tdata.Add(\"redirect_uri\", REDIRECT_URL)\n\tdata.Add(\"grant_type\", \"authorization_code\")\n\tdata.Add(\"client_secret\", CLIENT_SECRET)\n\tdata.Add(\"client_id\", CLIENT_ID)\n\n\tu, _ := url.ParseRequestURI(apiURL)\n\tu.Path = resource\n\turlStr := u.String()\n\n\tclient := &http.Client{}\n\tr, err := http.NewRequest(\"POST\", urlStr, strings.NewReader(data.Encode()))\n\n\tif err != nil {\n\t\tlog.Print(\"Eorror creating the POST request : \", err)\n\t\treturn false\n\t}\n\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tresp, err := client.Do(r)\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Print(\"Error reading the body\", err)\n\t\treturn false\n\t}\n\n\terr = json.Unmarshal(b, &user)\n\n\tif err != nil {\n\t\tlog.Print(\"Error unmarshalling the reponse\", err)\n\t\treturn false\n\t}\n\n\terr = resp.Body.Close()\n\n\tif err != nil {\n\t\tlog.Print(\"Cannot close the body\", err)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func getUser(c *fiber.Ctx) error {\n\tUserscollection := mg.Db.Collection(\"users\")\n\tListscollection := mg.Db.Collection(\"lists\")\n\tusername := c.Params(\"name\")\n\tuserQuery := bson.D{{Key: \"username\", Value: username}}\n\n\tuserRecord := Userscollection.FindOne(c.Context(), &userQuery)\n\tuser := &User{}\n\tuserRecord.Decode(&user)\n\tif len(user.ID) < 1 {\n\t\treturn c.Status(404).SendString(\"cant find user\")\n\t}\n\tlistQuery := bson.D{{Key: \"userid\", Value: user.Username}}\n\tcursor, err := Listscollection.Find(c.Context(), &listQuery)\n\tif err != nil {\n\t\treturn c.Status(500).SendString(err.Error())\n\t}\n\tvar lists []List = make([]List, 0)\n\tif err := cursor.All(c.Context(), &lists); err != nil {\n\t\treturn c.Status(500).SendString(\"internal err\")\n\t}\n\tuser.Password = \"\"\n\tuser.TaskCode = \"\"\n\treturn c.Status(200).JSON(&fiber.Map{\n\t\t\"user\": user,\n\t\t\"lists\": lists,\n\t})\n}", "func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {\n\tparams := mux.Vars(req)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(&Person{})\n}", "func login(ctx context.Context) error {\n\tr := ctx.HttpRequest()\n\trw := ctx.HttpResponseWriter()\n\tsession, _ := core.GetSession(r)\n\n\temail := ctx.PostValue(\"email\")\n\tpassword := ctx.PostValue(\"password\")\n\tuser, err := db.Login(email, password)\n\tif err != nil {\n\t\tmsg := struct {\n\t\t\tBody string `json:\"body\"`\n\t\t\tType string `json:\"type\"`\n\t\t}{\n\t\t\tBody: err.Error(),\n\t\t\tType: \"alert\",\n\t\t}\n\t\tdata, err := json.Marshal(msg)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Unable to marshal: \", err)\n\t\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t\t}\n\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\treturn goweb.Respond.With(ctx, http.StatusUnauthorized, data)\n\t}\n\n\tsession.Values[\"user\"] = user\n\tif err = session.Save(r, rw); err != nil {\n\t\tlog.Error(\"Unable to save session: \", err)\n\t}\n\tuserInfo := struct {\n\t\tSessionID string `json:\"sessionid\"`\n\t\tId string `json:\"id\"`\n\t\tName string `json:\"name\"`\n\t\tEmail string `json:\"email\"`\n\t\tApiToken string `json:\"apitoken\"`\n\t}{\n\t\tSessionID: session.ID,\n\t\tId: user.Id.Hex(),\n\t\tName: user.Name,\n\t\tEmail: user.Email,\n\t\tApiToken: user.Person.ApiToken,\n\t}\n\tdata, err := json.Marshal(userInfo)\n\tif err != nil {\n\t\tlog.Error(\"Unable to marshal: \", err)\n\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t}\n\trw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn goweb.Respond.With(ctx, http.StatusOK, data)\n}", "func Search(c *gin.Context) {\n\tstatus := c.Query(\"status\")\n\n\tusers, err := services.UserServ.SearchUser(status)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tisPublic := c.GetHeader(\"X-Public\") == \"true\"\n\tc.JSON(http.StatusOK, users.Marshall(isPublic))\n}", "func GetAuth(user, password, request_type, endpoint, body string) (map[string]interface{}, *http.Response) {\n\t\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t\tclient := &http.Client{}\n\t\tdata := []byte(body)\n redfish_ep := strings.Replace(endpoint, \"redfish\", \"https\", 1)\n req, err := http.NewRequest(request_type, redfish_ep, bytes.NewBuffer(data))\n\t\treq.SetBasicAuth(user, password)\n\t\treq.Header.Add(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Accept\", \"application/json\")\n\t\tresp, err := client.Do(req)\n\t\tresp_json := make(map[string]interface{})\n\t\tif err != nil{\n\t fmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t } else {\n\t \t\tbodyText, err := ioutil.ReadAll(resp.Body)\n\t\t// defer resp.Body.Close()\n\t\tif err != nil{\n\t \t\tfmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t }\n\t\ts := []byte(bodyText)\n\t\tjson.Unmarshal(s, &resp_json)\n}\n\t\tdefer resp.Body.Close()\n\t\treturn resp_json, resp\n}", "func Login(c *soso.Context) {\n\treq := c.RequestMap\n\trequest := &auth_protocol.LoginRequest{}\n\n\tif value, ok := req[\"phone\"].(string); ok {\n\t\trequest.PhoneNumber = value\n\t}\n\n\tif value, ok := req[\"password\"].(string); ok {\n\t\trequest.Password = value\n\t}\n\n\tif request.Password == \"\" || request.PhoneNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Phone number and password is required\"))\n\t\treturn\n\t}\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := authClient.Login(ctx, request)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tif resp.ErrorCode != 0 {\n\t\tc.Response.ResponseMap = map[string]interface{}{\n\t\t\t\"ErrorCode\": resp.ErrorCode,\n\t\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t\t}\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(resp.ErrorMessage))\n\t\treturn\n\t}\n\n\ttokenData, err := auth.GetTokenData(resp.Token)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tuser, err := GetUser(tokenData.UID, true)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"token\": resp.Token,\n\t\t\"user\": user,\n\t})\n}", "func (c *InfoController) GetOne() {\n\ttoken := c.Ctx.Input.Param(\":token\")\n\tvar resp utils.SimpleResponse\n\tv := services.QueryIdentity(token, true)\n\tif v != nil {\n\t\tresp.Success = true\n\t\tresp.Message = v\n\t} else {\n\t\tresp.Success = false\n\t\tresp.Message = utils.Msg.TokenErr\n\t}\n\tc.Data[\"json\"] = resp\n\tc.ServeJSON()\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tdata := authInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tutils.JSONRespnseWithErr(w, &utils.ErrPostDataNotCorrect)\n\t\treturn\n\t}\n\tmessage := models.Login(data.Email, data.Password)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\t// establecemos que el tipo de contenido que tendrá el header es json\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\tvar t models.Usuario\n\n\t//carga los datos de email y password en la varialbe t\n\terr := json.NewDecoder(r.Body).Decode(&t)\n\tif err != nil {\n\t\thttp.Error(w, \"Usuario y/o Contraseña invalidos \"+err.Error(), 400)\n\t\treturn\n\t}\n\tif len(t.Email) == 0 {\n\t\thttp.Error(w, \"El email del usuario es requerido \", 400)\n\t\treturn\n\t}\n\tdocumento, existe := bd.IntentoLogin(t.Email, t.Password)\n\tif !existe {\n\t\thttp.Error(w, \"Usuario y/o Contraseña invalidos \", 400)\n\t\treturn\n\t}\n\n\tjwtKey, err := jwt.GeneroJWT(documento)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al intentar generar el Token correspondiente \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tresp := models.RespuestaLogin{\n\t\tToken: jwtKey,\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated)\n\terr = json.NewEncoder(w).Encode(resp)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al intentar codificar el token en un nuevo json \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\t// metodo para gravar token en la cookie del usuario\n\texpirationTime := time.Now().Add(24 * time.Hour)\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"token\",\n\t\tValue: jwtKey,\n\t\tExpires: expirationTime,\n\t})\n\t// ->./jwt/jwt.go\n}", "func (jar *JsonApiUrl) Get(v interface{}) {\n\tvar res *http.Response\n\tvar body[]byte\n\n\t// retrieve json of the migrated entity from the jsonapi and unmarshal the single response\n\tif len(strings.TrimSpace(jar.Username)) == 0 {\n\t\tres, body = GetResource(jar.T.(*testing.T), jar.String())\n\t} else {\n\t\tres, body = GetResourceWithBasicAuth(jar.T.(*testing.T), jar.String(), jar.Username, jar.Password)\n\t}\n\tdefer func() { _ = res.Close }()\n\tUnmarshalResponse(jar.T.(*testing.T), body, res, &JsonApiResponse{}, nil).To(v)\n}", "func CheckinPeopleGET(w http.ResponseWriter, r *http.Request) {\n\tid := r.URL.Query().Get(\"id\")\n if id == \"\" {\n\t\tError(w, fmt.Errorf(\"Required args: id\"), http.StatusBadRequest)\n\t\treturn\n }\n\n dbPerson, err := people.GetPerson(id)\n if err != nil {\n\t\tError(w, err, http.StatusNotFound)\n\t\treturn\n }\n\n\tfullImage := r.URL.Query().Get(\"full_images\")\n\tonlyImageID := r.URL.Query().Get(\"only_image_id\")\n\n resp := schema.CheckinPeoplePOSTReq{\n Person: dbPerson.Person(),\n }\n\n if fullImage != \"\" {\n if onlyImageID == \"\" {\n imgs, err := images.GetImages(dbPerson.ID, \"\")\n if err != nil {\n Error(w, err, http.StatusNotFound)\n return\n }\n resp.Images = imgs.Images\n } else {\n ids, err := images.GetImageIDs(dbPerson.ID)\n if err != nil {\n Error(w, err, http.StatusNotFound)\n return\n }\n resp.ImageIDs = ids\n }\n }\n\n\trespondJSON(resp, w, r)\n}", "func getAll(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\n\t// sending query over db object and storing respose in var result\n\tresult, err := db.Query(\"SELECT fname, lname, email, pword, id FROM person\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\n\t// to fetch one record at a time from result\n\tfor result.Next() {\n\n\t\t// creating a variable person to store the and then show it\n\t\tvar person Person\n\t\terr := result.Scan(&person.Fname, &person.Lname, &person.Email, &person.Pword, &person.Id)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tpeople = append(people, person)\n\t}\n\t// Encode json to be sent to client machine\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetPeople(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t//PopulateInitialData()\n\tjson.NewEncoder(w).Encode(people)\n}", "func IndexGET(w http.ResponseWriter, r *http.Request) {\n\t// Get session\n\tsession := session.Instance(r)\n\n\tif session.Values[\"id\"] != nil {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/auth\"\n\t\tv.Vars[\"first_name\"] = session.Values[\"first_name\"]\n\t\tv.Render(w)\n\t} else {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/anon\"\n\t\tv.Render(w)\n\t\treturn\n\t}\n}", "func getUsersHandler(c *gin.Context) {\n\tuser, _ := c.Get(JwtIdentityKey)\n\n\t// Role check.\n\tif !isAdmin(user) {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"unauthorized\"})\n\t\treturn\n\t}\n\n\tpage := c.DefaultQuery(\"page\", \"1\")\n\tcount := c.DefaultQuery(\"count\", \"10\")\n\tpageInt, _ := strconv.Atoi(page)\n\tcountInt, _ := strconv.Atoi(count)\n\n\tif page == \"0\" {\n\t\tpageInt = 1\n\t}\n\n\tvar wg sync.WaitGroup\n\tvar users *[]types.User\n\tvar usersCount int\n\n\tdb := data.New()\n\twg.Add(1)\n\tgo func() {\n\t\tusers = db.Users.GetUsers((pageInt-1)*countInt, countInt)\n\t\twg.Done()\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tusersCount = db.Users.GetUsersCount()\n\t\twg.Done()\n\t}()\n\twg.Wait()\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"code\": http.StatusOK,\n\t\t\"users\": users,\n\t\t\"count\": usersCount,\n\t})\n}", "func (r *Login) Method() string {\n\treturn \"GET\"\n}", "func GetHandler(w http.ResponseWriter, r *http.Request) {\n\tun, _, ok := r.BasicAuth()\n\tif !ok {\n\t\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(`Basic realm=\"%s\"`, BasicAuthRealm))\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(http.StatusText(http.StatusUnauthorized) + \"\\n\"))\n\t\treturn\n\t}\n\tu := &User{\n\t\tUsername: un,\n\t}\n\tif reqIsAdmin(r) && r.FormValue(\"username\") != \"\" {\n\t\tu.Username = strings.ToLower(r.FormValue(\"username\"))\n\t} else {\n\t\tcu, err := GetCurrent(r)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tu.Username = cu.Username\n\t}\n\terr := u.Get()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tjd, jerr := json.Marshal(&u)\n\tif jerr != nil {\n\t\thttp.Error(w, jerr.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(jd))\n}", "func (s *Identity) InfoGET(w http.ResponseWriter, r *http.Request) {\n\tinfo := map[string]string{\n\t\t\"version\": \"1.0\",\n\t\t\"providerName\": \"Acme\",\n\t}\n\twriteResponse(info, w, r)\n}", "func GetUser(context *gin.Context) {\n\t//TODO: implement me uwu\n\tJwtCtx := login.ExtractClaims(context)\n\t// identity claim is the username in the database\n\tusername := JwtCtx[jwt.IdentityKey]\n\tuserData := database.GetUser(username.(string))\n\tpayload := models.UserInfoPayload{\n\t\tUserCommon: userData.UserCommon,\n\t}\n\tcontext.JSON(http.StatusOK, payload)\n}", "func Search(c *gin.Context) {\n\tstatus := c.Query(\"status\")\n\n\tusers, err := services.UserService.Search(status)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, users.Marshall(c.GetHeader(\"X-Public\") == \"true\"))\n\n}", "func Login(req *restful.Request, res *restful.Response) {\n\tvar loginRequest map[string]interface{}\n\terr := json.NewDecoder(req.Request.Body).Decode(&loginRequest)\n\tif err != nil {\n\t\tres.WriteError(http.StatusInternalServerError, err)\n\t}\n\n\t//Send email with url to complete login process from here\n\tres.WriteEntity(loginRequest[\"email\"])\n}", "func editHandler(w http.ResponseWriter, r *http.Request, title string) {\n\t// Get cookie\n\tcookie, err := r.Cookie(\"V\")\n\tif err != nil || cookie == nil {\n\t\tlog.Println(\"May log out or cookie expire\", err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tcookieValue := strings.TrimPrefix(cookie.Value, \"cookie=\")\n\t// Prefetch from backend API\n\tp, err := readProfile(cookieValue)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tclient := &http.Client{}\n\t//\n\ttoken := TokenInfo{}\n\ttoken.Type = \"STANDARD\"\n\ttoken.Value = \"\"\n\ttokenData, err := json.Marshal(token)\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\ttokenBuffer := string(tokenData)\n\ttokenPayload := strings.NewReader(tokenBuffer)\n\t// Get token request\n\tgetTokenURL := \"http://localhost:8080/v1/tokens\"\n\trequest, err := http.NewRequest(\"POST\", getTokenURL, tokenPayload)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Cookie\", cookieValue)\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.Println(\"error occurred when reading response\", err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\terr = json.Unmarshal(bodyBytes, &token)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tupdateNormal := UpdateDescription{}\n\tupdateNormal.Username = p.Username\n\tupdateNormal.Description = p.Description\n\tupdateNormal.Token = token.Value\n\trenderTemplateDescription(w, \"edit\", &updateNormal)\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tid, err := strconv.Atoi(params[\"id\"])\n\tif err != nil {\n\t\tfmt.Println(\"Oops, \", err)\n\t}\n\tfor _, searchID := range models.People {\n\t\tif searchID.ID == id {\n\t\t\tjson.NewEncoder(w).Encode(searchID)\n\t\t}\n\t}\n}", "func Login(nbmaster string, httpClient *http.Client, username string, password string, domainName string, domainType string) string {\r\n fmt.Printf(\"\\nLog into the NetBackup webservices...\\n\")\r\n\r\n loginDetails := map[string]string{\"userName\": username, \"password\": password}\r\n if len(domainName) > 0 {\r\n loginDetails[\"domainName\"] = domainName\r\n }\r\n if len(domainType) > 0 {\r\n loginDetails[\"domainType\"] = domainType\r\n }\r\n loginRequest, _ := json.Marshal(loginDetails)\r\n\r\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/login\"\r\n\r\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(loginRequest))\r\n request.Header.Add(\"Content-Type\", contentTypeV2);\r\n\r\n response, err := httpClient.Do(request)\r\n\r\n token := \"\"\r\n if err != nil {\r\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\r\n panic(\"Unable to login to the NetBackup webservices.\")\r\n } else {\r\n if response.StatusCode == 201 {\r\n data, _ := ioutil.ReadAll(response.Body)\r\n var obj interface{}\r\n json.Unmarshal(data, &obj)\r\n loginResponse := obj.(map[string]interface{})\r\n token = loginResponse[\"token\"].(string)\r\n } else {\r\n printErrorResponse(response)\r\n }\r\n }\r\n\r\n return token\r\n}", "func restGet(room string, client *http.Client, ip string, port string) (*http.Response, error) {\n\treturn client.Get(fmt.Sprintf(\"http://%v/rest/%v\", net.JoinHostPort(ip, port), room))\n}", "func GetUserProfileHandler(w http.ResponseWriter, r *http.Request) {\n\n}", "func GetPeople(w http.ResponseWriter, req *http.Request ){\t\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(models.People)\n}", "func (client *ShorelineClient) Login(username, password string) (*UserData, string, error) {\n\thost := client.getHost()\n\tif host == nil {\n\t\treturn nil, \"\", errors.New(\"No known user-api hosts.\")\n\t}\n\n\thost.Path = path.Join(host.Path, \"login\")\n\n\treq, _ := http.NewRequest(\"POST\", host.String(), nil)\n\treq.SetBasicAuth(username, password)\n\n\tres, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdefer res.Body.Close()\n\n\tswitch res.StatusCode {\n\tcase 200:\n\t\tud, err := extractUserData(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\treturn ud, res.Header.Get(\"x-tidepool-session-token\"), nil\n\tcase 404:\n\t\treturn nil, \"\", nil\n\tdefault:\n\t\treturn nil, \"\", &status.StatusError{\n\t\t\tstatus.NewStatusf(res.StatusCode, \"Unknown response code from service[%s]\", req.URL)}\n\t}\n}", "func SearchIdentities(w http.ResponseWriter, r *http.Request) {\n\tapiContext := api.GetApiContext(r)\n\tauthHeader := r.Header.Get(\"Authorization\")\n\n\tif authHeader != \"\" {\n\t\t// header value format will be \"Bearer <token>\"\n\t\tif !strings.HasPrefix(authHeader, \"Bearer \") {\n\t\t\tlog.Debug(\"GetMyIdentities Failed to find Bearer token %v\", authHeader)\n\t\t\tReturnHTTPError(w, r, http.StatusUnauthorized, \"Unauthorized, please provide a valid token\")\n\t\t}\n\t\taccessToken := strings.TrimPrefix(authHeader, \"Bearer \")\n\t\tlog.Debugf(\"token is this %s\", accessToken)\n\n\t\t//see which filters are passed, if none then error 400\n\n\t\texternalId := r.URL.Query().Get(\"externalId\")\n\t\texternalIdType := r.URL.Query().Get(\"externalIdType\")\n\t\tname := r.URL.Query().Get(\"name\")\n\n\t\tif externalId != \"\" && externalIdType != \"\" {\n\t\t\t//search by id and type\n\t\t\tidentity, err := server.GetIdentity(externalId, externalIdType, accessToken)\n\t\t\tif err == nil {\n\t\t\t\tapiContext.Write(&identity)\n\t\t\t} else {\n\t\t\t\t//failed to search the identities\n\t\t\t\tlog.Errorf(\"SearchIdentities Failed with error %v\", err)\n\t\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, \"Internal Server Error\")\n\t\t\t}\n\t\t} else if name != \"\" {\n\n\t\t\tidentities, err := server.SearchIdentities(name, true, accessToken)\n\t\t\tlog.Debugf(\"identities %v\", identities)\n\t\t\tif err == nil {\n\t\t\t\tresp := client.IdentityCollection{}\n\t\t\t\tresp.Data = identities\n\n\t\t\t\tapiContext.Write(&resp)\n\t\t\t} else {\n\t\t\t\t//failed to search the identities\n\t\t\t\tlog.Errorf(\"SearchIdentities Failed with error %v\", err)\n\t\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, \"Internal Server Error\")\n\t\t\t}\n\t\t} else {\n\t\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t\t}\n\t} else {\n\t\tlog.Debug(\"No Authorization header found\")\n\t\tReturnHTTPError(w, r, http.StatusUnauthorized, \"Unauthorized, please provide a valid token\")\n\t}\n}", "func Login(res http.ResponseWriter, req *http.Request) {\n\tuser := new(model.User)\n\tID := req.Context().Value(\"ID\").(string)\n\tdata := req.Context().Value(\"data\").(*validation.Login)\n\tnow := time.Now().Unix()\n\tresponse := make(map[string]interface{})\n\tdocKey, err := connectors.ReadDocument(\"users\", ID, user)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t} else if len(docKey) == 0 {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusBadRequest, constants.NotFoundResource))\n\t\treturn\n\t}\n\ttimeDiff := time.Unix(user.OtpValidity, 0).Sub(time.Now())\n\tcompareOtp := bcrypt.CompareHashAndPassword([]byte(user.OTP), []byte(data.OTP))\n\tif compareOtp != nil || timeDiff < 0 {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusBadRequest, constants.InvalidOTP))\n\t\treturn\n\t}\n\tif user.OtpType == constants.OTPType[\"email\"] {\n\t\tuser.EmailVerify = 1\n\t} else if user.OtpType == constants.OTPType[\"phone\"] {\n\t\tuser.PhoneVerify = 1\n\t}\n\tuser.OTP, user.OtpType, user.OtpValidity, user.LastLogedIn, user.UpdatedAt = \"\", \"\", 0, now, now\n\tdocKey, err = connectors.UpdateDocument(\"users\", docKey, user)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\taccessToken, err := generateToken(docKey, \"aceessToken\", constants.AccessTokenValidity)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\trefreshToken, err := generateToken(docKey, \"refreshToken\", constants.RefreshTokenValidity)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\tresponse[\"accessToken\"] = accessToken\n\tresponse[\"refreshToken\"] = refreshToken\n\trender.Render(res, req, responses.NewHTTPSucess(http.StatusOK, response))\n}", "func Callback(c *gin.Context) {\n\tprovider := c.Param(\"provider\")\n\n\tvar logincode vo.LoginReq\n\tif err := c.ShouldBindQuery(&logincode); err != nil {\n\t\tfmt.Println(\"xxxx\", err)\n\t}\n\n\tfmt.Println(\"provider\", provider, logincode)\n\n\tuserInfo := vo.GetUserInfoFromOauth(provider, logincode.Code, logincode.State)\n\tfmt.Println(\"get user info\", userInfo)\n\n\tif userInfo == nil {\n\t\tc.JSON(http.StatusOK, sailor.HTTPAirdbResponse{\n\t\t\tCode: enum.AirdbSuccess,\n\t\t\tSuccess: true,\n\t\t\tData: vo.LoginResp{\n\t\t\t\tNickname: \"xxx\",\n\t\t\t\tHeadimgurl: \"xxx.png\",\n\t\t\t},\n\t\t})\n\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, sailor.HTTPAirdbResponse{\n\t\tCode: enum.AirdbSuccess,\n\t\tSuccess: true,\n\t\tData: vo.LoginResp{\n\t\t\tNickname: userInfo.Login,\n\t\t\tHeadimgurl: userInfo.AvatarURL,\n\t\t},\n\t})\n}", "func Login(c echo.Context) error {\r\n\r\n\tconfig := config.GetInstance()\r\n\r\n\tbody := make(map[string]interface{})\r\n\terr := json.NewDecoder(c.Request().Body).Decode(&body)\r\n\tif err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 1,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: \"Errore interno\",\r\n\t\t})\r\n\t}\r\n\r\n\tbody[\"command-name\"] = \"login\"\r\n\r\n\tform := url.Values{}\r\n\r\n\tform.Add(\"command-name\", body[\"command-name\"].(string))\r\n\tform.Add(\"name\", body[\"username\"].(string))\r\n\tform.Add(\"password\", body[\"password\"].(string))\r\n\r\n\tURLRequest := config.GetRemoteURL()\r\n\r\n\treq, err := http.NewRequest(\"POST\", URLRequest+\"/process-request.php\", bytes.NewBufferString(form.Encode()))\r\n\r\n\tif err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 2,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: err.Error(),\r\n\t\t})\r\n\t}\r\n\r\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded; param=value;charset=UTF-8\")\r\n\r\n\tsetCookie(req, \"auth-key\", config.RemoteAuthKey)\r\n\r\n\tclient := &http.Client{}\r\n\r\n\tres, err := client.Do(req)\r\n\tif err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 3,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: err.Error(),\r\n\t\t})\r\n\t}\r\n\r\n\tdefer res.Body.Close()\r\n\r\n\tsetSession(c, res)\r\n\r\n\tvar httpResponseData models.HTTPResponse\r\n\r\n\tif err := json.NewDecoder(res.Body).Decode(&httpResponseData); err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 4,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: err.Error(),\r\n\t\t})\r\n\t}\r\n\r\n\treturn c.JSON(200, httpResponseData)\r\n}", "func getPi(w http.ResponseWriter, r *http.Request) {\n\t// Get pi name from request\n\tvars := mux.Vars(r)\n\tpiname := vars[\"piname\"]\n\n\t// Retrieve pi object from data store\n\tc := appengine.NewContext(r)\n\tq := datastore.NewQuery(piListKind).Filter(\"name =\", piname)\n\tt := q.Run(c)\n\tvar pi Pi\n\t_, err := t.Next(&pi)\n\tif err == datastore.Done {\n\t\thttp.Error(w, \"404 Not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Return JSON representatikon of Pi object\n\tbuffer, _ := json.MarshalIndent(pi, \"\", \" \")\n\tfmt.Fprint(w, string(buffer))\n}", "func getUser(w http.ResponseWriter, r *http.Request) {\n\t// set header.\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar user schema.User\n\n\tid := strings.TrimPrefix(r.URL.Path, \"/users/\") // Extracting user id from the URL by performing expression/pattern matching\n\t// OR\n\t// re := regexp.MustCompile(\"/users/([!-z]+)\")\n\t// id := re.FindStringSubmatch(r.URL.Path)[1] \n\n\tfilter := bson.M{\"id\": id}\n\t\n\terr := users.FindOne(context.TODO(), filter).Decode(&user)\n\n\tif err != nil {\n\t\tlog.Fatal(err, w)\n\t}\n\n\tjson.NewEncoder(w).Encode(user)\n}", "func (c *Client) get(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"GET\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}", "func List(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tlistHandler(w, authUser, false)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Login endpoint hit\")\n\t\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := models.User{}\n\n\tif user.Authorise(username, password) {\n\t\tjson.NewEncoder(w).Encode(user)\n\t} else {\n\t\tm := make(map[string]string)\n\t\tm[\"Message\"] = \"Username and password do not match\"\n\t\tjson.NewEncoder(w).Encode(m)\n\t}\n}" ]
[ "0.63776165", "0.6154853", "0.615378", "0.6062602", "0.59676594", "0.5934943", "0.5893324", "0.58626664", "0.5861018", "0.5853691", "0.584366", "0.5807749", "0.5805815", "0.57685137", "0.5765969", "0.57202905", "0.57076734", "0.57067597", "0.5703087", "0.5691566", "0.5685883", "0.5660162", "0.56445765", "0.56265336", "0.55809003", "0.55656177", "0.5553285", "0.553637", "0.5525778", "0.55164045", "0.5510464", "0.5487555", "0.54866415", "0.5481695", "0.5478648", "0.54775065", "0.54551005", "0.5440581", "0.54211783", "0.5415237", "0.5413503", "0.5411977", "0.54089266", "0.5401512", "0.5397677", "0.53892773", "0.53698754", "0.5361653", "0.53596276", "0.5352561", "0.53478104", "0.5345945", "0.5341571", "0.5341365", "0.5335537", "0.5332959", "0.5315115", "0.5314193", "0.5308738", "0.53075933", "0.5304144", "0.5299119", "0.52990764", "0.5297171", "0.52956784", "0.5291283", "0.5290496", "0.5286682", "0.52856785", "0.5283104", "0.5276968", "0.5274148", "0.5272121", "0.52714044", "0.5271322", "0.52695537", "0.526459", "0.5262972", "0.5262857", "0.52627116", "0.5257182", "0.5257152", "0.52569246", "0.52562577", "0.5252125", "0.52467746", "0.5238802", "0.52384514", "0.5237666", "0.5235135", "0.5234841", "0.52337176", "0.5229506", "0.5229324", "0.52290297", "0.52267766", "0.521875", "0.5216769", "0.52166325", "0.52136546" ]
0.76519233
0
LoginGET displays the login page
LoginGET отображает страницу входа
func LoginGET(w http.ResponseWriter, r *http.Request) { sess := model.Instance(r) v := view.New(r) v.Name = "login/login" v.Vars["token"] = csrfbanana.Token(w, r, sess) // Refill any form fields view.Repopulate([]string{"cuenta","password"}, r.Form, v.Vars) v.Render(w) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func LoginGET(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"login.html\", gin.H{})\n}", "func (m *Repository) GetLogin(w http.ResponseWriter, r *http.Request) {\n\tif m.App.Session.Exists(r.Context(), \"user_id\") {\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\trender.Template(w, r, \"login.page.tmpl\", &models.TemplateData{\n\t\tForm: forms.New(nil),\n\t})\n}", "func handleLoginGET(w http.ResponseWriter, req *http.Request) {\n\ttmpl, err := template.ParseFiles(\"./templates/login.html\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tdata := LoginPage {\n\t\tTitle: \"Login\",\n\t}\n\n\ttmpl.Execute(w, data)\n}", "func GetLogin(w http.ResponseWriter, req *http.Request, app *App) {\n\tif models.UserCount(app.Db) > 0 {\n\t\trender(w, \"admin/login\", map[string]interface{}{\"hideNav\": true}, app)\n\t} else {\n\t\thttp.Redirect(w, req, app.Config.General.Prefix+\"/register\", http.StatusSeeOther)\n\t}\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\trender(w, \"login\", pageVars)\n}", "func UsersLoginGet(c buffalo.Context) error {\n\treturn c.Render(200, r.HTML(\"users/login\"))\n}", "func showLoginPage(c *gin.Context) {\n\trender(c, gin.H{\n\t\t\"title\": \"Login\",\n\t\t\"ErrorMessage\": \"\",\n\t}, \"login.html\")\n}", "func Login(res http.ResponseWriter, req *http.Request) {\n\tdata := struct{ Title string }{\"Login\"}\n\ttemplates.ExecuteTemplate(res, \"login\", data)\n}", "func (c Control) ServeLogin(w http.ResponseWriter, r *http.Request) {\n\ttemplate := map[string]interface{}{\"error\": false}\n\tif r.Method == http.MethodPost {\n\t\t// Get their submitted hash and the real hash.\n\t\tpassword := r.PostFormValue(\"password\")\n\t\thash := HashPassword(password)\n\t\tc.Config.RLock()\n\t\trealHash := c.Config.AdminHash\n\t\tc.Config.RUnlock()\n\t\t// Check if they got the password correct.\n\t\tif hash == realHash {\n\t\t\ts, _ := Store.Get(r, \"sessid\")\n\t\t\ts.Values[\"authenticated\"] = true\n\t\t\ts.Save(r, w)\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\t\treturn\n\t\t}\n\t\ttemplate[\"error\"] = true\n\t}\n\n\t// Serve login page with no template.\n\tdata, err := Asset(\"templates/login.mustache\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\tcontent := mustache.Render(string(data), template)\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tw.Write([]byte(content))\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"login called\")\n}", "func (app *Application) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]interface{}\n\tdata = make(map[string]interface{})\n\tfmt.Println(\"login.html\")\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\tuname := r.FormValue(\"username\")\n\t\tpword := r.FormValue(\"password\")\n\t\torg := r.FormValue(\"org\")\n\t\tprintln(uname, pword, org)\n\t\t//according uname, comparing pword with map[uname]\n\t\tfor _, v := range webutil.Orgnization[org] {\n\t\t\tfmt.Println(\"org user\", v.UserName)\n\t\t\tif v.UserName == uname {\n\t\t\t\tif v.Secret == pword {\n\t\t\t\t\twebutil.MySession.SetSession(uname, org, w)\n\t\t\t\t\thttp.Redirect(w, r, \"./home.html\", 302)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\t//login failed redirect to login page and show failed\n\t\tdata[\"LoginFailed\"] = true\n\t\tloginTemplate(w, r, \"login.html\", data)\n\t\treturn\n\t}\n\tloginTemplate(w, r, \"login.html\", data)\n}", "func (s TppHTTPServer) Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tdata := LoginPageData{PageTitle: \"AXA Pay Bank Login\", BankID: s.BankID, PIN: s.PIN}\n\t//fmt.Fprint(w, \"TPP server reference PISP Login\\n\")\n\ttmpl := template.Must(template.ParseFiles(\"api/login.html\"))\n\tr.ParseForm()\n\tlog.Println(\"Form:\", r.Form)\n\ttmpl.Execute(w, data)\n\n}", "func (a Authentic) login(c buffalo.Context) error {\n\treturn c.Render(200, a.Config.LoginPage)\n}", "func Login(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tfmt.Println(\"Login\")\n}", "func Login(ctx echo.Context) error {\n\n\tf := forms.New(utils.GetLang(ctx))\n\tutils.SetData(ctx, \"form\", f)\n\n\t// set page tittle to login\n\tutils.SetData(ctx, settings.PageTitle, \"login\")\n\n\treturn ctx.Render(http.StatusOK, tmpl.LoginTpl, utils.GetData(ctx))\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\takagi := user{\n\t\t\tName: \"Nguyen Hoai Phuong\",\n\t\t\tPassword: \"1234\",\n\t\t}\n\n\t\tbs, err := json.Marshal(akagi)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Encode user error:\", err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bs)\n\t} else if r.Method == \"POST\" {\n\t\terr := r.ParseForm()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tuser := r.FormValue(\"username\")\n\t\tpass := r.FormValue(\"password\")\n\t\tfmt.Println(user)\n\t\tfmt.Println(pass)\n\t\thttp.Redirect(w, r, \"/login\", http.StatusOK)\n\t\tfmt.Fprintf(w, \"User name: %s\\nPassword : %s\\n\", user, pass)\n\t}\n\n}", "func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}", "func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\n\tchallenge, err := readURLChallangeParams(r, \"login\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tif r.Form == nil {\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tuserName := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\tloginChallenge := r.Form.Get(\"challenge\")\n\t\tpass, err := h.LoginService.CheckPasswords(userName, password)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tif pass {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(userName)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", loginChallenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\t\t}\n\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, true)\n\t\ttemplLogin.Execute(w, loginData)\n\t} else {\n\t\tchallengeBody, err := h.LoginService.ReadChallenge(challenge, \"login\")\n\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Print(err)\n\t\t}\n\n\t\tif !challengeBody.Skip {\n\t\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, false)\n\t\t\ttemplLogin.Execute(w, loginData)\n\t\t} else {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(challengeBody.Subject)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", challenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\n\t\t}\n\t}\n}", "func getLoginHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tif database.RetrieveUsersCount() == 0 {\n\t\thttp.Redirect(w, r, \"/admin/register\", http.StatusFound)\n\t\treturn\n\t}\n\thttp.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, \"login.html\"))\n\treturn\n}", "func loginPage(w http.ResponseWriter, r *http.Request){\n\terr := templ.ExecuteTemplate(w, \"login\", nil)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tappengineContext := appengine.NewContext(r)\n\tappengineUser := user.Current(appengineContext)\n\tif appengineUser != nil {\n\t\turl, err := user.LogoutURL(appengineContext, \"/\")\n\t\tif err == nil {\n\t\t\tw.Header().Set(\"Location\", url)\n\t\t\tw.WriteHeader(http.StatusFound)\n\t\t\treturn\n\t\t}\n\t}\n\tw.Header().Set(\"Location\", \"/\")\n\tw.WriteHeader(http.StatusFound)\n}", "func login(w http.ResponseWriter, r *http.Request) {\n clearCache(w)\n exists, _ := getCookie(r, LOGIN_COOKIE)\n if exists {\n http.Redirect(w, r, \"/home\", http.StatusSeeOther)\n return\n }\n if r.Method == http.MethodGet {\n LOG[INFO].Println(\"Login Page\")\n http.ServeFile(w, r, \"../../web/login.html\")\n } else if r.Method == http.MethodPost {\n LOG[INFO].Println(\"Executing Login\")\n r.ParseForm()\n LOG[INFO].Println(\"Form Values: Username\", r.PostFormValue(\"username\"))\n passhash := sha512.Sum512([]byte(r.PostFormValue(\"password\")))\n LOG[INFO].Println(\"Hex Encoded Passhash:\", hex.EncodeToString(passhash[:]))\n response := sendCommand(CommandRequest{CommandLogin, struct{\n Username string\n Password string\n }{\n r.PostFormValue(\"username\"),\n hex.EncodeToString(passhash[:]),\n }})\n if response == nil {\n http.SetCookie(w, genCookie(ERROR_COOKIE, \"Send Command Error\"))\n http.Redirect(w, r, \"/error\", http.StatusSeeOther)\n return\n }\n if !response.Success {\n LOG[WARNING].Println(StatusText(response.Status))\n http.Redirect(w, r, \"/login\", http.StatusSeeOther)\n return\n }\n\n LOG[INFO].Println(\"Successfully Logged In\")\n http.SetCookie(w, genCookie(LOGIN_COOKIE, r.PostFormValue(\"username\")))\n http.Redirect(w, r, \"/home\", http.StatusSeeOther)\n }\n}", "func logIn(res http.ResponseWriter, req *http.Request) {\n\t// retrive the name form URL\n\tname := req.FormValue(\"name\")\n\tname = html.EscapeString(name)\n\tif name != \"\" {\n\t\tuuid := generateUniqueId()\n\t\tsessionsSyncLoc.Lock()\n\t\tsessions[uuid] = name\n\t\tsessionsSyncLoc.Unlock()\n\n\t\t// save uuid in the cookie\n\t\tcookie := http.Cookie{Name: \"uuid\", Value: uuid, Path: \"/\"}\n\t\thttp.SetCookie(res, &cookie)\n\n\t\t// redirect to /index.html endpoint\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t} else {\n\t\t// if the provided input - name is empty, display this message\n\t\tres.Header().Set(\"Content-Type\", \"text/html\")\n\t\tfmt.Fprintf(\n\t\t\tres,\n\t\t\t`<html>\n\t\t\t<body>\n\t\t\t<form action=\"login\">\n\t\t\t C'mon, I need a name.\n\t\t\t</form>\n\t\t\t</p>\n\t\t\t</body>\n\t\t\t</html>`,\n\t\t)\n\t}\n}", "func loginFormHandler(w http.ResponseWriter, r *http.Request) {\n\tb.pageDisplayer.DisplayPage(w, \"login_form.html\", nil)\n}", "func (_ *Auth) Login(c *gin.Context) {\n\n\tflash := helper.GetFlash(c)\n\tc.HTML(http.StatusOK, \"auth/login.tpl\", gin.H{\n\t\t\"title\": \"Gin Blog\",\n\t\t\"flash\": flash,\n\t})\n}", "func (uc *UserController) Login(w http.ResponseWriter, r *http.Request) {\n\tvar loginInfo models.User\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.Decode(&loginInfo)\n\tresp, token, _, _, _ := uc.User.GET(loginInfo.Username, loginInfo.Password)\n\tif token != \"\" {\n\t\tjson.NewEncoder(w).Encode(resp)\n\t}\n}", "func HandlerLogin(responseWriter http.ResponseWriter, request *http.Request) {\n\trequest.ParseForm()\n\n\tif request.Method == STR_GET {\n\t\tServeLogin(responseWriter, STR_EMPTY)\n\t} else {\n\t\tvar userName string = request.FormValue(API_KEY_username)\n\t\tvar password string = request.FormValue(API_KEY_password)\n\t\tif userName == STR_EMPTY || password == STR_EMPTY {\n\t\t\tServeLogin(responseWriter, \"Please enter username and password\")\n\t\t\treturn\n\t\t}\n\n\t\tvar userId = -1\n\t\tvar errorUser error = nil\n\t\tuserId, errorUser = DbGetUser(userName, password, nil)\n\t\tif errorUser != nil {\n\t\t\tlog.Printf(\"HandlerLogin, errorUser=%s\", errorUser.Error())\n\t\t}\n\t\tif userId > -1 {\n\t\t\ttoken := DbAddToken(userId, nil)\n\t\t\tAddCookie(responseWriter, token)\n\t\t\thttp.Redirect(responseWriter, request, GetApiUrlListApiKeys(), http.StatusTemporaryRedirect)\n\t\t} else {\n\t\t\tServeLogin(responseWriter, \"Wrong username or password\")\n\t\t}\n\t}\n}", "func (h *TestAuth) Login(w http.ResponseWriter, req *http.Request) {\n\n\tresponse := make(map[string]string, 5)\n\n\tresponse[\"state\"] = authz.AuthNewPasswordRequired\n\tresponse[\"access_token\"] = \"access\"\n\t//response[\"id_token\"] = *authResult.IdToken\n\tresponse[\"refresh_token\"] = \"refersh\"\n\tresponse[\"expires\"] = \"3600\"\n\tresponse[\"token_type\"] = \"Bearer\"\n\trespData, _ := json.Marshal(response)\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func LoginGetHandler(ctx *enliven.Context) {\n\tif ctx.Enliven.Core.Email.Enabled() {\n\t\tctx.Strings[\"ForgotPasswordURL\"] = config.GetConfig()[\"user_forgot_password_route\"]\n\t}\n\tctx.ExecuteBaseTemplate(\"user_login\")\n}", "func (db *MyConfigurations) showLoginPage(c echo.Context) error {\n\tstatus, message := getFlashMessages(&c) // gets the flash message and status if there was any\n\tusers := models.GetAllUsers(db.GormDB) // gets all the users that are in the database\n\tvaluesToReturn := echo.Map{\n\t\t\"status\": status, // pass the status of the flash message\n\t\t\"message\": message, // pass the message\n\t\t\"title\": \"تسجيل دخول\", // the title of the page\n\t\t\"hideNavBar\": true, // boolean to indicate weather or not the NavBar should be displayed\n\t\t\"users\": users, // pass the users array to display to the user\n\t}\n\tif checkIfRequestFromMobileDevice(c) {\n\t\treturn c.JSON(http.StatusOK, &valuesToReturn)\n\t}\n\treturn c.Render(http.StatusOK, \"login.html\", &valuesToReturn)\n}", "func LoginAction(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\n\tuserName := r.FormValue(\"userName\")\n\t// validate username\n\tif len(userName) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Username specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\t// validate password\n\tif len(password) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Password specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t// get expected password\n\texpectedPassword := getStringFromDB(\"Users\", userName)\n\n\t// verify the password\n\tif expectedPassword != password {\n\t\thttp.Redirect(w, r, \"/login?errorM=Invalid credentials\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t\n\t// Create a new random session token\n\tsessionToken, err := uuid.NewUUID()\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/login?errorM=Unable to create token\", http.StatusSeeOther)\n\t}\n\t// Set the token in the db, along with the userName\n\tupdateDBString(\"Sessions\", userName, sessionToken.String())\n\n\t// set the expiration time\n\texpires := time.Now().Add(600 * time.Second)\n\tck := http.Cookie{\n Name: \"JSESSION_ID\",\n Path: \"/\",\n\t\tExpires: expires,\n\t\tValue: userName+\"_\"+sessionToken.String(),\n\t}\n\n // write the cookie to response\n http.SetCookie(w, &ck)\n\thttp.Redirect(w, r, \"/listbuckets\", http.StatusSeeOther)\n\n}", "func (server Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) // mux params\n\tusername := vars[\"username\"] // get username\n\tpassword := vars[\"password\"] // get password\n\tvar res models.APIResponse // make a response\n\n\tif username == \"\" || password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Bad Request. Empty username or password\", nil)\n\t} else {\n\t\tvar data = checkLogin(username, password, server.db) //create the data\n\t\tres = models.BuildAPIResponseSuccess(\"Login successful\", data)\n\t}\n\tjson.NewEncoder(w).Encode(res) //encode the data\n\n}", "func LoginPage(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"Login.html\", gin.H{\n\t\t\"loginURL\": \"http://127.0.0.1:8080/user/login\",\n\t})\n}", "func LoginHandler(c echo.Context) error {\n\treturn c.JSON(http.StatusOK, c.QueryParams())\n}", "func LoginRoute(res http.ResponseWriter, req *http.Request) {\n if req.Method == \"GET\" {\n res.Write([]byte(`\n <html>\n <head>\n <title> Login </title>\n </head>\n <body>\n <h1> Login </h1>\n <form action = \"/login\" method = \"post\">\n Username:<br>\n <input type=\"text\" name=\"Username\"><br>\n Password:<br>\n <input type = \"password\" name = \"Password\">\n <input type = \"submit\" value = \"Login\">\n </form>\n </body>\n </html>\n `))\n } else {\n req.ParseForm()\n username := req.FormValue(\"Username\")\n password := req.FormValue(\"Password\")\n\n uid, err := CheckUser(username, password)\n if err == nil {\n\n session := http.Cookie{\n Name: \"session\",\n Value: strconv.Itoa(uid),\n\n //MaxAge: 10 * 60,\n Secure: false,\n HttpOnly: true,\n SameSite: 1,\n\n Path: \"/\",\n }\n http.SetCookie(res, &session)\n Redirect(\"/library\", res)\n } else {\n res.Write([]byte(err.Error()))\n }\n }\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\t/*\n\t\tTratamento dos dados vindos do front-end\n\t\tNesse caso, o request pega login e senha\n\t*/\n\tvar login models.Credentials\n\tbody := r.Body\n\tbytes, err := util.BodyToBytes(body)\n\terr = util.BytesToStruct(bytes, &login)\n\n\t// Checks if struct is a valid one\n\tif err = validation.Validator.Struct(login); err != nil {\n\n\t\tlog.Printf(\"[WARN] invalid user information, because, %v\\n\", err)\n\t\tw.WriteHeader(http.StatusPreconditionFailed) // Status 412\n\t\treturn\n\t}\n\n\t// err1 consulta o login no banco de dados\n\terr1 := database.CheckLogin(login.Login)\n\n\t// err2 consulta a senha referente ao login fornecido\n\terr2 := database.CheckSenha(login.Login, login.Senha)\n\n\t// Condicao que verifica se os dois dados constam no banco de dados\n\tif (err1 != nil) || (err2 != true) {\n\t\tlog.Println(\"[FAIL]\")\n\t\tw.WriteHeader(http.StatusForbidden) // Status 403\n\t} else {\n\t\tlog.Println(\"[SUCCESS]\")\n\t\tw.WriteHeader(http.StatusAccepted) // Status 202\n\t}\n\n\treturn\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\t_, err := req.Cookie(\"login\")\n\tif err == nil {\n\t\thttp.Redirect(res, req, \"app\", http.StatusSeeOther)\n\t}\n\tTPL.ExecuteTemplate(res, \"login\", nil)\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"login\")\n}", "func (h *auth) Login(c echo.Context) error {\n\t// Filter params\n\tvar params service.LoginParams\n\tif err := c.Bind(&params); err != nil {\n\t\tlog.Println(\"Could not get parameters:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not get credentials.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" || params.Password == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"No email or password provided.\"))\n\t}\n\n\treturn h.login(c, params)\n\n}", "func ShowLoginPage(c *gin.Context) {\n\trender(c, gin.H{\n\t\t\"title\": \"Login\",\n\t}, \"login.html\")\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\n\t// Start the session.\n\tsession := sessions.Start(w, r)\n\tif len(session.GetString(\"username\")) != 0 && checkErr(w, r, err) {\n\t\t// Redirect to index page if the user isn't signed in. Will remove later.\n\t\thttp.Redirect(w, r, \"/\", 302)\n\t}\n\n\tif r.Method != \"POST\" {\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Log In\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"login.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tusers := QueryUser(username)\n\n\t// Compare inputted password to the password in the database. If they're the same, return nil.\n\tvar password_compare = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password))\n\n\tif password_compare == nil {\n\n\t\tsession := sessions.Start(w, r)\n\t\tsession.Set(\"username\", users.Username)\n\t\tsession.Set(\"user_id\", users.ID)\n\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t} else {\n\n\t\thttp.Redirect(w, r, \"/login\", 302)\n\n\t}\n\n}", "func JLoginGET(w http.ResponseWriter, r *http.Request) {\n var params httprouter.Params\n\tsess := model.Instance(r)\n\n\tv := view.New(r)\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n\n params = context.Get(r, \"params\").(httprouter.Params)\n cuenta := params.ByName(\"cuenta\")\n password := params.ByName(\"password\")\n stEnc, _ := base64.StdEncoding.DecodeString(password)\n\t password = string(stEnc)\n var jpers model.Jperson\n jpers.Cuenta = cuenta\n\tpass, err := (&jpers).JPersByCuenta()\n\tif err == model.ErrNoResult {\n loginAttempt(sess)\n\t} else {\n\t\tb:= passhash.MatchString(pass, password)\n if b && jpers.Nivel > 0{ var js []byte\n\t\t js, err = json.Marshal(jpers)\n if err == nil{\n\t\t\tmodel.Empty(sess)\n\t\t\tsess.Values[\"id\"] = jpers.Id\n sess.Save(r, w)\n w.Header().Set(\"Content-Type\", \"application/json\")\n w.Write(js)\n\t\t\treturn\n }\n\t }\n }\n log.Println(err)\n//\t http.Error(w, err.Error(), http.StatusBadRequest)\n http.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n }", "func genericLoginPage(s *data.Site, u *data.User) *contentBuffers {\n\tvar cb contentBuffers\n\n\tcb.head.WriteString(`<title>Log In</title><link rel=\"shortcut icon\" href=\"`)\n\tif s.Favicon == \"\" {\n\t\tcb.head.WriteString(userContentSrc + `favicon.png\">`)\n\t} else {\n\t\tcb.head.WriteString(s.Favicon + `\">`)\n\t}\n\n\tcb.head.WriteString(\"<style>#msg {color: #EF5350;}</style>\")\n\n\tcb.body.WriteString(\"<h2>Log in to your account</h2>\")\n\n\tif u.Role != users.RoleNone {\n\t\tcb.body.WriteString(`<h4 id=\"msg\">You are already logged in as the user: ` + u.Uname + `</h4>`)\n\t\tcb.body.WriteString(`<form action=\"/api/user/logout\" method=\"POST\"><input type=\"submit\" value=\"Log Out\"></form>`)\n\t} else {\n\t\tcb.body.WriteString(`<h4 id=\"msg\"></h4>\n\t\t<form action=\"/api/user/login-form\" method=\"POST\">\n\t\t\t<label for=\"user\">Username or Email Address</label><br>\n\t\t\t<input type=\"text\" name=\"user\" id=\"user\"><br>\n\t\t\t<label for=\"pass\">Password</label><br>\n\t\t\t<input type=\"password\" name=\"pass\" id=\"pass\"><br>\n\t\t\t<input type=\"submit\" value=\"Log In\">\n\t\t</form>\n\t\t<script>\n\t\t\tvar msgR = new RegExp(/msg=([^&]*)/);\n\t\t\tconst msgMatch = msgR.exec(window.location.search);\n\t\t\tif (msgMatch) {\n\t\t\t\tif (msgMatch[1] !== \"\") { document.getElementById(\"msg\").innerHTML = decodeURIComponent(msgMatch[1]); }\n\t\t\t}\n\t\t</script>`)\n\t}\n\n\treturn &cb\n}", "func Login(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\ttmp := []string{\n\t\t\"user.login\",\n\t\t\"default.layout\",\n\t\t\"default.navigation\",\n\t}\n\thelper.ProcessTemplates(w, \"layout\", nil, tmp...)\n}", "func Login(c *gin.Context) {\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\temail := c.PostForm(\"email\")\n\t//check if provided user credentials are valid or not\n\tif store.ValidUser(username, password, email) {\n\t\ttoken := generateSessionToken()\n\t\tc.SetCookie(\"token\", token, 3600, \"\", \"\", false, true)\n\t\tc.Set(\"is_logged_in\", true)\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Successful Login\"}, \"login-successful.html\")\n\t} else {\n\t\tc.HTML(http.StatusBadRequest, \"login.html\", gin.H{\n\t\t\t\"ErrorTitle\": \"Login Failed\",\n\t\t\t\"ErrorMessage\": \"Invalid credentials provided\"})\n\t}\n}", "func LoadLoginPage(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\n\tif cookie[\"token\"] != \"\" {\n\t\thttp.Redirect(w, r, \"/feed\", 302)\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"login.html\", nil)\n}", "func HandleLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tvalues := LoginFormValues{}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&values, r.PostForm)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\tacc, err := data.GetAccountByHandle(values.Handle)\n\tif err == mgo.ErrNotFound {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tm := acc.Password.Match(values.Password)\n\tif !m {\n\t\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tsess, err := store.Get(r, \"s\")\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tsess.Values[\"accountID\"] = acc.ID.Hex()\n\tsess.Save(r, w)\n\thttp.Redirect(w, r, \"/tasks\", http.StatusSeeOther)\n}", "func loginHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\tcounter.Increment(\"login\")\n\n\t// get the requested username\n\tusername := req.FormValue(\"name\")\n\tif len(username) < 1 {\n\t\trenderBaseTemplate(res, \"login_error.html\", nil)\n\t} else {\n\t\terr := session.Create(res, username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Login endpoint hit\")\n\t\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := models.User{}\n\n\tif user.Authorise(username, password) {\n\t\tjson.NewEncoder(w).Encode(user)\n\t} else {\n\t\tm := make(map[string]string)\n\t\tm[\"Message\"] = \"Username and password do not match\"\n\t\tjson.NewEncoder(w).Encode(m)\n\t}\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\ttmpl := template.Must(template.ParseFiles(\"templates/login.html\"))\n\tif r.Method != http.MethodPost {\n\t\ttmpl.Execute(w, nil)\n\t}\n\n\tdetails := userLogin{\n\t\tUsername: r.FormValue(\"username\"),\n\t\tPassword: r.FormValue(\"psw\"),\n\t}\n\n\tlog.Println(details)\n\t//Attempt login by calling LDAP verify credentials\n\tlog.Println(\"Username: \" + details.Username)\n\tlog.Println(\"Pass: \" + details.Password)\n\tauth := verifyCredentials(details.Username, details.Password)\n\tlog.Println(auth)\n\n\t//authorize user and create JWT\n\tif auth {\n\t\tfmt.Println(\"starting auth ...\")\n\t\tfor _, cookie := range r.Cookies() {\n\t\t\tfmt.Print(\"Cookie User: \")\n\t\t\tfmt.Println(w, cookie.Name)\n\t\t\treadJWT(cookie.Name)\n\t\t}\n\t\ttoken := generateJWT(details.Username)\n\t\tsetJwtCookie(token, w, r)\n\t\thttp.Redirect(w, r, \"/dashboard\", http.StatusSeeOther)\n\t}\n\n}", "func (app *application) login(w http.ResponseWriter, r *http.Request) {\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"email\", \"password\")\n\tform.MatchesPattern(\"email\", forms.RxEmail)\n\tif !form.Valid() {\n\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\treturn\n\t}\n\tvar id int\n\tif form.Get(\"accType\") == \"customer\" {\n\t\tid, err = app.customers.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"customerID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/customer/home\", http.StatusSeeOther)\n\t} else {\n\t\tid, err = app.vendors.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"vendorID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/vendor/home\", http.StatusSeeOther)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tdata := authInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tutils.JSONRespnseWithErr(w, &utils.ErrPostDataNotCorrect)\n\t\treturn\n\t}\n\tmessage := models.Login(data.Email, data.Password)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func Login(res http.ResponseWriter, req *http.Request) (bool, string) {\n\tname := req.FormValue(NameParameter)\n\tname = html.EscapeString(name)\n\tlog.Debugf(\"Log in user. Name: %s\", name)\n\tif name != \"\" {\n\t\tuuid := generateRandomUUID()\n\t\tsuccess := authClient.SetRequest(uuid, name)\n\t\tif success {\n\t\t\tcookiesManager.SetCookieValue(res, CookieName, uuid)\n\t\t}\n\t\t// successfully loged in\n\t\tif success {\n\t\t\treturn success, \"\"\n\t\t} else {\n\t\t\treturn success, \"authServerFail\"\n\t\t}\n\n\t}\n\n\treturn false, \"noName\"\n}", "func Login() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\temail := r.FormValue(\"email\")\n\t\t// validate email\n\t\tpw := r.FormValue(\"pw\")\n\t\t// validate pass\n\n\t\tlog.Println(\"email:\", email)\n\t\tlog.Println(\"pw:\", pw)\n\t}\n}", "func Login(username string, password string) error {\n\tdata := url.Values{}\n\tdata.Set(\"login\", username)\n\tdata.Set(\"haslo\", password)\n\n\tres, err := http.Post(loginURL, \"application/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to make HTTP POST login request: %v\", err)\n\t}\n\n\tlog.Println(\"auth status:\", res.Status)\n\n\treturn nil\n}", "func (s *HttpServer) loginForm(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\ts.RenderTemplate(ctx, w, \"login\", nil)\n}", "func LoginPage(w http.ResponseWriter, r *http.Request) { \n tmpl, err := template.ParseFiles(\"templates/loginPage.html\")\n if err != nil {\n fmt.Println(err)\n }\n var user helpers.User\n credentials := userCredentials{\n EmailId: r.FormValue(\"emailId\"),\n Password: r.FormValue(\"password\"), \n }\n\n login_info := dbquery.GetUserByEmail(credentials.EmailId)\n user = helpers.User{\n UserId: login_info.UserId,\n FirstName: login_info.FirstName,\n LastName: login_info.LastName, \n Role: login_info.Role,\n Email: login_info.Email,\n \n }\n\n var emailValidation string\n\n _userIsValid := CheckPasswordHash(credentials.Password, login_info.Password)\n\n if !validation(login_info.Email, credentials.EmailId, login_info.Password, credentials.Password) {\n emailValidation = \"Please enter valid Email ID/Password\"\n }\n\n if _userIsValid {\n setSession(user, w)\n http.Redirect(w, r, \"/dashboard\", http.StatusFound)\n }\n\n var welcomeLoginPage string\n welcomeLoginPage = \"Login Page\"\n\n tmpl.Execute(w, Response{WelcomeMessage: welcomeLoginPage, ValidateMessage: emailValidation}) \n \n}", "func loginprompt(w http.ResponseWriter, r *http.Request) {\n\t_, tid := GetAndOrUpdateSession(w, r)\n\tif tid != \"\" {\n\t\tshowMessage(w, \"Error: already logged in\",\n\t\t\t\"You are already logged in\", tid, \"\")\n\t\treturn\n\t}\n\ttemplate.Must(template.New(\"\").Parse(tLoginPrompt)).Execute(w, map[string]string{\n\t\t\"PageTitle\": \"Please log in\",\n\t\t\"Team\": r.FormValue(\"team\"),\n\t\t// TODO URL escaping would be pretty sweet\n\t\t\"TeamURL\": url.QueryEscape(r.FormValue(\"team\")),\n\t})\n}", "func (h *AuthHandlers) Login(w http.ResponseWriter, req *http.Request) {\n\tvar err error\n\tvar data []byte\n\n\tsystemContext, err := h.getSystemContext(req)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"request context retrevial failure\")\n\t\tmiddleware.ReturnError(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tif data, err = ioutil.ReadAll(req.Body); err != nil {\n\t\tlog.Error().Err(err).Msg(\"read body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\tdefer req.Body.Close()\n\n\tloginDetails := &authz.LoginDetails{}\n\tif err := json.Unmarshal(data, loginDetails); err != nil {\n\t\tlog.Error().Err(err).Msg(\"marshal body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\n\tif err := h.validate.Struct(loginDetails); err != nil {\n\t\tmiddleware.ReturnError(w, \"validation failure \"+err.Error(), 500)\n\t\treturn\n\t}\n\tloginDetails.OrgName = strings.ToLower(loginDetails.OrgName)\n\tloginDetails.Username = strings.ToLower(loginDetails.Username)\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login attempt\")\n\n\torgData, err := h.getOrgByName(req.Context(), systemContext, loginDetails.OrgName)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"failed to get organization from name\")\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\n\tresults, err := h.authenticator.Login(req.Context(), orgData, loginDetails)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login failed\")\n\t\tif req.Context().Err() != nil {\n\t\t\tmiddleware.ReturnError(w, \"internal server error\", 500)\n\t\t\treturn\n\t\t}\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\t// add subscription id to response\n\tresults[\"subscription_id\"] = fmt.Sprintf(\"%d\", orgData.SubscriptionID)\n\n\trespData, err := json.Marshal(results)\n\tif err != nil {\n\t\tmiddleware.ReturnError(w, \"marshal auth response failed\", 500)\n\t\treturn\n\t}\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Str(\"OrgCID\", orgData.OrgCID).Msg(\"setting orgCID in cookie\")\n\tif err := h.secureCookie.SetAuthCookie(w, results[\"access_token\"], orgData.OrgCID, orgData.SubscriptionID); err != nil {\n\t\tmiddleware.ReturnError(w, \"internal cookie failure\", 500)\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func (s *Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvar acc data.Account\n\t// получение данных JSON account\n\tif err := json.NewDecoder(r.Body).Decode(&acc); err != nil {\n\t\thttp.Error(w, e.DecodeError.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\ttoken, err := s.service.Login(&acc)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tw.Header().Set(\"Token\", token)\n\tfmt.Fprint(w, \"See in tab Headers.\")\n}", "func (this *Handle) pageLogin(w http.ResponseWriter, r *http.Request) {\n\tif this.user.CheckLogin(w, r) == true {\n\t\tthis.ToURL(w, r, \"/center\")\n\t\treturn\n\t} else {\n\t\tthis.ShowTemplate(w, r, \"login.html\", nil)\n\t\treturn\n\t}\n}", "func (uh *UserHandler) Login(w http.ResponseWriter, r *http.Request) {\n\n\terrMap := make(map[string]string)\n\tuser := uh.Authentication(r)\n\tif user != nil {\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodGet {\n\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\ttoken, err := stringTools.CSRFToken(uh.CSRF)\n\t\tinputContainer := InputContainer{CSRF: token}\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodPost {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\t// Validating CSRF Token\n\t\tcsrfToken := r.FormValue(\"csrf\")\n\t\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\n\t\tif !ok || errCRFS != nil {\n\t\t\terrMap[\"csrf\"] = \"Invalid token used!\"\n\t\t}\n\n\t\terr := uh.UService.Login(email, password)\n\n\t\tif err != nil || len(errMap) > 0 {\n\t\t\terrMap[\"login\"] = \"Invalid email or password!\"\n\t\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\t\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\n\t\t\tinputContainer := InputContainer{Error: errMap, CSRF: token}\n\t\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\t\treturn\n\t\t}\n\n\t\tnewSession := uh.configSess()\n\t\tclaims := stringTools.Claims(email, newSession.Expires)\n\t\tsession.Create(claims, newSession, w)\n\t\t_, err = uh.SService.StoreSession(newSession)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n}", "func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar resp = map[string]interface{}{\"status\": \"success\", \"message\": \"logged in\"}\n\n\tuser := &models.User{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser.Prepare() // here strip the text of white spaces\n\n\terr = user.Validate(\"login\") // fields(email, password) are validated\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tusr, err := user.GetUser(a.DB)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif usr == nil { // user is not registered\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please signup\"\n\t\tresponses.JSON(w, http.StatusBadRequest, resp)\n\t\treturn\n\t}\n\n\terr = models.CheckPasswordHash(user.Password, usr.Password)\n\tif err != nil {\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please try again\"\n\t\tresponses.JSON(w, http.StatusForbidden, resp)\n\t\treturn\n\t}\n\ttoken, err := utils.EncodeAuthToken(usr.ID)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tresp[\"token\"] = token\n\tresponses.JSON(w, http.StatusOK, resp)\n\treturn\n}", "func login(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\n\t// Where authentication could be done\n\tif r.FormValue(\"code\")!=\"code\"{\n\t\tif r.FormValue(\"code\")==\"\"{\n\t\t\tsession.AddFlash(\"must enter a code\")\n\t\t}\n\t\tsession.AddFlash(\"the code was incorrect\")\n\t\terr:=session.Save(r,w)\n\t\tif err!=nil{\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\thttp.Redirect(w,r,\"/forbiden\",http.StatusFound)\n\t\treturn\n\t}\n\tusername:=r.FormValue(\"username\")\n\tpassword:=r.FormValue(\"password\")\n\tuser:=&user{\n\t\tUserName: username,\n\t\tPassword: password,\n\t\tAuthenticated: true,\n\t}\n\tsession.Values[\"user\"]=user\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/secret\",http.StatusFound)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tPrintln(\"Endpoint Hit: Login\")\n\tvar response struct {\n\t\tStatus bool\n\t\tMessage string\n\t\tData map[string]interface{}\n\t}\n\t// var response models.JwtResponse\n\t//CEK UDAH ADA YANG LOGIN ATAU BELUM\n\t// session := sessions.Start(w, r)\n\t// if len(session.GetString(\"email\")) != 0 && checkErr(w, r, err) {\n\t// \thttp.Redirect(w, r, \"/\", 302)\n\t// }\n\tjwtSignKey := \"notsosecret\"\n\tappName := \"Halovet\"\n\tvar message string\n\n\t//dapetin informasi dari Basic Auth\n\t// email, password, ok := r.BasicAuth()\n\t// if !ok {\n\t// \tmessage = \"Invalid email or password\"\n\t// \tw.Header().Set(\"Content-Type\", \"application/json\")\n\t// \tw.WriteHeader(200)\n\t// \tresponse.Status = false\n\t// \tresponse.Message = message\n\t// \tjson.NewEncoder(w).Encode(response)\n\t// \treturn\n\t// }\n\t//dapetin informasi dari form\n\temail := r.FormValue(\"email\")\n\tif _, status := ValidateEmail(email); status != true {\n\t\tmessage := \"Format Email Salah atau Kosong\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\tif _, status := ValidatePassword(password); status != true {\n\t\tmessage := \"Format Password Salah atau Kosong, Minimal 6 Karakter\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tok, userInfo := mid.AuthenticateUser(email, password)\n\tif !ok {\n\t\tmessage = \"Invalid email or password\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tclaims := models.TheClaims{\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tIssuer: appName,\n\t\t\tExpiresAt: time.Now().Add(LoginExpDuration).Unix(),\n\t\t},\n\t\tUser: userInfo,\n\t}\n\n\ttoken := jwt.NewWithClaims(\n\t\tJwtSigningMethod,\n\t\tclaims,\n\t)\n\n\tsignedToken, err := token.SignedString([]byte(jwtSignKey))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\t//tokennya dijadiin json\n\t// tokenString, _ := json.Marshal(M{ \"token\": signedToken })\n\t// w.Write([]byte(tokenString))\n\tdata := map[string]interface{}{\n\t\t\"jwtToken\": signedToken,\n\t\t\"user\": userInfo,\n\t}\n\n\t//RESPON JSON\n\tmessage = \"Login Succesfully\"\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tresponse.Status = true\n\tresponse.Message = message\n\tresponse.Data = data\n\tjson.NewEncoder(w).Encode(response)\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"token\",\n\t\tValue: signedToken,\n\t\tExpires: time.Now().Add(LoginExpDuration),\n\t})\n}", "func (app *application) loginForm(w http.ResponseWriter, r *http.Request) {\n\tapp.render(w, r, \"login.page.tmpl\", &templateData{\n\t\tForm: forms.New(nil),\n\t})\n}", "func (sry *Sryun) Login(res http.ResponseWriter, req *http.Request) (*model.User, bool, error) {\n\tusername := req.FormValue(\"username\")\n\tpassword := req.FormValue(\"password\")\n\n\tlog.Infoln(\"got\", username, \"/\", password)\n\n\tif username == sry.User.Login && password == sry.Password {\n\t\treturn sry.User, true, nil\n\t}\n\treturn nil, false, errors.New(\"bad auth\")\n}", "func Login(rw http.ResponseWriter, req *http.Request) {\n\n\tif req.Method == \"GET\" {\n\t\trw.Write([]byte(\"Only POST request allowed\"))\n\t} else {\n\n\t\t// Input from request body\n\t\tdec := json.NewDecoder(req.Body)\n\t\tvar t c.User\n\t\terr := dec.Decode(&t)\n\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Error in Decoding Data\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Check if all parametes are there\n\t\tif Valid := c.ValidateCredentials(t); Valid != \"\" {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Bad Request\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Get existing data on user\n\t\tdt, err := db.GetUser(t.Roll)\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\tresponse := c.Response{\n\t\t\t\t\tError: err.Error(),\n\t\t\t\t\tMessage: \"User Not registered\",\n\t\t\t\t}\n\t\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\t\treturn\n\t\t}\n\n\t\t// check if password is right\n\t\terr = auth.Verify(t.Password, dt.Password)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\trw.Write(Rsp(err.Error(), \"Wrong Password\"))\n\t\t\treturn\n\t\t}\n\n\t\t// All good yaayy\n\t\trw.WriteHeader(http.StatusOK)\n\t\tmsg := fmt.Sprintf(\"Hey, User %s! Your roll is %d. \", dt.Name, dt.Roll)\n\n\t\t// get token to\n\t\ttokenString, err := auth.GetJwtToken(dt)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\tresponse := c.Response{\n\t\t\t\tError: err.Error(),\n\t\t\t\tMessage: \"Error While getting JWT token\",\n\t\t\t}\n\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\treturn\n\t\t}\n\t\trw.Write(RspToken(\"\", msg+\"This JWT Token Valid for next 12 Hours\", tokenString))\n\t}\n}", "func (app *application) loginForm(w http.ResponseWriter, r *http.Request) {\n\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin {\n\t\tForm: \t\t\tforms.New(nil),\n\t})\n}", "func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {\n\tvar d UserLoginRequest\n\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\n\t\trender.BadRequest(w, r, \"invalid json string\")\n\t\treturn\n\t}\n\n\t//Check if email exists\n\tuser, err := h.Client.User.\n\t\tQuery().\n\t\tWhere(usr.Email(d.Email)).\n\t\tOnly(r.Context())\n\tif err != nil {\n\t\tswitch {\n\t\tcase ent.IsNotFound(err):\n\t\t\trender.NotFound(w, r, \"Email Doesn't exists\")\n\t\tcase ent.IsNotSingular(err):\n\t\t\trender.BadRequest(w, r, \"Invalid Email\")\n\t\tdefault:\n\t\t\trender.InternalServerError(w, r, \"Server Error\")\n\t\t}\n\t\treturn\n\t}\n\n\t// Verify the password\n\tif user.Password == d.Password {\n\t\tfmt.Println(\"User Verified. Log In Successful\")\n\t\trender.OK(w, r, user)\n\t\treturn\n\t}\n\trender.Unauthorized(w, r, \"Invalid Email or Password.\")\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tif username != \"\" && password != \"\" {\n\t\tauth := database.QuickGetAuth()\n\t\tnauth := &database.Auth{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\n\t\tif auth.Equal(nauth) {\n\t\t\thttp.SetCookie(w, nauth.MakeCookie())\n\t\t\thttp.Redirect(w, r, \"/admin\", 301)\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/admin/nono\", 301)\n\t\t}\n\t} else {\n\t\thttp.Redirect(w, r, \"/admin\", 301)\n\t}\n}", "func loginActionHandler(w http.ResponseWriter, r *http.Request) {\n\n\t// Read the private key\n\tpemData, err := ioutil.ReadFile(PRIVATE_KEY_FILE)\n\tcheckHttpError(err, w)\n\n\t// Extract the PEM-encoded data block\n\tblock, _ := pem.Decode(pemData)\n\tif block == nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif got, want := block.Type, \"RSA PRIVATE KEY\"; got != want {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Decode the RSA private key\n\tpriv, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tcheckHttpError(err, w)\n\n\t// Decode the Base64 into binary\n\tcipheredValue, err := base64.StdEncoding.DecodeString(r.FormValue(\"CipheredValue\"))\n\tcheckHttpError(err, w)\n\n\t// Decrypt the data\n\tvar out []byte\n\tout, err = rsa.DecryptPKCS1v15(rand.Reader, priv, cipheredValue)\n\tcheckHttpError(err, w)\n\n\t//home or login\n\tsession, _ := store.Get(r, \"goServerView\")\n\th := sha512.New()\n\th.Write(out)\n\tstr := base64.StdEncoding.EncodeToString(h.Sum([]byte{}))\n\n\tif str == config.Password {\n\t\tsession.Values[\"isConnected\"] = true\n\t\tsession.Values[\"user\"] = r.FormValue(\"User\")\n\t\tsession.Save(r, w)\n\t\thomeHandler(w, r)\n\t} else {\n\t\tsession.Values[\"isConnected\"] = false\n\t\tsession.AddFlash(\"Either the username or the password provided is wrong\")\n\t\tsession.Save(r, w)\n\t\tloginFormHandler(w, r)\n\t}\n}", "func IndexHandler(c *gin.Context) {\n\tval, _ := c.Cookie(\"auth\")\n\tif val != \"\" {\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/dashboard\")\n\t\treturn\n\t}\n\n\tc.HTML(http.StatusOK, \"login.html\", nil)\n}", "func LoginHandler(c *gin.Context) {\n\tval, _ := c.Cookie(\"auth\")\n\tif val != \"\" {\n\t\tc.Redirect(http.StatusOK, \"/dashboard\")\n\t\treturn\n\t}\n\n\tinfo := models.LoginInfo{\n\t\tEmail: c.Query(\"email\"),\n\t\tPassword: c.Query(\"password\"),\n\t}\n\n\tif info.Email == \"\" || info.Password == \"\" {\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/\")\n\t\treturn\n\t}\n\n\tif ok, err := crud.CheckLoginInfo(info); !ok || err != nil {\n\t\tc.HTML(http.StatusInternalServerError, \"login.html\", err.Error())\n\t}\n\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/dashboard\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/data\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/report\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/config\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/config/submit\", \"127.0.0.1\", false, false)\n\n\tc.Redirect(http.StatusTemporaryRedirect, \"/dashboard\")\n\treturn\n}", "func LoginHandler(ctx *gin.Context) {\n\tstate = randToken()\n\tsession := sessions.Default(ctx)\n\tsession.Set(\"state\", state)\n\tsession.Save()\n\tfmt.Println(\"LOGIN SESSION:\", session.Get(\"userid\"))\n\t// TODO create this page from a template\n\tloginPage := fmt.Sprintf(`\n\t<html>\n\t<title>Google Login</title>\n\t<body>\n\t<h3>Google Login</h3>\n\t<a href=\"%s\"><button>Login with Google</button></a>\n\t</body>\n\t</html>\n\t`, GetLoginURL(state))\n\tctx.Writer.Write([]byte(loginPage))\n}", "func LoginHandler(c *gin.Context) {\n\tsess := sessions.Default(c)\n\tinfo := sess.Flashes(\"info\")\n\terrors := sess.Flashes(\"error\")\n\tsess.Save()\n\n\tc.HTML(http.StatusOK, \"login.html\", gin.H{\n\t\t\"errors\": errors,\n\t\t\"info\": info,\n\t})\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\tauth.GetGatekeeper().Login(w, r)\n}", "func Login(c *gin.Context) {\n\tvar form model.LoginForm\n\terr := c.BindJSON(&form)\n\tif err != nil {\n\t\tfailMsg(c, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tvalid, errMsg := validInfo(form)\n\tif !valid {\n\t\tfailMsg(c, http.StatusBadRequest, errMsg)\n\t\treturn\n\t}\n\tvalid = model.VerifyLogin(form)\n\tif !valid {\n\t\tfailMsg(c, http.StatusUnauthorized, \"wrong username or password\")\n\t\treturn\n\t}\n\ttoken, err := model.GenerateToken(form.Username)\n\tif err != nil {\n\t\tfailMsg(c, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"success\": true,\n\t\t\"error\": \"\",\n\t\t\"data\": \"Bearer \" + token,\n\t})\n\n}", "func Login(c *gin.Context) {\n\t// check if request was a POST\n\tif strings.EqualFold(c.Request.Method, \"POST\") {\n\t\t// assume all POST requests are coming from the CLI\n\t\tAuthenticateCLI(c)\n\n\t\treturn\n\t}\n\n\t// capture an error if present\n\terr := c.Request.FormValue(\"error\")\n\tif len(err) > 0 {\n\t\t// redirect to initial login screen with error code\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login/error?code=\"+err)\n\t}\n\n\t// redirect to our authentication handler\n\tc.Redirect(http.StatusTemporaryRedirect, \"/authenticate\")\n}", "func (c *LoginController) ShowLogin(ctx *app.ShowLoginLoginContext) error {\n\t// LoginController_ShowLogin: start_implement\n\tloginError := map[string]interface{}{}\n\tc.SessionStore.GetAs(\"loginError\", &loginError, ctx.Request)\n\n\ttemplateContent, err := ioutil.ReadFile(\"public/login/login-form.html\")\n\tif err != nil {\n\t\treturn ctx.InternalServerError(err)\n\t}\n\n\tt, err := template.New(\"login-form\").Parse(string(templateContent))\n\tif err != nil {\n\t\treturn ctx.InternalServerError(err)\n\t}\n\n\tresponseCode := 200\n\n\tif loginErrorCode, ok := loginError[\"code\"]; ok {\n\t\tresponseCode = loginErrorCode.(int)\n\t}\n\n\trw := ctx.ResponseWriter\n\n\trw.Header().Set(\"Content-Type\", \"text/html\")\n\terr = t.Execute(rw, loginError)\n\trw.WriteHeader(responseCode)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t}\n\t// LoginController_ShowLogin: end_implement\n\treturn nil\n}", "func Login(c *soso.Context) {\n\treq := c.RequestMap\n\trequest := &auth_protocol.LoginRequest{}\n\n\tif value, ok := req[\"phone\"].(string); ok {\n\t\trequest.PhoneNumber = value\n\t}\n\n\tif value, ok := req[\"password\"].(string); ok {\n\t\trequest.Password = value\n\t}\n\n\tif request.Password == \"\" || request.PhoneNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Phone number and password is required\"))\n\t\treturn\n\t}\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := authClient.Login(ctx, request)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tif resp.ErrorCode != 0 {\n\t\tc.Response.ResponseMap = map[string]interface{}{\n\t\t\t\"ErrorCode\": resp.ErrorCode,\n\t\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t\t}\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(resp.ErrorMessage))\n\t\treturn\n\t}\n\n\ttokenData, err := auth.GetTokenData(resp.Token)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tuser, err := GetUser(tokenData.UID, true)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"token\": resp.Token,\n\t\t\"user\": user,\n\t})\n}", "func Login(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Login\")\n\n\t// フォームデータのパース\n\terr := request.ParseForm()\n\tif err != nil {\n\t\toutputErrorLog(\"フォーム パース 失敗\", err)\n\t}\n\n\t// リクエストデータ取得\n\taccount := request.Form.Get(\"account\")\n\tpassword := request.Form.Get(\"password\")\n\tlog.Println(\"ユーザ:\", account)\n\n\t// ユーザデータ取得しモデルデータに変換\n\tdbm := db.ConnDB()\n\tuser := new(models.User)\n\trow := dbm.QueryRow(\"select account, name, password from users where account = ?\", account)\n\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\n\t\toutputErrorLog(\"ユーザ データ変換 失敗\", err)\n\t}\n\n\t// ユーザのパスワード認証\n\tif user.Password != password {\n\t\tlog.Println(\"ユーザ パスワード照合 失敗\")\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\n\tlog.Println(\"認証 成功\")\n\n\t// 認証が通ったら、セッション情報をDBに保存\n\tsessionID := generateSessionID(account)\n\tlog.Println(\"生成したセッションID:\", sessionID)\n\tnow := time.Now()\n\tresult, err := dbm.Exec(`INSERT INTO sessions\n\t\t(sessionID, account, expireDate)\n\t\tVALUES\n\t\t(?, ?, ?)\n\t\t`, sessionID, account, now.Add(1*time.Hour))\n\tnum, err := result.RowsAffected()\n\tif err != nil || num == 0 {\n\t\toutputErrorLog(\"セッション データ保存 失敗\", err)\n\t}\n\n\tlog.Println(\"セッション データ保存 成功\")\n\n\t// クッキーにセッション情報付与\n\tcookie := &http.Cookie{\n\t\tName: sessionIDName,\n\t\tValue: sessionID,\n\t}\n\thttp.SetCookie(rw, cookie)\n\n\t// HOME画面に遷移\n\thttp.Redirect(rw, request, \"/home\", http.StatusFound)\n}", "func (p *Base) Login() string {\n\treturn \"https://admin.thebase.in/users/login\"\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func (c *UserController) Login() {\n\n\tisAjax := c.GetString(\"isajax\")\n\n\tif isAjax == \"1\" {\n\t\t// Captcha Verification.\n\t\tif !cpt.VerifyReq(c.Ctx.Request) {\n\t\t\tc.Resp(false, \"验证码错误!\")\n\t\t\treturn\n\t\t}\n\n\t\t// Passing Captcha Verify.\n\t\tusername := c.GetString(\"username\")\n\t\tpassword := c.GetString(\"password\")\n\n\t\tuser, err := doLogin(username, password)\n\t\tif err == nil {\n\t\t\tc.SetSession(\"userinfo\", user.Username)\n\t\t\tc.Resp(true, \"登陆成功\")\n\t\t\treturn\n\t\t}\n\t\tc.Resp(false, err.Error())\n\t\treturn\n\t}\n\t// Login Fail! relogin.\n\tc.Data[\"Title\"] = beego.AppConfig.String(\"login_title\")\n\tc.Data[\"Copyright\"] = beego.AppConfig.String(\"copyright\")\n\n\t// Get Verification Code.\n\tcpt = captcha.NewWithFilter(\"/captcha/\", store)\n\tcpt.ChallengeNums, _ = beego.AppConfig.Int(\"captcha_length\")\n\tcpt.StdWidth = 100\n\tcpt.StdHeight = 42\n\n\tc.TplName = \"login.tpl\"\n}", "func Login() gin.HandlerFunc {\r\n\tif gin.Mode() == \"debug\" {\r\n\t\treturn func(c *gin.Context) { c.Next() }\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tsession := sessions.Default(c)\r\n\t\tUserID := session.Get(\"UserID\")\r\n\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\tfmt.Println(\"UserID, IsLeader\", UserID, IsLeader)\r\n\t\tif UserID == nil {\r\n\t\t\tstate := string([]byte(c.Request.URL.Path)[1:])\r\n\t\t\tc.Redirect(http.StatusFound, \"/login?state=\"+state)\r\n\t\t\tc.Abort()\r\n\t\t} else {\r\n\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\tc.Next()\r\n\t\t}\r\n\r\n\t}\r\n}", "func IndexGET(w http.ResponseWriter, r *http.Request) {\n\t// Get session\n\tsession := session.Instance(r)\n\n\tif session.Values[\"id\"] != nil {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/auth\"\n\t\tv.Vars[\"first_name\"] = session.Values[\"first_name\"]\n\t\tv.Render(w)\n\t} else {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/anon\"\n\t\tv.Render(w)\n\t\treturn\n\t}\n}", "func (m *Manager) Login() error {\n\terr := m.useFreePort()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = m.openLoginPage()\n\tif err != nil {\n\t\tfmt.Println(\"Failed to open the login page, open the following link in your browser:\")\n\t}\n\tfmt.Println(loginURL)\n\terr = m.retrieveTokensFromServer()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tvar user models.User\n\tif err = json.Unmarshal(body, &user); err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tdb, error := database.Connect()\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tdefer db.Close()\n\tuserRepo := repository.NewUserRepo(db)\n\tuserFound, err := userRepo.FindByEmail(user.Email)\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tif err = hash.Verify(user.Password, userFound.Password); err != nil {\n\t\tutils.Error(w, http.StatusUnauthorized, err)\n\t\treturn\n\t}\n\ttoken, err := authentication.Token(userFound.ID)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tw.Write([]byte(token))\n}", "func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar loginInfo uvm.UserLoginVM\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar err error\n\n\tif err = decoder.Decode(&loginInfo); err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request body\")\n\t\treturn\n\t}\n\n\t//TODO validate user data\n\n\tuser := a.UserStore.GetUserByEmail(loginInfo.Email)\n\n\tif user.ID == \"\" || utils.CheckPasswordHash(loginInfo.Password, user.Password) {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid credentials\")\n\t\treturn\n\t}\n\n\ttoken := auth.GenerateToken(a.APISecret, user)\n\n\tresult := models.UserResult{\n\t\tUsername: user.Username,\n\t\tPicture: user.Picture,\n\t\tRole: user.Role.Name,\n\t\tToken: token,\n\t}\n\n\trespondWithJSON(w, http.StatusOK, result)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser := models.User{}\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.SignIn(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}", "func (h *GitHubOAuth) Login(c *router.Control) {\n\turl := h.oAuthConf.AuthCodeURL(h.state, oauth2.AccessTypeOnline)\n\thttp.Redirect(c.Writer, c.Request, url, http.StatusTemporaryRedirect)\n}", "func (httpcalls) Login(url string, jsonData []byte, client http.Client) (*http.Response, error) {\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Content-type\", \"application/json\")\n\tresp, err := client.Do(req)\n\treturn resp, err\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\tlogRequest(r)\n\n\t// Get a session. Get() always returns a session, even if empty.\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := User{}\n\tquery := fmt.Sprintf(\n\t\t`SELECT username, access_level FROM users WHERE username='%s'\n\t\tAND password = crypt('%s', password)`, username, password)\n\tdb.Get(&user, query)\n\n\tif user.Username != \"\" {\n\t\tsession.Values[\"user\"] = user\n\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusUnauthorized)\n}", "func Login(user, passd string) (string, error) {\n\tt := TpaasLogin{Username: user, Password: passd}\n\n\tclient := gorequest.New().Post(loginUrl()).\n\t\tTimeout(HttpTimeout * time.Second).\n\t\tType(\"json\").\n\t\tSend(t)\n\n\tresp, body, ierrors := client.End()\n\tif len(ierrors) != 0 {\n\t\treturn \"\", ierrors[0]\n\t}\n\n\tif !HttpOK(resp.StatusCode) {\n\t\treturn \"\", errors.Errorf(\"http code:%d body:%s\", resp.StatusCode, body)\n\t}\n\n\tvar lg TpaasLoginResp\n\terr := json.Unmarshal([]byte(body), &lg)\n\tif err != nil {\n\t\treturn \"\", errors.WithMessage(err, \"logining response from tpaas is not json\")\n\t}\n\tif !HttpOK(lg.Code) {\n\t\treturn \"\", errors.Errorf(\"tpaas code:%d body:%s\", lg.Code, body)\n\t}\n\treturn lg.Data.Token, nil\n}", "func LoginPost(ctx echo.Context) error {\n\tvar flashMessages = flash.New()\n\tf := forms.New(utils.GetLang(ctx))\n\tlf, err := f.DecodeLogin(ctx.Request())\n\tif err != nil {\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tif !lf.Valid() {\n\t\tfor k, v := range lf.Ctx() {\n\t\t\tflashMessages.AddCtx(k, v)\n\t\t}\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tvar user *models.User\n\tif validate.IsEmail(lf.Name) {\n\t\tuser, err = query.AuthenticateUserByEmail(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tuser, err = query.AuthenticateUserByName(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// create a session for the user after the validation has passed. The info stored\n\t// in the session is the user ID, where as the key is userID.\n\tss, err := sessStore.Get(ctx.Request(), settings.App.Session.Name)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tss.Values[\"userID\"] = user.ID\n\terr = ss.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tperson, err := query.GetPersonByUserID(db.Conn, user.ID)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\n\t// add context data. IsLoged is just a conveniece in template rendering. the User\n\t// contains a models.Person object, where the PersonName is already loaded.\n\tutils.SetData(ctx, \"IsLoged\", true)\n\tutils.SetData(ctx, \"User\", person)\n\tflashMessages.Success(settings.FlashLoginSuccess)\n\tflashMessages.Save(ctx)\n\tctx.Redirect(http.StatusFound, \"/\")\n\treturn nil\n}", "func (c *client) Login(w http.ResponseWriter, r *http.Request) (string, error) {\n\tlogrus.Trace(\"Processing login request\")\n\n\t// generate a random string for creating the OAuth state\n\toAuthState, err := random.GenerateRandomString(32)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// temporarily redirect request to Github to begin workflow\n\thttp.Redirect(w, r, c.OConfig.AuthCodeURL(oAuthState), http.StatusTemporaryRedirect)\n\n\treturn oAuthState, nil\n}", "func Login(c *gin.Context) {\n\turl := GithubAuth.AuthCodeURL(\"state\", oauth2.AccessTypeOffline)\n\tc.Redirect(http.StatusFound, url)\n}", "func (controller *Auth) ShowLoginPage() {\n\tif controller.AccountConnected {\n\t\tcontroller.Redirect(\"/\", 302)\n\t} else {\n\t\tcontroller.showLoginForm()\n\t}\n}" ]
[ "0.78163654", "0.75899374", "0.7468364", "0.7320955", "0.7160428", "0.691093", "0.68139416", "0.6773794", "0.675614", "0.6752772", "0.66593784", "0.66468394", "0.6646164", "0.66439223", "0.6637479", "0.6600472", "0.659737", "0.65903026", "0.6589105", "0.65679455", "0.65355605", "0.65296197", "0.65190303", "0.6484801", "0.64555156", "0.6447445", "0.64286613", "0.6410929", "0.64101624", "0.64088815", "0.64053816", "0.63857985", "0.63820815", "0.63772017", "0.6375736", "0.63707024", "0.6367302", "0.63463825", "0.6330498", "0.63217777", "0.6312718", "0.6288135", "0.62855935", "0.6277289", "0.6270144", "0.6265177", "0.6260917", "0.6246118", "0.62407815", "0.6203026", "0.6181901", "0.61617297", "0.6160355", "0.61577904", "0.6150643", "0.6133868", "0.6130904", "0.612645", "0.6125379", "0.6122173", "0.6120974", "0.6119169", "0.6113575", "0.6109388", "0.61058736", "0.61032045", "0.60958856", "0.6095299", "0.60930747", "0.6082655", "0.6073187", "0.6071619", "0.6053984", "0.6051797", "0.603707", "0.6035718", "0.6031637", "0.60305035", "0.6021301", "0.6017578", "0.6014255", "0.60013604", "0.5996308", "0.5991944", "0.5990754", "0.5985269", "0.59849125", "0.59794366", "0.59716153", "0.5956889", "0.59475857", "0.5941461", "0.5940636", "0.59397936", "0.5938325", "0.59339786", "0.5930632", "0.5930307", "0.59288764", "0.591727" ]
0.801604
0
Implements the json.Marshaler interface and JSON encodes the Jwk
Реализует интерфейс json.Marshaler и кодирует Jwk в JSON
func (jwk *Jwk) MarshalJSON() (data []byte, err error) { // Remove any potentionally conflicting claims from the JWK's additional members delete(jwk.AdditionalMembers, "kty") delete(jwk.AdditionalMembers, "kid") delete(jwk.AdditionalMembers, "alg") delete(jwk.AdditionalMembers, "use") delete(jwk.AdditionalMembers, "key_ops") delete(jwk.AdditionalMembers, "crv") delete(jwk.AdditionalMembers, "x") delete(jwk.AdditionalMembers, "y") delete(jwk.AdditionalMembers, "d") delete(jwk.AdditionalMembers, "n") delete(jwk.AdditionalMembers, "p") delete(jwk.AdditionalMembers, "q") delete(jwk.AdditionalMembers, "dp") delete(jwk.AdditionalMembers, "dq") delete(jwk.AdditionalMembers, "qi") delete(jwk.AdditionalMembers, "e") delete(jwk.AdditionalMembers, "oth") delete(jwk.AdditionalMembers, "k") // There are additional claims, individually marshal each member obj := make(map[string]*json.RawMessage, len(jwk.AdditionalMembers)+10) if bytes, err := json.Marshal(jwk.Type); err == nil { rm := json.RawMessage(bytes) obj["kty"] = &rm } else { return nil, err } if len(jwk.Id) > 0 { if bytes, err := json.Marshal(jwk.Id); err == nil { rm := json.RawMessage(bytes) obj["kid"] = &rm } else { return nil, err } } if len(jwk.Algorithm) > 0 { if bytes, err := json.Marshal(jwk.Algorithm); err == nil { rm := json.RawMessage(bytes) obj["alg"] = &rm } else { return nil, err } } if len(jwk.Use) > 0 { if bytes, err := json.Marshal(jwk.Use); err == nil { rm := json.RawMessage(bytes) obj["use"] = &rm } else { return nil, err } } if len(jwk.Operations) > 0 { if bytes, err := json.Marshal(jwk.Operations); err == nil { rm := json.RawMessage(bytes) obj["key_ops"] = &rm } else { return nil, err } } switch jwk.Type { case KeyTypeEC: { if jwk.Curve != nil { jwk.Curve.Params() p := jwk.Curve.Params() if bytes, err := json.Marshal(p.Name); err == nil { rm := json.RawMessage(bytes) obj["crv"] = &rm } else { return nil, err } } if jwk.X != nil { b64u := &Base64UrlUInt{UInt: jwk.X} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["x"] = &rm } else { return nil, err } } if jwk.Y != nil { b64u := &Base64UrlUInt{UInt: jwk.Y} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["y"] = &rm } else { return nil, err } } if jwk.D != nil { b64u := &Base64UrlUInt{UInt: jwk.D} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["d"] = &rm } else { return nil, err } } } case KeyTypeRSA: { if jwk.D != nil { b64u := &Base64UrlUInt{UInt: jwk.D} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["d"] = &rm } else { return nil, err } } if jwk.N != nil { b64u := &Base64UrlUInt{UInt: jwk.N} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["n"] = &rm } else { return nil, err } } if jwk.P != nil { b64u := &Base64UrlUInt{UInt: jwk.P} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["p"] = &rm } else { return nil, err } } if jwk.Q != nil { b64u := &Base64UrlUInt{UInt: jwk.Q} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["q"] = &rm } else { return nil, err } } if jwk.Dp != nil { b64u := &Base64UrlUInt{UInt: jwk.Dp} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["dp"] = &rm } else { return nil, err } } if jwk.Dq != nil { b64u := &Base64UrlUInt{UInt: jwk.Dq} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["dq"] = &rm } else { return nil, err } } if jwk.Qi != nil { b64u := &Base64UrlUInt{UInt: jwk.Qi} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["qi"] = &rm } else { return nil, err } } if jwk.E >= 0 { b64u := &Base64UrlUInt{UInt: big.NewInt(int64(jwk.E))} if bytes, err := json.Marshal(&b64u); err == nil { rm := json.RawMessage(bytes) obj["e"] = &rm } else { return nil, err } } if len(jwk.OtherPrimes) > 0 { tempOthPrimes := make([]jwkOthPrimeJSON, len(jwk.OtherPrimes)) for i, v := range jwk.OtherPrimes { tempOthPrimes[i].Coeff = &Base64UrlUInt{UInt: v.Coeff} tempOthPrimes[i].Exp = &Base64UrlUInt{UInt: v.Exp} tempOthPrimes[i].R = &Base64UrlUInt{UInt: v.R} } if bytes, err := json.Marshal(tempOthPrimes); err == nil { rm := json.RawMessage(bytes) obj["oth"] = &rm } else { return nil, err } } } case KeyTypeOct: { if len(jwk.KeyValue) > 0 { b64o := &Base64UrlOctets{Octets: jwk.KeyValue} if bytes, err := json.Marshal(b64o); err == nil { rm := json.RawMessage(bytes) obj["k"] = &rm } else { return nil, err } } } } //Iterate through remaing members and add to json rawMessage for k, v := range jwk.AdditionalMembers { if bytes, err := json.Marshal(v); err == nil { rm := json.RawMessage(bytes) obj[k] = &rm } else { return nil, err } } // Marshal obj return json.Marshal(obj) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (j *JWK) MarshalJSON() ([]byte, error) {\n\tif isSecp256k1(j.Kty, j.Crv) {\n\t\treturn marshalSecp256k1(j)\n\t}\n\n\treturn (&j.JSONWebKey).MarshalJSON()\n}", "func JSONEncoder() Encoder { return jsonEncoder }", "func (m KeyPair) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\taO0, err := swag.WriteJSON(m.Resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar dataAO1 struct {\n\t\tGroup *Group `json:\"group,omitempty\"`\n\n\t\tPrivateKey string `json:\"privateKey,omitempty\"`\n\n\t\tPublicKey string `json:\"publicKey,omitempty\"`\n\t}\n\n\tdataAO1.Group = m.Group\n\n\tdataAO1.PrivateKey = m.PrivateKey\n\n\tdataAO1.PublicKey = m.PublicKey\n\n\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\n\tif errAO1 != nil {\n\t\treturn nil, errAO1\n\t}\n\t_parts = append(_parts, jsonDataAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (k *Key) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + k.Encode() + `\"`), nil\n}", "func (j *jws) Serialize(key interface{}) ([]byte, error) {\n\tif j.isJWT {\n\t\treturn j.Compact(key)\n\t}\n\treturn nil, ErrIsNotJWT\n}", "func Marshal(v Marshaler) ([]byte, error) {\n\tw := jwriter.Writer{}\n\tv.MarshalEasyJSON(&w)\n\treturn w.BuildBytes()\n}", "func (j JSON) Encode(w io.Writer) error {\n\tdata, err := json.Marshal(j.V)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstr := String(string(data))\n\treturn str.Encode(w)\n}", "func EncodeJSON(w io.Writer, i *Iterator) error {\n\tr := make(Record)\n\n\t// Open paren.\n\tif _, err := w.Write([]byte{'['}); err != nil {\n\t\treturn err\n\t}\n\n\tvar c int\n\tenc := json.NewEncoder(w)\n\n\tdelim := []byte{',', '\\n'}\n\n\tfor i.Next() {\n\t\tif c > 0 {\n\t\t\tif _, err := w.Write(delim); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tc++\n\n\t\tif err := i.Scan(r); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := enc.Encode(r); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Close paren.\n\tif _, err := w.Write([]byte{']'}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (v JwtData) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (handler Handler) EncodeJSON(v interface{}) (b []byte, err error) {\n\n\t//if(w.Get(\"pretty\",\"false\")==\"true\"){\n\tb, err = json.MarshalIndent(v, \"\", \" \")\n\t//}else{\n\t//\tb, err = json.Marshal(v)\n\t//}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (j *LuaKey) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (rec JSONLogRec) MarshalJSONObject(enc *gojay.Encoder) {\n\tif !rec.DisableTimestamp {\n\t\ttimestampFmt := rec.TimestampFormat\n\t\tif timestampFmt == \"\" {\n\t\t\ttimestampFmt = logr.DefTimestampFormat\n\t\t}\n\t\ttime := rec.Time()\n\t\tenc.AddTimeKey(rec.KeyTimestamp, &time, timestampFmt)\n\t}\n\tif !rec.DisableLevel {\n\t\tenc.AddStringKey(rec.KeyLevel, rec.Level().Name)\n\t}\n\tif !rec.DisableMsg {\n\t\tenc.AddStringKey(rec.KeyMsg, rec.Msg())\n\t}\n\tif !rec.DisableContext {\n\t\tctxFields := rec.sorter(rec.Fields())\n\t\tif rec.KeyContextFields != \"\" {\n\t\t\tenc.AddObjectKey(rec.KeyContextFields, jsonFields(ctxFields))\n\t\t} else {\n\t\t\tif len(ctxFields) > 0 {\n\t\t\t\tfor _, cf := range ctxFields {\n\t\t\t\t\tkey := rec.prefixCollision(cf.Key)\n\t\t\t\t\tencodeField(enc, key, cf.Val)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif rec.stacktrace && !rec.DisableStacktrace {\n\t\tframes := rec.StackFrames()\n\t\tif len(frames) > 0 {\n\t\t\tenc.AddArrayKey(rec.KeyStacktrace, stackFrames(frames))\n\t\t}\n\t}\n\n}", "func starlarkJSON(out *bytes.Buffer, v starlark.Value) error {\n\tswitch v := v.(type) {\n\tcase starlark.NoneType:\n\t\tout.WriteString(\"null\")\n\tcase starlark.Bool:\n\t\tfmt.Fprintf(out, \"%t\", v)\n\tcase starlark.Int:\n\t\tdata, err := json.Marshal(v.BigInt())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout.Write(data)\n\tcase starlark.Float:\n\t\tdata, err := json.Marshal(float64(v))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout.Write(data)\n\tcase starlark.String:\n\t\t// we have to use a json Encoder to disable noisy html\n\t\t// escaping. But the encoder appends a final \\n so we\n\t\t// also should remove it.\n\t\tdata := &bytes.Buffer{}\n\t\te := json.NewEncoder(data)\n\t\te.SetEscapeHTML(false)\n\t\tif err := e.Encode(string(v)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// remove final \\n introduced by the encoder\n\t\tout.Write(bytes.TrimSuffix(data.Bytes(), []byte(\"\\n\")))\n\tcase starlark.Indexable: // Tuple, List\n\t\tout.WriteByte('[')\n\t\tfor i, n := 0, starlark.Len(v); i < n; i++ {\n\t\t\tif i > 0 {\n\t\t\t\tout.WriteString(\", \")\n\t\t\t}\n\t\t\tif err := starlarkJSON(out, v.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tout.WriteByte(']')\n\tcase *starlark.Dict:\n\t\tout.WriteByte('{')\n\t\tfor i, item := range v.Items() {\n\t\t\tif i > 0 {\n\t\t\t\tout.WriteString(\", \")\n\t\t\t}\n\t\t\tif _, ok := item[0].(starlark.String); !ok {\n\t\t\t\treturn fmt.Errorf(\"cannot convert non-string dict key to JSON\")\n\t\t\t}\n\t\t\tif err := starlarkJSON(out, item[0]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tout.WriteString(\": \")\n\t\t\tif err := starlarkJSON(out, item[1]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tout.WriteByte('}')\n\n\tdefault:\n\t\treturn fmt.Errorf(\"cannot convert starlark type %q to JSON\", v.Type())\n\t}\n\treturn nil\n}", "func (v Signature) EncodeJSON(b []byte) []byte {\n\tb = append(b, `{\"hex_bytes\":`...)\n\tb = json.AppendHexBytes(b, v.Bytes)\n\tb = append(b, `,\"public_key\":`...)\n\tb = v.PublicKey.EncodeJSON(b)\n\tb = append(b, ',', '\"', 's', 'i', 'g', 'n', 'a', 't', 'u', 'r', 'e', '_', 't', 'y', 'p', 'e', '\"', ':')\n\tb = json.AppendString(b, string(v.SignatureType))\n\tb = append(b, ',', '\"', 's', 'i', 'g', 'n', 'i', 'n', 'g', '_', 'p', 'a', 'y', 'l', 'o', 'a', 'd', '\"', ':')\n\tb = v.SigningPayload.EncodeJSON(b)\n\treturn append(b, \"}\"...)\n}", "func (k Kitten) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"eatsMiceYet\", k.EatsMiceYet)\n\tpopulate(objectMap, \"hisses\", k.Hisses)\n\tpopulate(objectMap, \"likesMilk\", k.LikesMilk)\n\tpopulate(objectMap, \"meows\", k.Meows)\n\tpopulate(objectMap, \"name\", k.Name)\n\treturn json.Marshal(objectMap)\n}", "func (a APIKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"connectionString\", a.ConnectionString)\n\tpopulate(objectMap, \"id\", a.ID)\n\tpopulateTimeRFC3339(objectMap, \"lastModified\", a.LastModified)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"readOnly\", a.ReadOnly)\n\tpopulate(objectMap, \"value\", a.Value)\n\treturn json.Marshal(objectMap)\n}", "func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) {\n\tbs, fnerr := iv.MarshalJSON()\n\tf.e.marshalAsis(bs, fnerr)\n}", "func (kv KV) MarshalJSON() ([]byte, error) {\n\tbuffer := bytes.NewBufferString(\"{\")\n\n\tjsonKey, err := json.Marshal(kv.Key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjsonValue, err := json.Marshal(kv.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer.Write(jsonKey)\n\tbuffer.WriteByte(58)\n\tbuffer.Write(jsonValue)\n\n\tbuffer.WriteString(\"}\")\n\treturn buffer.Bytes(), nil\n}", "func (v Join) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (gr gelfRecord) MarshalJSONObject(enc *gojay.Encoder) {\n\tenc.AddStringKey(GelfVersionKey, GelfVersion)\n\tenc.AddStringKey(GelfHostKey, gr.getHostname())\n\tenc.AddStringKey(GelfShortKey, gr.Msg())\n\n\tif gr.level.Stacktrace {\n\t\tframes := gr.StackFrames()\n\t\tif len(frames) != 0 {\n\t\t\tvar sbuf strings.Builder\n\t\t\tfor _, frame := range frames {\n\t\t\t\tfmt.Fprintf(&sbuf, \"%s\\n %s:%d\\n\", frame.Function, frame.File, frame.Line)\n\t\t\t}\n\t\t\tenc.AddStringKey(GelfFullKey, sbuf.String())\n\t\t}\n\t}\n\n\tsecs := float64(gr.Time().UTC().Unix())\n\tmillis := float64(gr.Time().Nanosecond() / 1000000)\n\tts := secs + (millis / 1000)\n\tenc.AddFloat64Key(GelfTimestampKey, ts)\n\n\tenc.AddUint32Key(GelfLevelKey, uint32(gr.level.ID))\n\n\tvar fields []logr.Field\n\tif gr.EnableCaller {\n\t\tcaller := logr.Field{\n\t\t\tKey: \"_caller\",\n\t\t\tType: logr.StringType,\n\t\t\tString: gr.LogRec.Caller(),\n\t\t}\n\t\tfields = append(fields, caller)\n\t}\n\n\tfields = append(fields, gr.Fields()...)\n\tif gr.sorter != nil {\n\t\tfields = gr.sorter(fields)\n\t}\n\n\tif len(fields) > 0 {\n\t\tfor _, field := range fields {\n\t\t\tif !strings.HasPrefix(\"_\", field.Key) {\n\t\t\t\tfield.Key = \"_\" + field.Key\n\t\t\t}\n\t\t\tif err := encodeField(enc, field); err != nil {\n\t\t\t\tenc.AddStringKey(field.Key, fmt.Sprintf(\"<error encoding field: %v>\", err))\n\t\t\t}\n\t\t}\n\t}\n}", "func (j *LuaKey) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn nil\n\t}\n\tvar err error\n\tvar obj []byte\n\t_ = obj\n\t_ = err\n\tbuf.WriteString(`{\"key\":`)\n\tif j.Key != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.Key {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\t\t\t/* Interface types must use runtime reflection. type=interface {} kind=interface */\n\t\t\terr = buf.Encode(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteByte('}')\n\treturn nil\n}", "func (q QnAMakerEndpointKeysRequestBody) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"authkey\", q.Authkey)\n\tpopulate(objectMap, \"hostname\", q.Hostname)\n\treturn json.Marshal(objectMap)\n}", "func (o ApiKey) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.UnparsedObject != nil {\n\t\treturn json.Marshal(o.UnparsedObject)\n\t}\n\tif o.Created != nil {\n\t\ttoSerialize[\"created\"] = o.Created\n\t}\n\tif o.CreatedBy != nil {\n\t\ttoSerialize[\"created_by\"] = o.CreatedBy\n\t}\n\tif o.Key != nil {\n\t\ttoSerialize[\"key\"] = o.Key\n\t}\n\tif o.Name != nil {\n\t\ttoSerialize[\"name\"] = o.Name\n\t}\n\n\tfor key, value := range o.AdditionalProperties {\n\t\ttoSerialize[key] = value\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func (k *TimeKey) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + k.String() + `\"`), nil\n}", "func writeJSON(buf *bytes.Buffer, v interface{}, keyName string) error {\n\tenc, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, `failed to encode '%s'`, keyName)\n\t}\n\tbuf.Write(enc)\n\n\treturn nil\n}", "func (k Key) MarshalJSON() ([]byte, error) {\n\t// Marshal the Key property only\n\treturn json.Marshal(k.Key)\n}", "func Marshal(v Marshaler) ([]byte, error) {\n\tif isNilInterface(v) {\n\t\treturn nullBytes, nil\n\t}\n\n\tw := jwriter.Writer{}\n\tv.MarshalTinyJSON(&w)\n\treturn w.BuildBytes()\n}", "func (s StreamingPolicyContentKeys) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"defaultKey\", s.DefaultKey)\n\tpopulate(objectMap, \"keyToTrackMappings\", s.KeyToTrackMappings)\n\treturn json.Marshal(objectMap)\n}", "func (v Header) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson171edd05EncodeGithubComEmirmuminogluJwt(w, v)\n}", "func (v PublicKey) EncodeJSON(b []byte) []byte {\n\tb = append(b, `{\"hex_bytes\":`...)\n\tb = json.AppendHexBytes(b, v.Bytes)\n\tb = append(b, `,\"curve_type\":`...)\n\tb = json.AppendString(b, string(v.CurveType))\n\treturn append(b, \"}\"...)\n}", "func (k *KeyStore) serialize(w io.Writer) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(k.Values)\n}", "func (v publicKey) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson94b2531bEncodeGitRonaksoftComRiverWebWasmConnection(w, v)\n}", "func (v Bucket) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser27(w, v)\n}", "func (v JwtData) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels16(w, v)\n}", "func jsonEnc(in T) ([]byte, error) {\n\treturn jsonx.Marshal(in)\n}", "func (w Watcher) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", w.Etag)\n\tpopulate(objectMap, \"id\", w.ID)\n\tpopulate(objectMap, \"location\", w.Location)\n\tpopulate(objectMap, \"name\", w.Name)\n\tpopulate(objectMap, \"properties\", w.Properties)\n\tpopulate(objectMap, \"tags\", w.Tags)\n\tpopulate(objectMap, \"type\", w.Type)\n\treturn json.Marshal(objectMap)\n}", "func (myTagKey TagKey) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(map[string]interface{}{\n\t\t\"ID\": myTagKey.IDvar,\n\t\t\"KeyValue\": myTagKey.KeyValuevar,\n\t})\n}", "func (v handshakeRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson2802b09fEncodeGithubComPhilippseithSignalr4(w, v)\n}", "func (sl Slice) MarshalJSON() ([]byte, error) {\n\tnk := len(sl)\n\tb := make([]byte, 0, nk*100+20)\n\tif nk == 0 {\n\t\tb = append(b, []byte(\"null\")...)\n\t\treturn b, nil\n\t}\n\tnstr := fmt.Sprintf(\"[{\\\"n\\\":%d,\", nk)\n\tb = append(b, []byte(nstr)...)\n\tfor i, kid := range sl {\n\t\t// fmt.Printf(\"json out of %v\\n\", kid.PathUnique())\n\t\tknm := kit.Types.TypeName(reflect.TypeOf(kid).Elem())\n\t\ttstr := fmt.Sprintf(\"\\\"type\\\":\\\"%v\\\", \\\"name\\\": \\\"%v\\\"\", knm, kid.UniqueName()) // todo: escape names!\n\t\tb = append(b, []byte(tstr)...)\n\t\tif i < nk-1 {\n\t\t\tb = append(b, []byte(\",\")...)\n\t\t}\n\t}\n\tb = append(b, []byte(\"},\")...)\n\tfor i, kid := range sl {\n\t\tvar err error\n\t\tvar kb []byte\n\t\tkb, err = json.Marshal(kid)\n\t\tif err == nil {\n\t\t\tb = append(b, []byte(\"{\")...)\n\t\t\tb = append(b, kb[1:len(kb)-1]...)\n\t\t\tb = append(b, []byte(\"}\")...)\n\t\t\tif i < nk-1 {\n\t\t\t\tb = append(b, []byte(\",\")...)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"error doing json.Marshall from kid: %v\\n\", kid.PathUnique())\n\t\t\tlog.Println(err)\n\t\t\tfmt.Printf(\"output to point of error: %v\\n\", string(b))\n\t\t}\n\t}\n\tb = append(b, []byte(\"]\")...)\n\t// fmt.Printf(\"json out: %v\\n\", string(b))\n\treturn b, nil\n}", "func JsonMarshal(t interface{}) ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\tenc := json.NewEncoder(buffer)\n\tenc.SetEscapeHTML(false)\n\terr := enc.Encode(t)\n\treturn buffer.Bytes(), err\n}", "func (v ServerKeys) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson94b2531bEncodeGitRonaksoftComRiverWebWasmConnection2(w, v)\n}", "func (jz JSONGzipEncoding) Marshal(v interface{}) ([]byte, error) {\n\tbuf, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// var bufSizeBefore = len(buf)\n\n\tbuf, err = GzipEncode(buf)\n\t// coloredoutput.Infof(\"gzip_json_compress_ratio=%d/%d=%.2f\",\n\t// bufSizeBefore, len(buf), float64(bufSizeBefore)/float64(len(buf)))\n\treturn buf, err\n}", "func (v FormDataMQ) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonB83d7b77EncodeGoplaygroundMyjson(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func EncodeJson(v interface{}) ([]byte, error) {\n\treturn json.ConfigCompatibleWithStandardLibrary.Marshal(v)\n}", "func (v Stash) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(w, v)\n}", "func (key Key) MarshalJSON() ([]byte, error) {\n\tif !key.IsValid() {\n\t\treturn nil, fmt.Errorf(\"unknown key: %v\", key)\n\t}\n\n\treturn json.Marshal(string(key))\n}", "func JSON(data interface{}, args ...interface{}) string {\n\tw := Writer{\n\t\tOptions: ojg.DefaultOptions,\n\t\tWidth: 80,\n\t\tMaxDepth: 3,\n\t\tSEN: false,\n\t}\n\tw.config(args)\n\tb, _ := w.encode(data)\n\n\treturn string(b)\n}", "func (s StreamingPolicyContentKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"label\", s.Label)\n\tpopulate(objectMap, \"policyName\", s.PolicyName)\n\tpopulate(objectMap, \"tracks\", s.Tracks)\n\treturn json.Marshal(objectMap)\n}", "func TestEncode(t *testing.T) {\n\tvar err error\n\tassert := assert.New(t)\n\n\tauthor := bio{\n\t\tFirstname: \"Bastien\",\n\t\tLastname: \"Gysler\",\n\t\tHobbies: []string{\"DJ\", \"Running\", \"Tennis\"},\n\t\tMisc: map[string]string{\n\t\t\t\"lineSeparator\": \"\\u2028\",\n\t\t\t\"Nationality\": \"Swiss\",\n\t\t\t\"City\": \"Zürich\",\n\t\t\t\"foo\": \"\",\n\t\t\t\"bar\": \"\\\"quoted text\\\"\",\n\t\t\t\"esc\": \"escaped \\\\ sanitized\",\n\t\t\t\"r\": \"\\r return line\",\n\t\t\t\"default\": \"< >\",\n\t\t\t\"runeError\": \"\\uFFFD\",\n\t\t},\n\t}\n\n\t// Build document\n\troot := &Node{}\n\troot.AddChild(\"firstname\", &Node{\n\t\tData: author.Firstname,\n\t})\n\troot.AddChild(\"lastname\", &Node{\n\t\tData: author.Lastname,\n\t})\n\n\tfor _, h := range author.Hobbies {\n\t\troot.AddChild(\"hobbies\", &Node{\n\t\t\tData: h,\n\t\t})\n\t}\n\n\tmisc := &Node{}\n\tfor k, v := range author.Misc {\n\t\tmisc.AddChild(k, &Node{\n\t\t\tData: v,\n\t\t})\n\t}\n\troot.AddChild(\"misc\", misc)\n\tvar enc *Encoder\n\n\t// Convert to JSON string\n\tbuf := new(bytes.Buffer)\n\tenc = NewEncoder(buf)\n\n\terr = enc.Encode(nil)\n\tassert.NoError(err)\n\n\tenc.SetAttributePrefix(\"test\")\n\tenc.SetContentPrefix(\"test2\")\n\t// err = enc.EncodeWithCustomPrefixes(root, \"test3\", \"test4\")\n\tenc.CustomPrefixesOption(\"test3\", \"test4\")\n\terr = enc.Encode(root)\n\tassert.NoError(err)\n\n\terr = enc.Encode(root)\n\tassert.NoError(err)\n\n\t// Build SimpleJSON\n\tsj, err := sj.NewJson(buf.Bytes())\n\tres, err := sj.Map()\n\tassert.NoError(err)\n\n\t// Assertions\n\tassert.Equal(author.Firstname, res[\"firstname\"])\n\tassert.Equal(author.Lastname, res[\"lastname\"])\n\n\tresHobbies, err := sj.Get(\"hobbies\").StringArray()\n\tassert.NoError(err)\n\tassert.Equal(author.Hobbies, resHobbies)\n\n\tresMisc, err := sj.Get(\"misc\").Map()\n\tassert.NoError(err)\n\tfor k, v := range resMisc {\n\t\tassert.Equal(author.Misc[k], v)\n\t}\n\n\tenc.err = fmt.Errorf(\"Testing if error provided is returned\")\n\tassert.Error(enc.Encode(nil))\n}", "func (v ProductShrinked) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels3(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (j *Producer) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (f jsonFields) MarshalJSONObject(enc *gojay.Encoder) {\n\tfor _, ctxField := range f {\n\t\tencodeField(enc, ctxField.Key, ctxField.Val)\n\t}\n}", "func signAndEncodeJSON(w io.Writer, v interface{}, privateKey *packet.PrivateKey, config *packet.Config) error {\n\t// Get clearsign encoder.\n\tplaintext, err := clearsign.Encode(w, privateKey, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer plaintext.Close()\n\n\t// Wrap clearsign encoder with JSON encoder.\n\treturn json.NewEncoder(plaintext).Encode(v)\n}", "func (s SSHPublicKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"keyData\", s.KeyData)\n\treturn json.Marshal(objectMap)\n}", "func JsonEncode(i interface{}) string {\n\tb, err := json.Marshal(i)\n\n\tif err != nil {\n\t\tfmt.Println(\"util.getJsonStr.error\", err)\n\t\treturn \"\"\n\t}\n\n\treturn string(b)\n}", "func (a ApplicationGatewaySKU) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"capacity\", a.Capacity)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"tier\", a.Tier)\n\treturn json.Marshal(objectMap)\n}", "func jsonMarshal(t interface{}) ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\tencoder := json.NewEncoder(buffer)\n\tencoder.SetEscapeHTML(false)\n\tencoder.SetIndent(\"\", \" \")\n\terr := encoder.Encode(t)\n\treturn buffer.Bytes(), err\n}", "func (obj CustomObjectKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CustomObjectKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"key-value-document\", Alias: (*Alias)(&obj)})\n}", "func encodeJSON(w io.Writer, v interface{}) (err error) {\n\tenc := json.NewEncoder(w)\n\tenc.SetEscapeHTML(false)\n\treturn enc.Encode(v)\n}", "func (k KeyUsage) MarshalJSON() ([]byte, error) {\n\tvar enc auxKeyUsage\n\tenc.Value = uint32(k)\n\tif k&KeyUsageDigitalSignature > 0 {\n\t\tenc.DigitalSignature = true\n\t}\n\tif k&KeyUsageContentCommitment > 0 {\n\t\tenc.ContentCommitment = true\n\t}\n\tif k&KeyUsageKeyEncipherment > 0 {\n\t\tenc.KeyEncipherment = true\n\t}\n\tif k&KeyUsageDataEncipherment > 0 {\n\t\tenc.DataEncipherment = true\n\t}\n\tif k&KeyUsageKeyAgreement > 0 {\n\t\tenc.KeyAgreement = true\n\t}\n\tif k&KeyUsageCertSign > 0 {\n\t\tenc.CertificateSign = true\n\t}\n\tif k&KeyUsageCRLSign > 0 {\n\t\tenc.CRLSign = true\n\t}\n\tif k&KeyUsageEncipherOnly > 0 {\n\t\tenc.EncipherOnly = true\n\t}\n\tif k&KeyUsageDecipherOnly > 0 {\n\t\tenc.DecipherOnly = true\n\t}\n\treturn json.Marshal(&enc)\n}", "func (c *JSONCodec) Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}", "func (j *Producer) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn nil\n\t}\n\tvar err error\n\tvar obj []byte\n\t_ = obj\n\t_ = err\n\tbuf.WriteString(`{ `)\n\tif len(j.ID) != 0 {\n\t\tbuf.WriteString(`\"id\":`)\n\t\tfflib.WriteJsonString(buf, string(j.ID))\n\t\tbuf.WriteByte(',')\n\t}\n\tif len(j.Name) != 0 {\n\t\tbuf.WriteString(`\"name\":`)\n\t\tfflib.WriteJsonString(buf, string(j.Name))\n\t\tbuf.WriteByte(',')\n\t}\n\tif len(j.Cat) != 0 {\n\t\tbuf.WriteString(`\"cat\":`)\n\t\tif j.Cat != nil {\n\t\t\tbuf.WriteString(`[`)\n\t\t\tfor i, v := range j.Cat {\n\t\t\t\tif i != 0 {\n\t\t\t\t\tbuf.WriteString(`,`)\n\t\t\t\t}\n\t\t\t\tfflib.WriteJsonString(buf, string(v))\n\t\t\t}\n\t\t\tbuf.WriteString(`]`)\n\t\t} else {\n\t\t\tbuf.WriteString(`null`)\n\t\t}\n\t\tbuf.WriteByte(',')\n\t}\n\tif len(j.Domain) != 0 {\n\t\tbuf.WriteString(`\"domain\":`)\n\t\tfflib.WriteJsonString(buf, string(j.Domain))\n\t\tbuf.WriteByte(',')\n\t}\n\tif j.Ext != nil {\n\t\tif true {\n\t\t\tbuf.WriteString(`\"ext\":`)\n\n\t\t\t{\n\n\t\t\t\tobj, err = j.Ext.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t\tbuf.WriteByte(',')\n\t\t}\n\t}\n\tbuf.Rewind(1)\n\tbuf.WriteByte('}')\n\treturn nil\n}", "func JSONEncode(data interface{}) string {\n\tbt, _ := json.Marshal(data)\n\treturn string(bt)\n}", "func (r RegenerateKeyParameters) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"keyName\", r.KeyName)\n\treturn json.Marshal(objectMap)\n}", "func (d DefaultKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"label\", d.Label)\n\tpopulate(objectMap, \"policyName\", d.PolicyName)\n\treturn json.Marshal(objectMap)\n}", "func (v Header) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson171edd05EncodeGithubComEmirmuminogluJwt(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (kem deprecatedKeyEntryMap) MarshalJSON() ([]byte, error) {\n\tintermediate := map[string]KeyEntry{}\n\tfor k, v := range kem {\n\t\tintermediate[strconv.Itoa(k)] = v\n\t}\n\treturn json.Marshal(&intermediate)\n}", "func (v UserJSONT) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6afd136EncodeCourseraWeek3Perf(w, v)\n}", "func (sw SignatureWitness) MarshalJSON() ([]byte, error) {\n\tobj := struct {\n\t\tType string `json:\"type\"`\n\t\tQuorum int `json:\"quorum\"`\n\t\tKeys []keyID `json:\"keys\"`\n\t\tSigs []chainjson.HexBytes `json:\"signatures\"`\n\t}{\n\t\tType: \"signature\",\n\t\tQuorum: sw.Quorum,\n\t\tKeys: sw.Keys,\n\t\tSigs: sw.Sigs,\n\t}\n\treturn json.Marshal(obj)\n}", "func jsonMarshal(t interface{}) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tencoder := json.NewEncoder(&buffer)\n\tencoder.SetEscapeHTML(false)\n\tif err := encoder.Encode(t); err != nil {\n\t\treturn nil, err\n\t}\n\t// Prettify\n\tvar out bytes.Buffer\n\tif err := json.Indent(&out, buffer.Bytes(), \"\", \"\\t\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn out.Bytes(), nil\n}", "func (v Stash) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v SigningPayload) EncodeJSON(b []byte) []byte {\n\tb = append(b, \"{\"...)\n\tif v.AccountIdentifier.Set {\n\t\tb = append(b, '\"', 'a', 'c', 'c', 'o', 'u', 'n', 't', '_', 'i', 'd', 'e', 'n', 't', 'i', 'f', 'i', 'e', 'r', '\"', ':')\n\t\tb = v.AccountIdentifier.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.Address.Set {\n\t\tb = append(b, `\"address\":`...)\n\t\tb = json.AppendString(b, v.Address.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, `\"hex_bytes\":`...)\n\tb = json.AppendHexBytes(b, v.Bytes)\n\tb = append(b, \",\"...)\n\tif v.SignatureType.Set {\n\t\tb = append(b, '\"', 's', 'i', 'g', 'n', 'a', 't', 'u', 'r', 'e', '_', 't', 'y', 'p', 'e', '\"', ':')\n\t\tb = json.AppendString(b, string(v.SignatureType.Value))\n\t\tb = append(b, \",\"...)\n\t}\n\tb[len(b)-1] = '}'\n\treturn b\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tif ImplementsPreJSONMarshaler(v) {\n\t\terr := v.(PreJSONMarshaler).PreMarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn json.Marshal(v)\n}", "func (v EventApplicationKeyAdd) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk20(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (m MultipleActivationKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", m.ID)\n\tpopulate(objectMap, \"location\", m.Location)\n\tpopulate(objectMap, \"name\", m.Name)\n\tpopulate(objectMap, \"properties\", m.Properties)\n\tpopulate(objectMap, \"tags\", m.Tags)\n\tpopulate(objectMap, \"type\", m.Type)\n\treturn json.Marshal(objectMap)\n}", "func (pk PublicKey) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(pk.String())\n}", "func (k KeyDelivery) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"accessControl\", k.AccessControl)\n\treturn json.Marshal(objectMap)\n}", "func (k KeyValueProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"contentType\", k.ContentType)\n\tpopulate(objectMap, \"eTag\", k.ETag)\n\tpopulate(objectMap, \"key\", k.Key)\n\tpopulate(objectMap, \"label\", k.Label)\n\tpopulateTimeRFC3339(objectMap, \"lastModified\", k.LastModified)\n\tpopulate(objectMap, \"locked\", k.Locked)\n\tpopulate(objectMap, \"tags\", k.Tags)\n\tpopulate(objectMap, \"value\", k.Value)\n\treturn json.Marshal(objectMap)\n}", "func (v Bucket) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser27(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (rht *RHT) Marshal() string {\n\tmembers := rht.Members()\n\n\tsize := len(members)\n\tkeys := make([]string, 0, size)\n\tfor k := range members {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tsb := strings.Builder{}\n\tsb.WriteString(\"{\")\n\n\tidx := 0\n\tfor _, k := range keys {\n\t\tvalue := members[k]\n\t\tsb.WriteString(fmt.Sprintf(\"\\\"%s\\\":%s\", k, value.Marshal()))\n\t\tif size-1 != idx {\n\t\t\tsb.WriteString(\",\")\n\t\t}\n\t\tidx++\n\t}\n\tsb.WriteString(\"}\")\n\n\treturn sb.String()\n}", "func (js JobSecrets) MarshalJSON() ([]byte, error) {\n\tjs.JobSecretsType = JobSecretsTypeJobSecrets\n\tobjectMap := make(map[string]interface{})\n\tif js.JobSecretsType != \"\" {\n\t\tobjectMap[\"jobSecretsType\"] = js.JobSecretsType\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v WSRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer3(w, v)\n}", "func (s SecurityDomainJSONWebKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"alg\", s.Alg)\n\tpopulate(objectMap, \"e\", s.E)\n\tpopulate(objectMap, \"key_ops\", s.KeyOps)\n\tpopulate(objectMap, \"kid\", s.Kid)\n\tpopulate(objectMap, \"kty\", s.Kty)\n\tpopulate(objectMap, \"n\", s.N)\n\tpopulate(objectMap, \"use\", s.Use)\n\tpopulate(objectMap, \"x5c\", s.X5C)\n\tpopulate(objectMap, \"x5t\", s.X5T)\n\tpopulate(objectMap, \"x5t#S256\", s.X5TS256)\n\treturn json.Marshal(objectMap)\n}", "func (a APIKeys) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"key1\", a.Key1)\n\tpopulate(objectMap, \"key2\", a.Key2)\n\treturn json.Marshal(objectMap)\n}", "func JSONMarshal(data interface{}) ([]byte, error) {\n\tvar b []byte\n\tvar err error\n\n\tb, err = json.MarshalIndent(data, \"\", \" \")\n\n\treturn b, err\n}", "func (v ServerKeys) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson94b2531bEncodeGitRonaksoftComRiverWebWasmConnection2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (a AppSKUInfo) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", a.Name)\n\treturn json.Marshal(objectMap)\n}", "func (r *Key) marshal(c *Client) ([]byte, error) {\n\tm, err := expandKey(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling Key: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}", "func (om *OrderedMap) MarshalJSON() ([]byte, error) {\n\tbuffer := bytes.NewBufferString(\"{\")\n\n\tfirst := true\n\tfor idx := 0; idx < len(om.kvList); idx++ {\n\t\tif om.kvList[idx] == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !first {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\n\t\tjsonKey, err := json.Marshal(om.kvList[idx].Key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tjsonValue, err := json.Marshal(om.kvList[idx].Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuffer.Write(jsonKey)\n\t\tbuffer.WriteByte(58)\n\t\tbuffer.Write(jsonValue)\n\n\t\tfirst = false\n\t}\n\n\tbuffer.WriteString(\"}\")\n\treturn buffer.Bytes(), nil\n}", "func (v FormDataMQ) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonB83d7b77EncodeGoplaygroundMyjson(w, v)\n}", "func (s Sawshark) MarshalJSON() ([]byte, error) {\n\ts.Fishtype = FishtypeSawshark\n\ttype Alias Sawshark\n\treturn json.Marshal(&struct {\n\t\tAlias\n\t}{\n\t\tAlias: (Alias)(s),\n\t})\n}", "func JsonEncode(data []byte, v interface{}) error {\n\n\treturn json.Unmarshal(data, v)\n}", "func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}", "func (t WKTime) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + t.Encode() + `\"`), nil\n}", "func (v Segment) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonB27eec76EncodeGithubComTisonetOpenrtbEasyjson6(w, v)\n}", "func (v Version) EncodeJSON(b []byte) []byte {\n\tb = append(b, \"{\"...)\n\tif len(v.Metadata) > 0 {\n\t\tb = append(b, `\"metadata\":`...)\n\t\tb = append(b, v.Metadata...)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.MiddlewareVersion.Set {\n\t\tb = append(b, '\"', 'm', 'i', 'd', 'd', 'l', 'e', 'w', 'a', 'r', 'e', '_', 'v', 'e', 'r', 's', 'i', 'o', 'n', '\"', ':')\n\t\tb = json.AppendString(b, v.MiddlewareVersion.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, `\"node_version\":`...)\n\tb = json.AppendString(b, v.NodeVersion)\n\tb = append(b, ',', '\"', 'r', 'o', 's', 'e', 't', 't', 'a', '_', 'v', 'e', 'r', 's', 'i', 'o', 'n', '\"', ':')\n\tb = json.AppendString(b, v.RosettaVersion)\n\treturn append(b, \"}\"...)\n}", "func (gkc *ServiceAccountKey) MarshalJSON() ([]byte, error) {\n\tfmap := make(map[string]any, 2)\n\tfmap[config.AuthorizerTypeProperty] = ServiceAccountKeyAuthorizerType\n\tfmap[\"key\"] = gkc.Key\n\treturn json.Marshal(fmap)\n}", "func (r ResourceSKU) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"kind\", r.Kind)\n\tpopulate(objectMap, \"locations\", r.Locations)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"resourceType\", r.ResourceType)\n\tpopulate(objectMap, \"restrictions\", r.Restrictions)\n\tpopulate(objectMap, \"tier\", r.Tier)\n\treturn json.Marshal(objectMap)\n}", "func (k KeyValueListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", k.NextLink)\n\tpopulate(objectMap, \"value\", k.Value)\n\treturn json.Marshal(objectMap)\n}", "func (s StreamingLocatorContentKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"labelReferenceInStreamingPolicy\", s.LabelReferenceInStreamingPolicy)\n\tpopulate(objectMap, \"policyName\", s.PolicyName)\n\tpopulate(objectMap, \"tracks\", s.Tracks)\n\tpopulate(objectMap, \"type\", s.Type)\n\tpopulate(objectMap, \"value\", s.Value)\n\treturn json.Marshal(objectMap)\n}" ]
[ "0.70164174", "0.6944281", "0.68375885", "0.67024183", "0.6682063", "0.6647078", "0.6481345", "0.647343", "0.64550096", "0.64235896", "0.64145947", "0.637341", "0.6367879", "0.6362876", "0.6359962", "0.63448554", "0.63441277", "0.632238", "0.6312419", "0.62963176", "0.62856406", "0.6265631", "0.6261716", "0.6256516", "0.62548137", "0.6252782", "0.62503266", "0.62421584", "0.6231277", "0.622927", "0.6218251", "0.6206533", "0.62043023", "0.62036794", "0.6196564", "0.6194289", "0.6188456", "0.61871123", "0.6157374", "0.6153328", "0.6150722", "0.6148101", "0.61415404", "0.6137081", "0.61349934", "0.6133089", "0.6127477", "0.61269635", "0.6121031", "0.6115432", "0.61115223", "0.6105062", "0.6103365", "0.61001205", "0.6099189", "0.6098707", "0.6098346", "0.6093518", "0.6092899", "0.6089062", "0.6086912", "0.6084805", "0.6078709", "0.60748154", "0.60713893", "0.60708433", "0.6068613", "0.60673255", "0.6065589", "0.60617447", "0.6054318", "0.60526913", "0.60502553", "0.60501903", "0.60453075", "0.60439044", "0.6041402", "0.6040906", "0.603292", "0.60301286", "0.6028616", "0.6025921", "0.6021722", "0.60215145", "0.60201085", "0.6014257", "0.60117614", "0.60076123", "0.60031813", "0.6003158", "0.60024685", "0.600238", "0.6000753", "0.59971136", "0.5993591", "0.59926677", "0.5991281", "0.5988219", "0.5985796", "0.59833777" ]
0.76333815
0
Validate checkes the JWK object to verify the parameter set represent a valid JWK. If jwk is valid a nil error will be returned. If a JWK is invalid an error will be returned describing the values that causes the validation to fail.
Validate проверяет объект JWK, чтобы убедиться, что набор параметров представляет собой допустимый JWK. Если jwk допустим, будет возвращена nil-ошибка. Если JWK недопустим, будет возвращена ошибка, описывающая значения, приводящие к неудаче проверки.
func (jwk *Jwk) Validate() error { // If the alg parameter is set, make sure it matches the set JWK Type if len(jwk.Algorithm) > 0 { algKeyType := GetKeyType(jwk.Algorithm) if algKeyType != jwk.Type { fmt.Errorf("Jwk Type (kty=%v) doesn't match the algorithm key type (%v)", jwk.Type, algKeyType) } } switch jwk.Type { case KeyTypeRSA: if err := jwk.validateRSAParams(); err != nil { return err } case KeyTypeEC: if err := jwk.validateECParams(); err != nil { return err } case KeyTypeOct: if err := jwk.validateOctParams(); err != nil { return err } default: return errors.New("KeyType (kty) must be EC, RSA or Oct") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (jwk *Jwk) validateECParams() error {\n\tif jwk.X == nil {\n\t\treturn errors.New(\"EC Required Param (X) is nil\")\n\t}\n\tif jwk.Y == nil {\n\t\treturn errors.New(\"EC Required Param (Y) is nil\")\n\t}\n\tif jwk.Curve == nil {\n\t\treturn errors.New(\"EC Required Param (Crv) is nil\")\n\t}\n\treturn nil\n}", "func (pk PublicKey) JWK() JWK {\n\tentry, ok := pk[JwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func (m *RemoteJwks) Validate() error {\n\treturn m.validate(false)\n}", "func mustUnmarshalJWK(s string) *jose.JSONWebKey {\n\tret := &jose.JSONWebKey{}\n\tif err := json.Unmarshal([]byte(s), ret); err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}", "func (jwk *Jwk) validateRSAParams() error {\n\tif jwk.E < 1 {\n\t\treturn errors.New(\"RSA Required Param (E) is empty/default (<= 0)\")\n\t}\n\tif jwk.N == nil {\n\t\treturn errors.New(\"RSA Required Param (N) is nil\")\n\t}\n\n\tpOk := jwk.P != nil\n\tqOk := jwk.Q != nil\n\tdpOk := jwk.Dp != nil\n\tdqOk := jwk.Dq != nil\n\tqiOk := jwk.Qi != nil\n\tothOk := len(jwk.OtherPrimes) > 0\n\n\tparamsOR := pOk || qOk || dpOk || dqOk || qiOk\n\tparamsAnd := pOk && qOk && dpOk && dqOk && qiOk\n\n\tif jwk.D == nil {\n\t\tif (paramsOR || othOk) == true {\n\t\t\treturn errors.New(\"RSA first/second prime values are present but not Private key value (D)\")\n\t\t}\n\t} else {\n\t\tif paramsOR != paramsAnd {\n\t\t\treturn errors.New(\"Not all RSA first/second prime values are present or not present\")\n\t\t} else if !paramsOR && othOk {\n\t\t\treturn errors.New(\"RSA other primes is included but 1st, 2nd prime variables are missing\")\n\t\t} else if othOk {\n\t\t\tfor i, oth := range jwk.OtherPrimes {\n\t\t\t\tif oth.Coeff == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Coeff missing/nil\", i)\n\t\t\t\t} else if oth.R == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, R missing/nil\", i)\n\t\t\t\t} else if oth.Exp == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Exp missing/nil\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *JSONWebKey) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (r VerifyJWTRequest) Validate() error {\n\treturn validation.ValidateStruct(&r,\n\t\tvalidation.Field(&r.Jwt, validation.Required),\n\t)\n}", "func (jwk *Jwk) validateOctParams() error {\n\tif len(jwk.KeyValue) < 1 {\n\t\treturn errors.New(\"Oct Required Param KeyValue (k) is empty\")\n\t}\n\n\treturn nil\n}", "func (ja *JWTAuth) Validate() error {\n\tif len(ja.SignKey) == 0 {\n\t\treturn errors.New(\"sign_key is required\")\n\t}\n\tif len(ja.UserClaims) == 0 {\n\t\tja.UserClaims = []string{\n\t\t\t\"username\",\n\t\t}\n\t}\n\tfor claim, placeholder := range ja.MetaClaims {\n\t\tif claim == \"\" || placeholder == \"\" {\n\t\t\treturn fmt.Errorf(\"invalid meta claim: %s -> %s\", claim, placeholder)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *JwtComponent) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif v, ok := interface{}(m.GetPrivateKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PrivateKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetPublicKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PublicKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewJWK(jwk map[string]interface{}) JWK {\n\treturn jwk\n}", "func (o *GetSlashingParametersOKBodyResult) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *JGroup) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAllowedDomains(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomize(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDefaultChannels(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStackTemplates(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTitle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ThermalSimulationParameters) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAnisotropicStrainCoefficientsParallel(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAnisotropicStrainCoefficientsPerpendicular(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAnisotropicStrainCoefficientsZ(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBeamDiameter(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCoaxialAverageSensorZHeights(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHatchSpacing(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHeaterTemperature(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIncludeStressAnalysis(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInstantDynamicSensorLayers(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInstantDynamicSensorRadius(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInstantStaticSensorRadius(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLaserWattage(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerRotationAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerThickness(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMeshResolutionFactor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputCoaxialAverageSensorData(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputInstantDynamicSensor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputInstantStaticSensor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputPointProbe(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputPointThermalHistory(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputPrintRitePcsSensor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputShrinkage(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputStateMap(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrintRitePcsSensorRadius(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScanSpeed(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSelectedPoints(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSlicingStripeWidth(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartingLayerAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (keySetter *KeySetter) Validate() []string {\n\tvar errorData []string = []string{}\n\tif keySetter.Key == \"\" {\n\t\terrorData = append(errorData, \"field 'key' is required\")\n\t}\n\tif keySetter.Value == \"\" || keySetter.Value == nil {\n\t\terrorData = append(errorData, \"field 'value' is required\")\n\t}\n\tif keySetter.Expiry < 0 {\n\t\terrorData = append(errorData, \"Enter a valid numerical expiry in ms\")\n\t}\n\treturn errorData\n}", "func (o *UIParameter) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := elemental.ValidateRequiredString(\"key\", o.Key); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredString(\"type\", string(o.Type)); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"type\", string(o.Type), []string{\"Boolean\", \"Checkbox\", \"CVSSThreshold\", \"DangerMessage\", \"Duration\", \"Enum\", \"Endpoint\", \"FileDrop\", \"Float\", \"FloatSlice\", \"InfoMessage\", \"Integer\", \"IntegerSlice\", \"JSON\", \"List\", \"Message\", \"Namespace\", \"Password\", \"String\", \"StringSlice\", \"Switch\", \"TagsExpression\", \"Title\", \"WarningMessage\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\t// Custom object validation.\n\tif err := ValidateUIParameters(o); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (k Key) Validate() error {\n\n\t// check method\n\tif err := k.hasValidMethod(); err != nil {\n\t\treturn err\n\t}\n\n\t//check label\n\tif err := k.hasValidLabel(); err != nil {\n\t\treturn err\n\t}\n\n\t// check secret\n\tif err := k.hasValidSecret32(); err != nil {\n\t\treturn err\n\t}\n\n\t// check algo\n\tif err := k.hasValidAlgo(); err != nil {\n\t\treturn err\n\t}\n\n\t// check digits\n\tif err := k.hasValidDigits(); err != nil {\n\t\treturn err\n\t}\n\n\t// check period\n\tif err := k.hasValidPeriod(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetJWTPayload(ctx context.Context) (ValidatedJWTPayload, bool) {\n\tvalue := ctx.Value(key)\n\n\tpayload, ok := value.(ValidatedJWTPayload)\n\tif ok && payload.Validated {\n\t\treturn payload, true\n\t}\n\n\treturn ValidatedJWTPayload{}, false\n}", "func (o *GetSlashingParametersOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateResult(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *MailerConfigInputPayload) Validate() (err error) {\n\tif ut.APIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.APIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.api_key`, *ut.APIKey, utf8.RuneCountInString(*ut.APIKey), 1, true))\n\t\t}\n\t}\n\tif ut.Domain != nil {\n\t\tif utf8.RuneCountInString(*ut.Domain) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.domain`, *ut.Domain, utf8.RuneCountInString(*ut.Domain), 1, true))\n\t\t}\n\t}\n\tif ut.FromName != nil {\n\t\tif utf8.RuneCountInString(*ut.FromName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.from_name`, *ut.FromName, utf8.RuneCountInString(*ut.FromName), 1, true))\n\t\t}\n\t}\n\tif ut.PublicAPIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.PublicAPIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.public_api_key`, *ut.PublicAPIKey, utf8.RuneCountInString(*ut.PublicAPIKey), 1, true))\n\t\t}\n\t}\n\treturn\n}", "func (c AuthConfig) Validate() []error {\n\tvar errs []error\n\n\tif len(c.JwksURI) == 0 {\n\t\terrs = append(errs, errors.Errorf(\"AuthConfig requires a non-empty JwksURI config value\"))\n\t}\n\n\treturn errs\n}", "func (asap *ASAP) Validate(jwt jwt.JWT, publicKey cr.PublicKey) error {\n\theader := jwt.(jws.JWS).Protected()\n\tkid := header.Get(KeyID).(string)\n\talg := header.Get(algorithm).(string)\n\n\tsigningMethod, err := getSigningMethod(alg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jwt.Validate(publicKey, signingMethod, validator.GenerateValidator(kid, asap.ServiceID))\n}", "func (c openIDConfiguration) Validate() error {\n\tswitch {\n\tcase c.Issuer == \"\":\n\t\treturn errors.New(\"issuer cannot be empty\")\n\tcase c.JWKSetURI == \"\":\n\t\treturn errors.New(\"jwks_uri cannot be empty\")\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (jwk *Jwk) MarshalJSON() (data []byte, err error) {\n\n\t// Remove any potentionally conflicting claims from the JWK's additional members\n\tdelete(jwk.AdditionalMembers, \"kty\")\n\tdelete(jwk.AdditionalMembers, \"kid\")\n\tdelete(jwk.AdditionalMembers, \"alg\")\n\tdelete(jwk.AdditionalMembers, \"use\")\n\tdelete(jwk.AdditionalMembers, \"key_ops\")\n\tdelete(jwk.AdditionalMembers, \"crv\")\n\tdelete(jwk.AdditionalMembers, \"x\")\n\tdelete(jwk.AdditionalMembers, \"y\")\n\tdelete(jwk.AdditionalMembers, \"d\")\n\tdelete(jwk.AdditionalMembers, \"n\")\n\tdelete(jwk.AdditionalMembers, \"p\")\n\tdelete(jwk.AdditionalMembers, \"q\")\n\tdelete(jwk.AdditionalMembers, \"dp\")\n\tdelete(jwk.AdditionalMembers, \"dq\")\n\tdelete(jwk.AdditionalMembers, \"qi\")\n\tdelete(jwk.AdditionalMembers, \"e\")\n\tdelete(jwk.AdditionalMembers, \"oth\")\n\tdelete(jwk.AdditionalMembers, \"k\")\n\n\t// There are additional claims, individually marshal each member\n\tobj := make(map[string]*json.RawMessage, len(jwk.AdditionalMembers)+10)\n\n\tif bytes, err := json.Marshal(jwk.Type); err == nil {\n\t\trm := json.RawMessage(bytes)\n\t\tobj[\"kty\"] = &rm\n\t} else {\n\t\treturn nil, err\n\t}\n\n\tif len(jwk.Id) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Id); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"kid\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Algorithm) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Algorithm); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"alg\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Use) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Use); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"use\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Operations) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Operations); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"key_ops\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tswitch jwk.Type {\n\tcase KeyTypeEC:\n\t\t{\n\t\t\tif jwk.Curve != nil {\n\t\t\t\tjwk.Curve.Params()\n\t\t\t\tp := jwk.Curve.Params()\n\t\t\t\tif bytes, err := json.Marshal(p.Name); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"crv\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.X != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.X}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"x\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Y != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Y}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"y\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.D != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.D}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"d\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase KeyTypeRSA:\n\t\t{\n\t\t\tif jwk.D != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.D}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"d\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif jwk.N != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.N}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"n\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.P != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.P}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"p\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Q != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Q}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"q\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Dp != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Dp}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"dp\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Dq != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Dq}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"dq\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Qi != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Qi}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"qi\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.E >= 0 {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: big.NewInt(int64(jwk.E))}\n\t\t\t\tif bytes, err := json.Marshal(&b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"e\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(jwk.OtherPrimes) > 0 {\n\t\t\t\ttempOthPrimes := make([]jwkOthPrimeJSON, len(jwk.OtherPrimes))\n\t\t\t\tfor i, v := range jwk.OtherPrimes {\n\t\t\t\t\ttempOthPrimes[i].Coeff = &Base64UrlUInt{UInt: v.Coeff}\n\t\t\t\t\ttempOthPrimes[i].Exp = &Base64UrlUInt{UInt: v.Exp}\n\t\t\t\t\ttempOthPrimes[i].R = &Base64UrlUInt{UInt: v.R}\n\t\t\t\t}\n\n\t\t\t\tif bytes, err := json.Marshal(tempOthPrimes); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"oth\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase KeyTypeOct:\n\t\t{\n\t\t\tif len(jwk.KeyValue) > 0 {\n\t\t\t\tb64o := &Base64UrlOctets{Octets: jwk.KeyValue}\n\t\t\t\tif bytes, err := json.Marshal(b64o); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"k\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\t//Iterate through remaing members and add to json rawMessage\n\tfor k, v := range jwk.AdditionalMembers {\n\t\tif bytes, err := json.Marshal(v); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[k] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Marshal obj\n\treturn json.Marshal(obj)\n}", "func (a *Service) ValidateJweToken(token string) (map[string]interface{}, *error_utils.ApiError) {\n\n\t// parse token string\n\tclaims, err := a.parseTokenString(token)\n\tif err != nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(err.Error())\n\t}\n\n\t// validate dates\n\tif claims[\"orig_iat\"] == nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Orig Iat is missing\")\n\t}\n\n\t// try convert to float64\n\tif _, ok := claims[\"orig_iat\"].(float64); !ok {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Orig Iat must be float64 format\")\n\t}\n\n\t// get value and validate\n\torigIat := int64(claims[\"orig_iat\"].(float64))\n\tif origIat < a.timeFunc().Add(-a.maxRefresh).Unix() {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Token is expired\")\n\t}\n\n\t// check if exp exists in map\n\tif claims[\"exp\"] == nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Exp is missing\")\n\t}\n\n\t// try convert to float 64\n\tif _, ok := claims[\"exp\"].(float64); !ok {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Exp must be float64 format\")\n\t}\n\n\t// get value and validate\n\texp := int64(claims[\"exp\"].(float64))\n\tif exp < a.timeFunc().Unix(){\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Token is expired\")\n\t}\n\t// validate dates\n\n\t// validate issuer\n\t// check if iss exists in map\n\tif claims[\"iss\"] == nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Iss is missing\")\n\t}\n\n\t// try convert to string\n\tif _, ok := claims[\"iss\"].(string); !ok {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Iss must be string format\")\n\t}\n\n\t// get value and validate\n\tissuer := claims[\"iss\"]\n\tif issuer != a.issuer{\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Invalid issuer\")\n\t}\n\t// validate issuer\n\n\treturn claims, nil\n}", "func (kv BatchJobReplicateKV) Validate() error {\n\tif kv.Key == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\treturn nil\n}", "func (o *V0037JobProperties) GetWckeyOk() (*string, bool) {\n\tif o == nil || o.Wckey == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Wckey, true\n}", "func (r *BatchJobKeyRotateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error {\n\tif r == nil {\n\t\treturn nil\n\t}\n\n\tif r.APIVersion != batchKeyRotateAPIVersion {\n\t\treturn errInvalidArgument\n\t}\n\n\tif r.Bucket == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\n\tif _, err := o.GetBucketInfo(ctx, r.Bucket, BucketOptions{}); err != nil {\n\t\tif isErrBucketNotFound(err) {\n\t\t\treturn batchKeyRotationJobError{\n\t\t\t\tCode: \"NoSuchSourceBucket\",\n\t\t\t\tDescription: \"The specified source bucket does not exist\",\n\t\t\t\tHTTPStatusCode: http.StatusNotFound,\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\tif GlobalKMS == nil {\n\t\treturn errKMSNotConfigured\n\t}\n\tif err := r.Encryption.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, tag := range r.Flags.Filter.Tags {\n\t\tif err := tag.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, meta := range r.Flags.Filter.Metadata {\n\t\tif err := meta.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := r.Flags.Retry.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewJwkSet(target string) (*JwkSet, error) {\n\tif target == \"\" {\n\t\treturn nil, errors.New(\"invalid empty target url\")\n\t}\n\n\tdata, err := getHttpRespData(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseJwksData(data)\n}", "func (k *Kubelet) Validate() error {\n\tvar errors util.ValidateErrors\n\n\tb, err := yaml.Marshal(k)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"serializing configuration: %w\", err))\n\t}\n\n\tif err := yaml.Unmarshal(b, &k); err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"deserializing configuration: %w\", err))\n\t}\n\n\tif k.KubernetesCACertificate == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"kubernetesCACertificate can't be empty\"))\n\t}\n\n\terrors = append(errors, k.validateBootstrapConfig()...)\n\n\tif k.VolumePluginDir == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"volumePluginDir can't be empty\"))\n\t}\n\n\tif err := k.validateAdminConfig(); err != nil {\n\t\terrors = append(errors, err)\n\t}\n\n\tif err := k.Host.Validate(); err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"validating host configuration: %w\", err))\n\t}\n\n\tif k.Name == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"name can't be empty\"))\n\t}\n\n\treturn errors.Return()\n}", "func (ut *mailerConfigInputPayload) Validate() (err error) {\n\tif ut.APIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.APIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.api_key`, *ut.APIKey, utf8.RuneCountInString(*ut.APIKey), 1, true))\n\t\t}\n\t}\n\tif ut.Domain != nil {\n\t\tif utf8.RuneCountInString(*ut.Domain) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.domain`, *ut.Domain, utf8.RuneCountInString(*ut.Domain), 1, true))\n\t\t}\n\t}\n\tif ut.FromName != nil {\n\t\tif utf8.RuneCountInString(*ut.FromName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.from_name`, *ut.FromName, utf8.RuneCountInString(*ut.FromName), 1, true))\n\t\t}\n\t}\n\tif ut.PublicAPIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.PublicAPIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.public_api_key`, *ut.PublicAPIKey, utf8.RuneCountInString(*ut.PublicAPIKey), 1, true))\n\t\t}\n\t}\n\treturn\n}", "func Validate(schema, document string) (result *gojsonschema.Result, err error) {\n\tschemaLoader := gojsonschema.NewStringLoader(schema)\n\tdocumentLoader := gojsonschema.NewStringLoader(document)\n\treturn gojsonschema.Validate(schemaLoader, documentLoader)\n}", "func NewJwk(kty string) (j *Jwk, err error) {\n\tswitch kty {\n\tcase KeyTypeOct, KeyTypeRSA, KeyTypeEC:\n\t\tj = &Jwk{Type: kty}\n\tdefault:\n\t\terr = errors.New(\"Key Type Invalid. Must be Oct, RSA or EC\")\n\t}\n\n\treturn\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func (o *GetWellKnownJSONWebKeysInternalServerErrorBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *JSONWebKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (p PostGIS) WKTIsValidWithReason(wkt string) (bool, string) {\n\tvar isValid bool\n\tvar reason string\n\terr := p.db.QueryRow(`\n\t\tSELECT\n\t\t\tST_IsValid(ST_GeomFromText($1)),\n\t\t\tST_IsValidReason(ST_GeomFromText($1))`,\n\t\twkt,\n\t).Scan(&isValid, &reason)\n\tif err != nil {\n\t\t// It's not possible to distinguish between problems with the geometry\n\t\t// and problems with the database except by string-matching. It's\n\t\t// better to just report all errors, even if this means there will be\n\t\t// some false errors in the case of connectivity problems (or similar).\n\t\treturn false, err.Error()\n\t}\n\treturn isValid, reason\n}", "func (kv BatchKeyRotateKV) Validate() error {\n\tif kv.Key == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\treturn nil\n}", "func (m *JwtRequirement) Validate() error {\n\treturn m.validate(false)\n}", "func (jz *Jzon) Validate(validator *Jzon) (ok bool, report *Jzon, err error) {\n\t// TODO:\n\treturn\n}", "func (c *JWTClaimsJSON) Valid() error {\n\tif c.UID == \"\" {\n\t\treturn fmt.Errorf(\"UID must be present in token claims\")\n\t}\n\tif c.Expiry == 0 {\n\t\treturn fmt.Errorf(\"Token has no expiry\")\n\t}\n\tif c.Expiry < int(time.Now().Unix()) {\n\t\treturn fmt.Errorf(\"Token has expired\")\n\t}\n\tif c.Iat > int(time.Now().Unix()+int64(time.Second)) {\n\t\treturn fmt.Errorf(\"Token is from the future\")\n\t}\n\tif c.Issuer != config.AuthStrategyLDAPIssuer {\n\t\treturn fmt.Errorf(\"token is invalid because of authentication strategy mismatch\")\n\t}\n\treturn nil\n}", "func (m *JwtHeader) Validate() error {\n\treturn m.validate(false)\n}", "func (m *MV12WE) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateQuality(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResolution(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s JBIG2EncoderSettings) Validate() error {\n\tconst processName = \"validateEncoder\"\n\tif s.Threshold < 0 || s.Threshold > 1.0 {\n\t\treturn errors.Errorf(processName, \"provided threshold value: '%v' must be in range [0.0, 1.0]\", s.Threshold)\n\t}\n\tif s.ResolutionX < 0 {\n\t\treturn errors.Errorf(processName, \"provided x resolution: '%d' must be positive or zero value\", s.ResolutionX)\n\t}\n\tif s.ResolutionY < 0 {\n\t\treturn errors.Errorf(processName, \"provided y resolution: '%d' must be positive or zero value\", s.ResolutionY)\n\t}\n\tif s.DefaultPixelValue != 0 && s.DefaultPixelValue != 1 {\n\t\treturn errors.Errorf(processName, \"default pixel value: '%d' must be a value for the bit: {0,1}\", s.DefaultPixelValue)\n\t}\n\tif s.Compression != JB2Generic {\n\t\treturn errors.Errorf(processName, \"provided compression is not implemented yet\")\n\t}\n\treturn nil\n}", "func (p Params) Validate() error {\n\tif err := validateTokenCourse(p.TokenCourse); err != nil {\n\t\treturn err\n\t}\n\tif err := validateSubscriptionPrice(p.SubscriptionPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateVPNGBPrice(p.VPNGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateStorageGBPrice(p.StorageGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseVPNGb(p.BaseVPNGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseStorageGb(p.BaseStorageGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateCourseChangeSigners(p.CourseChangeSigners); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ut *jSONDataMetaStationFirmware) Validate() (err error) {\n\tif ut.Version == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"version\"))\n\t}\n\tif ut.Build == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"build\"))\n\t}\n\tif ut.Number == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"number\"))\n\t}\n\tif ut.Timestamp == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"timestamp\"))\n\t}\n\tif ut.Hash == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"hash\"))\n\t}\n\treturn\n}", "func (o *UserCurrentGetGPGKeyOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCanCertify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanEncryptComms(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanEncryptStorage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanSign(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateExpires(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateKeyID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePrimaryKeyID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePublicKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSubsKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (v GetWAPSelectedHostnamesRequest) Validate() error {\n\treturn validation.Errors{\n\t\t\"ConfigID\": validation.Validate(v.ConfigID, validation.Required),\n\t\t\"Version\": validation.Validate(v.Version, validation.Required),\n\t\t\"SecurityPolicyID\": validation.Validate(v.Version, validation.Required),\n\t}.Filter()\n}", "func (o *dryrunOptions) validate() error {\n\tif o.userWPAName == \"\" && o.labelSelector == \"\" && !o.allWPA {\n\t\treturn fmt.Errorf(\"the watermarkpodautoscaler name or label-selector is required\")\n\t}\n\n\treturn nil\n}", "func (m *JwtProvider) Validate() error {\n\treturn m.validate(false)\n}", "func (m *ScopedRoutes_ScopeKeyBuilder_FragmentBuilder_HeaderValueExtractor_KvElement) Validate() error {\n\treturn m.validate(false)\n}", "func (m *WasmParams) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (o *OAUTHKey) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (o *GetFwLeaderboardsCharactersOKBodyKills) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateActiveTotal(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateLastWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateYesterday(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func Validate(schema *gojsonschema.Schema, document gojsonschema.JSONLoader) (*errors.Errs, error) {\n\tresult, err := schema.Validate(document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Valid() {\n\t\treturn nil, nil\n\t}\n\tvar errs errors.Errs\n\tfor _, resultErr := range result.Errors() {\n\t\terrs = append(errs, resultErrorToError(resultErr))\n\t}\n\treturn &errs, nil\n}", "func JWTValidator(certificates map[string]CertificateList) jwt.Keyfunc {\n\treturn func(token *jwt.Token) (interface{}, error) {\n\n\t\tvar certificateList CertificateList\n\t\tvar kid string\n\t\tvar ok bool\n\n\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\tif kid, ok = token.Header[\"kid\"].(string); !ok {\n\t\t\treturn nil, fmt.Errorf(\"field 'kid' is of invalid type %T, should be string\", token.Header[\"kid\"])\n\t\t}\n\n\t\tif certificateList, ok = certificates[kid]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"kid '%s' not found in certificate list\", kid)\n\t\t}\n\n\t\tfor _, certificate := range certificateList {\n\t\t\treturn certificate.PublicKey, nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"no certificate candidates for kid '%s'\", kid)\n\t}\n}", "func (m *KeyPair) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with Resource\n\tif err := m.Resource.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r UserDetailsRequest) Validate() error {\n\treturn validation.ValidateStruct(&r,\n\t\tvalidation.Field(&r.Jwt, validation.Required),\n\t)\n}", "func (j *Job) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: j.Name, Name: \"Name\"},\n\t\t&validators.StringIsPresent{Field: j.Description, Name: \"Description\"},\n\t\t&validators.StringIsPresent{Field: j.Salary, Name: \"Salary\"},\n\t), nil\n}", "func (m *JwtAuthentication) Validate() error {\n\treturn m.validate(false)\n}", "func ValidateToken(tokenStr string, jwk map[string]JWKKey) (*jwt.Token, error) {\n\t// @note 2. Decode the token string into JWT format.\n\ttoken, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {\n\t\t// Methods both of Cognito User Pools and Google are RS256\n\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\t\t// @note 5. Get the kid from the JWT token header and retrieve the corresponding JSON Web Key that was stored\n\t\tif kid, ok := token.Header[\"kid\"]; ok {\n\t\t\tif kidStr, ok := kid.(string); ok {\n\t\t\t\tkey := jwk[kidStr]\n\t\t\t\t// @note 6. Verify the signature of the decoded JWT token.\n\t\t\t\trsaPublicKey := convertKey(key.E, key.N)\n\t\t\t\treturn rsaPublicKey, nil\n\t\t\t}\n\t\t}\n\t\t// Does not get RSA public key\n\t\treturn \"\", nil\n\t})\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\tclaims := token.Claims.(jwt.MapClaims)\n\tiss, ok := claims[\"iss\"]\n\tif !ok {\n\t\treturn token, fmt.Errorf(\"token does not contain issuer\")\n\t}\n\n\tissStr := iss.(string)\n\tif strings.Contains(issStr, \"cognito-idp\") {\n\t\terr = validateAWSJWTClaims(claims)\n\t\tif err != nil {\n\t\t\treturn token, err\n\t\t}\n\t} else if strings.Contains(issStr, \"accounts.google.com\") {\n\t\terr = validateGoogleJWTClaims(claims)\n\t\tif err != nil {\n\t\t\treturn token, err\n\t\t}\n\t}\n\n\tif token.Valid {\n\t\treturn token, nil\n\t}\n\n\treturn token, err\n}", "func (m JwtVapiClaims) Valid() error {\n\treturn nil\n}", "func Validate() error {\n\terrors := err.Errors()\n\tfor name, variable := range env.variables {\n\t\tif Get(name) == nil && variable.required {\n\t\t\terrors.AddError(err.Error(\"Property \" + name + \" not provided!\"))\n\t\t}\n\t}\n\tif errors.Count() > 0 {\n\t\tif env.settings.FailOnMissingRequired {\n\t\t\tpanic(errors)\n\t\t}\n\t\treturn errors\n\t}\n\treturn nil\n}", "func (ut *updateDeviceFirmwarePayload) Validate() (err error) {\n\tif ut.DeviceID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"deviceId\"))\n\t}\n\tif ut.FirmwareID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"firmwareId\"))\n\t}\n\treturn\n}", "func validateJWT(w http.ResponseWriter, req *http.Request) {\n\tif klog.V(3).Enabled() {\n\t\tklog.Infof(\"request received from: %v, headers: %v\", req.RemoteAddr, req.Header)\n\t}\n\tiapJWT := req.Header.Get(\"X-Goog-IAP-JWT-Assertion\")\n\tif iapJWT == \"\" {\n\t\tklog.V(1).Infof(\"X-Goog-IAP-JWT-Assertion header not found\")\n\t\thttp.Error(w, \"\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tif audience == \"\" {\n\t\tklog.V(1).ErrorS(fmt.Errorf(\"token cannot be validated, empty audience, check for previous errors\"), \"\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif issuer == \"\" {\n\t\tklog.V(1).ErrorS(fmt.Errorf(\"token cannot be validated, empty issuer, check for previous errors\"), \"\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tctx := context.Background()\n\t// we pass empty as audience here because we will validate it later\n\tpayload, err := jwtValidator.Validate(ctx, iapJWT, \"\")\n\tklog.V(3).Infof(\"payload received: %+v\", payload)\n\tif err != nil {\n\t\tklog.V(1).ErrorS(err, \"error validating jwt token\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// empty payload should not be possible\n\tif payload == nil {\n\t\tklog.V(1).ErrorS(nil, \"null payload received\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// validate the audience\n\tif audience != payload.Audience {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, invalid audience, expected %s, got %s\", audience, payload.Audience)\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// validate the issuer\n\tif issuer != payload.Issuer {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, invalid issuer, expected %s, got %s\", issuer, payload.Issuer)\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// validate expired - this may be redundant - but we check it anyway\n\tif payload.Expires == 0 || payload.Expires+30 < time.Now().Unix() {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, expired\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\t// validate IssuedAt - should not be in the future\n\tif payload.IssuedAt == 0 || payload.IssuedAt-30 > time.Now().Unix() {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, emitted in the future\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}", "func (p *Params) ValidateRequiredProperties() (bool, []error, []string) {\n\n\terrors := []error{}\n\twarnings := []string{}\n\n\t// validate app params\n\tif p.App == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Application name is required; either define an app label or use app property on this stage\"))\n\t}\n\tif p.Namespace == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Namespace is required; either use credentials with a defaultNamespace or set it via namespace property on this stage\"))\n\t}\n\n\tif p.Action == \"rollback-canary\" {\n\t\t// the above properties are all you need for a rollback\n\t\treturn len(errors) == 0, errors, warnings\n\t}\n\n\t// validate container params\n\tif p.Container.ImageRepository == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image repository is required; set it via container.repository property on this stage\"))\n\t}\n\tif p.Container.ImageName == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image name is required; set it via container.name property on this stage\"))\n\t}\n\tif p.Container.ImageTag == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image tag is required; set it via container.tag property on this stage\"))\n\t}\n\n\t// validate cpu params\n\tif p.Container.CPU.Request == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Cpu request is required; set it via container.cpu.request property on this stage\"))\n\t}\n\tif p.Container.CPU.Limit == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Cpu limit is required; set it via container.cpu.limit property on this stage\"))\n\t}\n\n\t// validate memory params\n\tif p.Container.Memory.Request == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Memory request is required; set it via container.memory.request property on this stage\"))\n\t}\n\tif p.Container.Memory.Limit == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Memory limit is required; set it via container.memory.limit property on this stage\"))\n\t}\n\n\t// defaults for rollingupdate\n\tif p.RollingUpdate.MaxSurge == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Rollingupdate max surge is required; set it via rollingupdate.maxsurge property on this stage\"))\n\t}\n\tif p.RollingUpdate.MaxUnavailable == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Rollingupdate max unavailable is required; set it via rollingupdate.maxunavailable property on this stage\"))\n\t}\n\n\tif p.Kind == \"job\" || p.Kind == \"cronjob\" {\n\t\tif p.Kind == \"cronjob\" {\n\t\t\tif p.Schedule == \"\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Schedule is required for a cronjob; set it via schedule property on this stage\"))\n\t\t\t}\n\n\t\t\tif p.ConcurrencyPolicy != \"Allow\" && p.ConcurrencyPolicy != \"Forbid\" && p.ConcurrencyPolicy != \"Replace\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"ConcurrencyPolicy is invalid; allowed values are Allow, Forbid or Replace\"))\n\t\t\t}\n\t\t}\n\n\t\t// the above properties are all you need for a worker\n\t\treturn len(errors) == 0, errors, warnings\n\t}\n\n\t// validate params with respect to incoming requests\n\tif p.Visibility == \"\" || (p.Visibility != \"private\" && p.Visibility != \"public\" && p.Visibility != \"iap\" && p.Visibility != \"public-whitelist\") {\n\t\terrors = append(errors, fmt.Errorf(\"Visibility property is required; set it via visibility property on this stage; allowed values are private, iap, public-whitelist or public\"))\n\t}\n\tif p.Visibility == \"iap\" && p.IapOauthCredentialsClientID == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"With visibility 'iap' property iapOauthClientID is required; set it via iapOauthClientID property on this stage\"))\n\t}\n\tif p.Visibility == \"iap\" && p.IapOauthCredentialsClientSecret == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"With visibility 'iap' property iapOauthClientSecret is required; set it via iapOauthClientSecret property on this stage\"))\n\t}\n\n\tif len(p.Hosts) == 0 {\n\t\terrors = append(errors, fmt.Errorf(\"At least one host is required; set it via hosts array property on this stage\"))\n\t}\n\tfor _, host := range p.Hosts {\n\t\tif len(host) > 253 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Host %v is longer than the allowed 253 characters, which is invalid for DNS; please shorten your host\", host))\n\t\t\tbreak\n\t\t}\n\n\t\tmatchesInvalidChars, _ := regexp.MatchString(\"[^a-zA-Z0-9-.]\", host)\n\t\tif matchesInvalidChars {\n\t\t\terrors = append(errors, fmt.Errorf(\"Host %v has invalid characters; only a-z, 0-9, - and . are allowed; please fix your host\", host))\n\t\t}\n\n\t\thostLabels := strings.Split(host, \".\")\n\t\tfor _, label := range hostLabels {\n\t\t\tif len(label) > 63 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Host %v has label %v - the parts between dots - that is longer than the allowed 63 characters, which is invalid for DNS; please shorten your host label\", host, label))\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, host := range p.InternalHosts {\n\t\tif len(host) > 253 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v is longer than the allowed 253 characters, which is invalid for DNS; please shorten your host\", host))\n\t\t\tbreak\n\t\t}\n\n\t\tmatchesInvalidChars, _ := regexp.MatchString(\"[^a-zA-Z0-9-.]\", host)\n\t\tif matchesInvalidChars {\n\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v has invalid characters; only a-z, 0-9, - and . are allowed; please fix your host\", host))\n\t\t}\n\n\t\thostLabels := strings.Split(host, \".\")\n\t\tfor _, label := range hostLabels {\n\t\t\tif len(label) > 63 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v has label %v - the parts between dots - that is longer than the allowed 63 characters, which is invalid for DNS; please shorten your host label\", host, label))\n\t\t\t}\n\t\t}\n\t}\n\n\tif p.Basepath == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Basepath property is required; set it via basepath property on this stage\"))\n\t}\n\tif p.Container.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Container port must be larger than zero; set it via container.port property on this stage\"))\n\t}\n\n\t// validate autoscale params\n\tif p.Autoscale.MinReplicas <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling min replicas must be larger than zero; set it via autoscale.min property on this stage\"))\n\t}\n\tif p.Autoscale.MaxReplicas <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling max replicas must be larger than zero; set it via autoscale.max property on this stage\"))\n\t}\n\tif p.Autoscale.CPUPercentage <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling cpu percentage must be larger than zero; set it via autoscale.cpu property on this stage\"))\n\t}\n\n\t// validate liveness params\n\tif p.Container.LivenessProbe.Path == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness path is required; set it via container.liveness.path property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness port must be larger than zero; set it via container.liveness.port property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.InitialDelaySeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness initial delay must be larger than zero; set it via container.liveness.delay property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.TimeoutSeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness timeout must be larger than zero; set it via container.liveness.timeout property on this stage\"))\n\t}\n\n\t// validate readiness params\n\tif p.Container.ReadinessProbe.Path == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness path is required; set it via container.readiness.path property on this stage\"))\n\t}\n\tif p.Container.ReadinessProbe.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness port must be larger than zero; set it via container.readiness.port property on this stage\"))\n\t}\n\tif p.Container.ReadinessProbe.TimeoutSeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness timeout must be larger than zero; set it via container.readiness.timeout property on this stage\"))\n\t}\n\n\t// validate metrics params\n\tif p.Container.Metrics.Scrape == nil {\n\t\terrors = append(errors, fmt.Errorf(\"Metrics scrape is required; set it via container.metrics.scrape property on this stage; allowed values are true or false\"))\n\t}\n\tif p.Container.Metrics.Scrape != nil && *p.Container.Metrics.Scrape {\n\t\tif p.Container.Metrics.Path == \"\" {\n\t\t\terrors = append(errors, fmt.Errorf(\"Metrics path is required; set it via container.metrics.path property on this stage\"))\n\t\t}\n\t\tif p.Container.Metrics.Port <= 0 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Metrics port must be larger than zero; set it via container.metrics.port property on this stage\"))\n\t\t}\n\t}\n\n\t// The \"sidecar\" field is deprecated, so it can be empty. But if it's specified, then we validate it.\n\tif p.Sidecar.Type != \"\" && p.Sidecar.Type != \"none\" {\n\t\terrors = p.validateSidecar(&p.Sidecar, errors)\n\t\twarnings = append(warnings, \"The sidecar field is deprecated, the sidecars list should be used instead.\")\n\t}\n\n\t// validate sidecars params\n\tfor _, sidecar := range p.Sidecars {\n\t\terrors = p.validateSidecar(sidecar, errors)\n\t}\n\n\treturn len(errors) == 0, errors, warnings\n}", "func (pr *Params) Validate() error {\n\tnames := []string{}\n\tfor nm := range pr.Objects {\n\t\tnames = append(names, nm)\n\t}\n\treturn pr.Params.ValidateSheets(names)\n}", "func (skmr *SecretKeyMemberRequest) Validate() error {\n\tif skmr.AccountID == nil {\n\t\treturn ErrInvalidAccountID\n\t}\n\n\tif skmr.SecretKeyID == nil {\n\t\treturn ErrInvalidKeyID\n\t}\n\n\treturn nil\n}", "func (m *FortifyJob) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvokingUserName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateJobState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateJobType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *GcpKms) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateLinks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateApplicationCredentials(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGcpKmsInlineEkmipReachability(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGoogleReachability(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProxyType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScope(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSvm(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (mt *EasypostAPIKey) Validate() (err error) {\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\tif mt.Mode == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"mode\"))\n\t}\n\tif mt.Key == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"key\"))\n\t}\n\tif mt.CreatedAt == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"created_at\"))\n\t}\n\n\tif !(mt.Mode == \"test\" || mt.Mode == \"production\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.mode`, mt.Mode, []interface{}{\"test\", \"production\"}))\n\t}\n\tif ok := goa.ValidatePattern(`^ApiKey$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^ApiKey$`))\n\t}\n\treturn\n}", "func (m *EnvironmentRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCredential(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKerberosConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKubernetesConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLdapConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLocation(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProxyConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRdsConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRegions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (JSONSchema) Validate(json string) error {\n\treturn nil\n}", "func (m *SoftwareDataEncryption) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (c configuration) Validate() error {\n\tvar errs error\n\n\terrs = errors.Append(errs, c.Auth.Validate())\n\terrs = errors.Append(errs, c.Config.Validate())\n\n\tif c.Environment == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"environment is required\"))\n\t}\n\n\t// TODO: this config is only used here, so the validation is here too. Either the config or the validation should be moved somewhere else.\n\tif c.Distribution.PKE.Amazon.GlobalRegion == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"pke amazon global region is required\"))\n\t}\n\n\treturn errs\n}", "func (plan *DeploymentPlan) Validate() error {\n\n\terr := checkRequired(&plan.VMWConfig.VCenterURL,\n\t\t\"VMware vCenter/vSphere credentials are missing\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.DCName,\n\t\t\"No Datacenter was specified, will try to use the default (will cause errors with Linked-Mode)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.DSName,\n\t\t\"A VMware vCenter datastore is required for provisioning\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.NetworkName,\n\t\t\"Specify a Network to connect to\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.VSphereHost,\n\t\t\"A Host inside of vCenter/vSphere is required to provision on for VM capacity\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ideally these should be populated as they're needed for a lot of the tasks.\n\terr = checkRequired(&plan.VMWConfig.VMTemplateAuth.Username,\n\t\t\"No Username for inside of the Guest OS was specified, somethings may fail\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.VMTemplateAuth.Password,\n\t\t\"No Password for inside of the Guest OS was specified, somethings may fail\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif plan.VMWConfig.VCenterURL == \"\" || plan.VMWConfig.DSName == \"\" || plan.VMWConfig.VSphereHost == \"\" {\n\t\treturn fmt.Errorf(\"Missing VSphere host\")\n\t}\n\n\treturn nil\n}", "func (e JwtHeaderValidationError) Key() bool { return e.key }", "func (m *JwtRequirementOrList) Validate() error {\n\treturn m.validate(false)\n}", "func Validate(fileName string, input string) error {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tschemaURI := fmt.Sprintf(\"file://%s\", filepath.Join(pwd, fileName))\n\n\tschemaLoader := gojsonschema.NewReferenceLoader(schemaURI)\n\tdocumentLoader := gojsonschema.NewStringLoader(input)\n\n\tresult, err := gojsonschema.Validate(schemaLoader, documentLoader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error loading JSON schema, error: %v\", err)\n\t}\n\n\tif result.Valid() {\n\t\treturn nil\n\t}\n\tfmt.Printf(\"Errors for JSON schema: '%s'\\n\", schemaURI)\n\tfor _, desc := range result.Errors() {\n\t\tfmt.Printf(\"\\t- %s\\n\", desc)\n\t}\n\tfmt.Printf(\"\\n\")\n\treturn fmt.Errorf(\"The output of the integration doesn't have expected JSON format\")\n}", "func (m *JToken) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateFirst(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateItem(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLast(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNext(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrevious(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRoot(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (jwtParser JWTParser) Validate() JWTParser {\n\tif jwtParser.SigningKeyGetter == nil {\n\t\tjwtParser.SigningKeyGetter = func(*jwt.Token) (interface{}, error) {\n\t\t\treturn jwtParser.Secret, nil\n\t\t}\n\t}\n\tif jwtParser.ValidationKeyGetter == nil {\n\t\tjwtParser.ValidationKeyGetter = func(*jwt.Token) (interface{}, error) {\n\t\t\treturn jwtParser.Secret, nil\n\t\t}\n\t}\n\treturn jwtParser\n}", "func (m LBSKU) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (user *User) Validate() (map[string]interface{}, bool) {\n\n\tif user.FirstName == \"\" {\n\t\treturn utils.Message(false, \"User First name should be on the payload\"), false\n\t}\n\n\tif user.LastName == \"\" {\n\t\treturn utils.Message(false, \"User Last name should be on the payload\"), false\n\t}\n\n\tif user.PhoneNumber == \"\" {\n\t\treturn utils.Message(false, \"User Phone number should be on the payload\"), false\n\t}\n\n\tif user.Age == \"\" {\n\t\treturn utils.Message(false, \"User Age should be on the payload\"), false\n\t}\n\n\tif user.Email == \"\" {\n\t\treturn utils.Message(false, \"User Email should be on the payload\"), false\n\t}\n\n\t//All the required parameters are present\n\treturn utils.Message(true, \"success\"), true\n}", "func (m *V3GatewayIdentifiers) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *BackupWPA) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateApMac(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapAnonymousIdentity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapPassword(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapTypeExt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapUsername(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnabled(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePresharedKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecurity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSsid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateWpaAuthentication(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *TableReporterParamsFilter) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAlerts(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateClusters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateConsistencyGroups(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContentLibraryImages(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContentLibraryVMTemplates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatacenters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDisks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateElfDataStores(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateElfImages(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGlobalAlertRules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHosts(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiConnections(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiLunSnapshots(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiLuns(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiTargets(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNamespaceGroups(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNfsExports(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNics(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNvmfNamespaceSnapshots(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNvmfNamespaces(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNvmfSubsystems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSnapshotPlans(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSystemAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTasks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUsbDevices(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUserAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUsers(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVdses(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVlans(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMEntityFilters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMPlacementGroups(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMTemplates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMVolumes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVms(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *recoveryPayload) Validate() (err error) {\n\tif ut.Token == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"token\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 10 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 10, true))\n\t\t}\n\t}\n\treturn\n}", "func (ut *jSONDataMeta) Validate() (err error) {\n\tif ut.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"id\"))\n\t}\n\tif ut.Station != nil {\n\t\tif err2 := ut.Station.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (m *JobJobFilament) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (np *NamePointer) Validate() (err error) {\n\tvar typeValidation error\n\tswitch np.Key {\n\tcase \"account_pubkey\":\n\t\ttypeValidation = np.validateAccountPubkey()\n\tcase \"oracle_pubkey\":\n\t\ttypeValidation = np.validateOraclePubkey()\n\tcase \"contract_pubkey\":\n\t\ttypeValidation = np.validateContractPubkey()\n\tcase \"channel\":\n\t\ttypeValidation = np.validateChannel()\n\tdefault:\n\t\ttypeValidation = nil\n\t}\n\treturn typeValidation\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func (opts resourceOptions) validate() error {\n\t// Check that the required flags did not get a flag as their value.\n\t// We can safely look for a '-' as the first char as none of the fields accepts it.\n\t// NOTE: We must do this for all the required flags first or we may output the wrong\n\t// error as flags may seem to be missing because Cobra assigned them to another flag.\n\tif strings.HasPrefix(opts.Group, \"-\") {\n\t\treturn fmt.Errorf(groupPresent)\n\t}\n\tif strings.HasPrefix(opts.Version, \"-\") {\n\t\treturn fmt.Errorf(versionPresent)\n\t}\n\tif strings.HasPrefix(opts.Kind, \"-\") {\n\t\treturn fmt.Errorf(kindPresent)\n\t}\n\n\t// We do not check here if the GVK values are empty because that would\n\t// make them mandatory and some plugins may want to set default values.\n\t// Instead, this is checked by resource.GVK.Validate()\n\n\treturn nil\n}", "func (s *Schema) validate(v interface{}) error {\n\tif s.Always != nil {\n\t\tif !*s.Always {\n\t\t\treturn validationError(\"\", \"always fail\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif s.Ref != nil {\n\t\tif err := s.Ref.validate(v); err != nil {\n\t\t\tfinishSchemaContext(err, s.Ref)\n\t\t\tvar refURL string\n\t\t\tif s.URL == s.Ref.URL {\n\t\t\t\trefURL = s.Ref.Ptr\n\t\t\t} else {\n\t\t\t\trefURL = s.Ref.URL + s.Ref.Ptr\n\t\t\t}\n\t\t\treturn validationError(\"$ref\", \"doesn't validate with %q\", refURL).add(err)\n\t\t}\n\n\t\t// All other properties in a \"$ref\" object MUST be ignored\n\t\treturn nil\n\t}\n\n\tif len(s.Types) > 0 {\n\t\tvType := jsonType(v)\n\t\tmatched := false\n\t\tfor _, t := range s.Types {\n\t\t\tif vType == t {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else if t == \"integer\" && vType == \"number\" {\n\t\t\t\tif _, ok := new(big.Int).SetString(fmt.Sprint(v), 10); ok {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"type\", \"expected %s, but got %s\", strings.Join(s.Types, \" or \"), vType)\n\t\t}\n\t}\n\n\tif len(s.Constant) > 0 {\n\t\tif !equals(v, s.Constant[0]) {\n\t\t\tswitch jsonType(s.Constant[0]) {\n\t\t\tcase \"object\", \"array\":\n\t\t\t\treturn validationError(\"const\", \"const failed\")\n\t\t\tdefault:\n\t\t\t\treturn validationError(\"const\", \"value must be %#v\", s.Constant[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(s.Enum) > 0 {\n\t\tmatched := false\n\t\tfor _, item := range s.Enum {\n\t\t\tif equals(v, item) {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"enum\", s.enumError)\n\t\t}\n\t}\n\n\tif s.Not != nil && s.Not.validate(v) == nil {\n\t\treturn validationError(\"not\", \"not failed\")\n\t}\n\n\tfor i, sch := range s.AllOf {\n\t\tif err := sch.validate(v); err != nil {\n\t\t\treturn validationError(\"allOf/\"+strconv.Itoa(i), \"allOf failed\").add(err)\n\t\t}\n\t}\n\n\tif len(s.AnyOf) > 0 {\n\t\tmatched := false\n\t\tvar causes []error\n\t\tfor i, sch := range s.AnyOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"anyOf\", \"anyOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif len(s.OneOf) > 0 {\n\t\tmatched := -1\n\t\tvar causes []error\n\t\tfor i, sch := range s.OneOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tif matched == -1 {\n\t\t\t\t\tmatched = i\n\t\t\t\t} else {\n\t\t\t\t\treturn validationError(\"oneOf\", \"valid against schemas at indexes %d and %d\", matched, i)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif matched == -1 {\n\t\t\treturn validationError(\"oneOf\", \"oneOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif s.If != nil {\n\t\tif s.If.validate(v) == nil {\n\t\t\tif s.Then != nil {\n\t\t\t\tif err := s.Then.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"then\", \"if-then failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif s.Else != nil {\n\t\t\t\tif err := s.Else.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"else\", \"if-else failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch v := v.(type) {\n\tcase map[string]interface{}:\n\t\tif s.MinProperties != -1 && len(v) < s.MinProperties {\n\t\t\treturn validationError(\"minProperties\", \"minimum %d properties allowed, but found %d properties\", s.MinProperties, len(v))\n\t\t}\n\t\tif s.MaxProperties != -1 && len(v) > s.MaxProperties {\n\t\t\treturn validationError(\"maxProperties\", \"maximum %d properties allowed, but found %d properties\", s.MaxProperties, len(v))\n\t\t}\n\t\tif len(s.Required) > 0 {\n\t\t\tvar missing []string\n\t\t\tfor _, pname := range s.Required {\n\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\tmissing = append(missing, strconv.Quote(pname))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(missing) > 0 {\n\t\t\t\treturn validationError(\"required\", \"missing properties: %s\", strings.Join(missing, \", \"))\n\t\t\t}\n\t\t}\n\n\t\tvar additionalProps map[string]struct{}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tadditionalProps = make(map[string]struct{}, len(v))\n\t\t\tfor pname := range v {\n\t\t\t\tadditionalProps[pname] = struct{}{}\n\t\t\t}\n\t\t}\n\n\t\tif len(s.Properties) > 0 {\n\t\t\tfor pname, pschema := range s.Properties {\n\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"properties/\"+escape(pname), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.PropertyNames != nil {\n\t\t\tfor pname := range v {\n\t\t\t\tif err := s.PropertyNames.validate(pname); err != nil {\n\t\t\t\t\treturn addContext(escape(pname), \"propertyNames\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.RegexProperties {\n\t\t\tfor pname := range v {\n\t\t\t\tif !formats.IsRegex(pname) {\n\t\t\t\t\treturn validationError(\"\", \"patternProperty %q is not valid regex\", pname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor pattern, pschema := range s.PatternProperties {\n\t\t\tfor pname, pvalue := range v {\n\t\t\t\tif pattern.MatchString(pname) {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"patternProperties/\"+escape(pattern.String()), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tif _, ok := s.AdditionalProperties.(bool); ok {\n\t\t\t\tif len(additionalProps) != 0 {\n\t\t\t\t\tpnames := make([]string, 0, len(additionalProps))\n\t\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\t\tpnames = append(pnames, strconv.Quote(pname))\n\t\t\t\t\t}\n\t\t\t\t\treturn validationError(\"additionalProperties\", \"additionalProperties %s not allowed\", strings.Join(pnames, \", \"))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tschema := s.AdditionalProperties.(*Schema)\n\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\t\tif err := schema.validate(pvalue); err != nil {\n\t\t\t\t\t\t\treturn addContext(escape(pname), \"additionalProperties\", err)\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\tfor dname, dvalue := range s.Dependencies {\n\t\t\tif _, ok := v[dname]; ok {\n\t\t\t\tswitch dvalue := dvalue.(type) {\n\t\t\t\tcase *Schema:\n\t\t\t\t\tif err := dvalue.validate(v); err != nil {\n\t\t\t\t\t\treturn addContext(\"\", \"dependencies/\"+escape(dname), err)\n\t\t\t\t\t}\n\t\t\t\tcase []string:\n\t\t\t\t\tfor i, pname := range dvalue {\n\t\t\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\t\t\treturn validationError(\"dependencies/\"+escape(dname)+\"/\"+strconv.Itoa(i), \"property %q is required, if %q property exists\", pname, dname)\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\n\tcase []interface{}:\n\t\tif s.MinItems != -1 && len(v) < s.MinItems {\n\t\t\treturn validationError(\"minItems\", \"minimum %d items allowed, but found %d items\", s.MinItems, len(v))\n\t\t}\n\t\tif s.MaxItems != -1 && len(v) > s.MaxItems {\n\t\t\treturn validationError(\"maxItems\", \"maximum %d items allowed, but found %d items\", s.MaxItems, len(v))\n\t\t}\n\t\tif s.UniqueItems {\n\t\t\tfor i := 1; i < len(v); i++ {\n\t\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\t\tif equals(v[i], v[j]) {\n\t\t\t\t\t\treturn validationError(\"uniqueItems\", \"items at index %d and %d are equal\", j, i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswitch items := s.Items.(type) {\n\t\tcase *Schema:\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := items.validate(item); err != nil {\n\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase []*Schema:\n\t\t\tif additionalItems, ok := s.AdditionalItems.(bool); ok {\n\t\t\t\tif !additionalItems && len(v) > len(items) {\n\t\t\t\t\treturn validationError(\"additionalItems\", \"only %d items are allowed, but found %d items\", len(items), len(v))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor i, item := range v {\n\t\t\t\tif i < len(items) {\n\t\t\t\t\tif err := items[i].validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items/\"+strconv.Itoa(i), err)\n\t\t\t\t\t}\n\t\t\t\t} else if sch, ok := s.AdditionalItems.(*Schema); ok {\n\t\t\t\t\tif err := sch.validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"additionalItems\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.Contains != nil {\n\t\t\tmatched := false\n\t\t\tvar causes []error\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := s.Contains.validate(item); err != nil {\n\t\t\t\t\tcauses = append(causes, addContext(strconv.Itoa(i), \"\", err))\n\t\t\t\t} else {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !matched {\n\t\t\t\treturn validationError(\"contains\", \"contains failed\").add(causes...)\n\t\t\t}\n\t\t}\n\n\tcase string:\n\t\tif s.MinLength != -1 || s.MaxLength != -1 {\n\t\t\tlength := utf8.RuneCount([]byte(v))\n\t\t\tif s.MinLength != -1 && length < s.MinLength {\n\t\t\t\treturn validationError(\"minLength\", \"length must be >= %d, but got %d\", s.MinLength, length)\n\t\t\t}\n\t\t\tif s.MaxLength != -1 && length > s.MaxLength {\n\t\t\t\treturn validationError(\"maxLength\", \"length must be <= %d, but got %d\", s.MaxLength, length)\n\t\t\t}\n\t\t}\n\t\tif s.Pattern != nil && !s.Pattern.MatchString(v) {\n\t\t\treturn validationError(\"pattern\", \"does not match pattern %q\", s.Pattern)\n\t\t}\n\t\tif s.Format != nil && !s.Format(v) {\n\t\t\treturn validationError(\"format\", \"%q is not valid %q\", v, s.FormatName)\n\t\t}\n\n\t\tvar content []byte\n\t\tif s.Decoder != nil {\n\t\t\tb, err := s.Decoder(v)\n\t\t\tif err != nil {\n\t\t\t\treturn validationError(\"contentEncoding\", \"%q is not %s encoded\", v, s.ContentEncoding)\n\t\t\t}\n\t\t\tcontent = b\n\t\t}\n\t\tif s.MediaType != nil {\n\t\t\tif s.Decoder == nil {\n\t\t\t\tcontent = []byte(v)\n\t\t\t}\n\t\t\tif err := s.MediaType(content); err != nil {\n\t\t\t\treturn validationError(\"contentMediaType\", \"value is not of mediatype %q\", s.ContentMediaType)\n\t\t\t}\n\t\t}\n\n\tcase json.Number, float64, int, int32, int64:\n\t\tnum, _ := new(big.Float).SetString(fmt.Sprint(v))\n\t\tif s.Minimum != nil && num.Cmp(s.Minimum) < 0 {\n\t\t\treturn validationError(\"minimum\", \"must be >= %v but found %v\", s.Minimum, v)\n\t\t}\n\t\tif s.ExclusiveMinimum != nil && num.Cmp(s.ExclusiveMinimum) <= 0 {\n\t\t\treturn validationError(\"exclusiveMinimum\", \"must be > %v but found %v\", s.ExclusiveMinimum, v)\n\t\t}\n\t\tif s.Maximum != nil && num.Cmp(s.Maximum) > 0 {\n\t\t\treturn validationError(\"maximum\", \"must be <= %v but found %v\", s.Maximum, v)\n\t\t}\n\t\tif s.ExclusiveMaximum != nil && num.Cmp(s.ExclusiveMaximum) >= 0 {\n\t\t\treturn validationError(\"exclusiveMaximum\", \"must be < %v but found %v\", s.ExclusiveMaximum, v)\n\t\t}\n\t\tif s.MultipleOf != nil {\n\t\t\tif q := new(big.Float).Quo(num, s.MultipleOf); !q.IsInt() {\n\t\t\t\treturn validationError(\"multipleOf\", \"%v not multipleOf %v\", v, s.MultipleOf)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e JwtRequirementValidationError) Key() bool { return e.key }", "func (ut *jSONDataMetaSensor) Validate() (err error) {\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.Key == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"key\"))\n\t}\n\tif ut.UnitOfMeasure == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"unitOfMeasure\"))\n\t}\n\tif ut.Ranges == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"ranges\"))\n\t}\n\tfor _, e := range ut.Ranges {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (pk PublicKey) PublicKeyJwk() JWK {\n\tentry, ok := pk[PublicKeyJwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func (m *OpenStackInstanceGroupV4Parameters) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (ut *JSONDataMetaStationFirmware) Validate() (err error) {\n\tif ut.Version == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"version\"))\n\t}\n\tif ut.Build == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"build\"))\n\t}\n\tif ut.Number == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"number\"))\n\t}\n\n\tif ut.Hash == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"hash\"))\n\t}\n\treturn\n}", "func (params Params) Validate() error {\n\tif err := ValidateNicknameParams(params.Nickname); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateDTagParams(params.DTag); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateBioParams(params.Bio); err != nil {\n\t\treturn err\n\t}\n\n\treturn ValidateOracleParams(params.Oracle)\n}" ]
[ "0.6095678", "0.569532", "0.5664185", "0.560481", "0.5594125", "0.55730027", "0.5429043", "0.5408447", "0.52270234", "0.5226582", "0.5189666", "0.5134343", "0.5122218", "0.51015174", "0.5083125", "0.50354177", "0.5019506", "0.50113547", "0.49843422", "0.4983307", "0.49801493", "0.49795255", "0.49658987", "0.49572718", "0.49542546", "0.4943839", "0.49127567", "0.48972034", "0.48912793", "0.48830804", "0.4878149", "0.48752856", "0.48711118", "0.48709372", "0.48699924", "0.48699045", "0.4866638", "0.4864562", "0.48624235", "0.48603466", "0.48594385", "0.4856705", "0.48560938", "0.48380974", "0.48355484", "0.4834099", "0.48242617", "0.4807957", "0.4806879", "0.4797226", "0.4793183", "0.47884116", "0.47846907", "0.477748", "0.47720996", "0.47680563", "0.47642246", "0.4763689", "0.47603038", "0.47591183", "0.4758333", "0.47582296", "0.47475043", "0.47470215", "0.4744737", "0.47419062", "0.47402427", "0.47299382", "0.47266665", "0.47221977", "0.47142267", "0.47133806", "0.47123873", "0.47006726", "0.46863043", "0.46760792", "0.46687737", "0.46657062", "0.46632543", "0.46626806", "0.46474347", "0.46435538", "0.463563", "0.4631561", "0.46314678", "0.4629598", "0.46291798", "0.4626049", "0.46244788", "0.46120036", "0.46079147", "0.46059427", "0.4602289", "0.46019116", "0.460055", "0.4599668", "0.45973384", "0.459603", "0.45947486", "0.4588533" ]
0.7443554
0
ValidateRSAParams checks the RSA parameters of a RSA type of JWK. If a JWK is invalid an error will be returned describing the values that causes the validation to fail.
ValidateRSAParams проверяет параметры RSA ключа JWK типа RSA. Если ключ JWK недействителен, будет возвращаться ошибка, описывающая значения, приводящие к провалу проверки.
func (jwk *Jwk) validateRSAParams() error { if jwk.E < 1 { return errors.New("RSA Required Param (E) is empty/default (<= 0)") } if jwk.N == nil { return errors.New("RSA Required Param (N) is nil") } pOk := jwk.P != nil qOk := jwk.Q != nil dpOk := jwk.Dp != nil dqOk := jwk.Dq != nil qiOk := jwk.Qi != nil othOk := len(jwk.OtherPrimes) > 0 paramsOR := pOk || qOk || dpOk || dqOk || qiOk paramsAnd := pOk && qOk && dpOk && dqOk && qiOk if jwk.D == nil { if (paramsOR || othOk) == true { return errors.New("RSA first/second prime values are present but not Private key value (D)") } } else { if paramsOR != paramsAnd { return errors.New("Not all RSA first/second prime values are present or not present") } else if !paramsOR && othOk { return errors.New("RSA other primes is included but 1st, 2nd prime variables are missing") } else if othOk { for i, oth := range jwk.OtherPrimes { if oth.Coeff == nil { return fmt.Errorf("Other Prime at index=%d, Coeff missing/nil", i) } else if oth.R == nil { return fmt.Errorf("Other Prime at index=%d, R missing/nil", i) } else if oth.Exp == nil { return fmt.Errorf("Other Prime at index=%d, Exp missing/nil", i) } } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (priv *PKCS11PrivateKeyRSA) Validate() error {\n\tpub := priv.key.PubKey.(*rsa.PublicKey)\n\tif pub.E < 2 {\n\t\treturn errMalformedRSAKey\n\t}\n\t// The software implementation actively rejects 'large' public\n\t// exponents, in order to simplify its own implementation.\n\t// Here, instead, we expect the PKCS#11 library to enforce its\n\t// own preferred constraints, whatever they might be.\n\treturn nil\n}", "func buildJWKFromRSA(k *rsa.PublicKey) (*Key, error) {\n\treturn &Key{\n\t\tKeyType: \"RSA\",\n\t\tN: base64.RawURLEncoding.EncodeToString(k.N.Bytes()),\n\t\tE: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(k.E)).Bytes()),\n\t}, nil\n}", "func (jwk *RSAPrivateJWK) PrivateRSA() (*rsa.PrivateKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\tprivateExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExponent := new(big.Int)\n\tprivateExponent = privateExponent.SetBytes(privateExponentBytes)\n\tfirstPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.FirstPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfirstPrimeFactor := new(big.Int)\n\tfirstPrimeFactor = firstPrimeFactor.SetBytes(firstPrimeFactorBytes)\n\tsecondPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeFactor := new(big.Int)\n\tsecondPrimeFactor = secondPrimeFactor.SetBytes(secondPrimeFactorBytes)\n\tprivateExpModFirstPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModFirstPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModFirstPrimeMinusOne := new(big.Int)\n\tprivateExpModFirstPrimeMinusOne = privateExpModFirstPrimeMinusOne.SetBytes(privateExpModFirstPrimeMinusOneBytes)\n\tprivateExpModSecondPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModSecondPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModSecondPrimeMinusOne := new(big.Int)\n\tprivateExpModSecondPrimeMinusOne = privateExpModSecondPrimeMinusOne.SetBytes(privateExpModSecondPrimeMinusOneBytes)\n\tsecondPrimeInverseModFirstPrimeBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeInverseModFirstPrimeBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeInverseModFirstPrime := new(big.Int)\n\tsecondPrimeInverseModFirstPrime = secondPrimeInverseModFirstPrime.SetBytes(secondPrimeInverseModFirstPrimeBytes)\n\trsaPrivateKey := rsa.PrivateKey{\n\t\tPublicKey: rsa.PublicKey{\n\t\t\tN: modulus,\n\t\t\tE: publicExponent,\n\t\t},\n\t\tD: privateExponent,\n\t\tPrimes: []*big.Int{firstPrimeFactor, secondPrimeFactor},\n\t\tPrecomputed: rsa.PrecomputedValues{\n\t\t\tDp: privateExpModFirstPrimeMinusOne,\n\t\t\tDq: privateExpModSecondPrimeMinusOne,\n\t\t\tQinv: secondPrimeInverseModFirstPrime,\n\t\t},\n\t}\n\treturn &rsaPrivateKey, nil\n}", "func (jwk *RSAPublicJWK) PublicRSA() (*rsa.PublicKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\trsaPublicKey := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: publicExponent,\n\t}\n\treturn &rsaPublicKey, nil\n}", "func parseRSA(in []byte) (*rsa.PublicKey, error) {\n\tvar w struct {\n\t\tE *big.Int\n\t\tN *big.Int\n\t\tRest []byte `ssh:\"rest\"`\n\t}\n\tif err := ssh.Unmarshal(in, &w); err != nil {\n\t\treturn nil, errors.Wrap(err, \"error unmarshaling public key\")\n\t}\n\tif w.E.BitLen() > 24 {\n\t\treturn nil, errors.New(\"invalid public key: exponent too large\")\n\t}\n\te := w.E.Int64()\n\tif e < 3 || e&1 == 0 {\n\t\treturn nil, errors.New(\"invalid public key: incorrect exponent\")\n\t}\n\n\tvar key rsa.PublicKey\n\tkey.E = int(e)\n\tkey.N = w.N\n\treturn &key, nil\n}", "func prepareRSAKeys(privRSAPath, pubRSAPath string)(*rsa.PublicKey, *rsa.PrivateKey, error){\n pwd, _ := os.Getwd()\n\n verifyBytes, err := ioutil.ReadFile(pwd+pubRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPublicKey\n }\n\n verifiedKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPubRSAKey\n }\n\n signBytes, err := ioutil.ReadFile(pwd+privRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPrivateKey\n }\n\n signedKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPrivRSAKey\n }\n \n return verifiedKey, signedKey, nil\n}", "func (jwk *Jwk) Validate() error {\n\n\t// If the alg parameter is set, make sure it matches the set JWK Type\n\tif len(jwk.Algorithm) > 0 {\n\t\talgKeyType := GetKeyType(jwk.Algorithm)\n\t\tif algKeyType != jwk.Type {\n\t\t\tfmt.Errorf(\"Jwk Type (kty=%v) doesn't match the algorithm key type (%v)\", jwk.Type, algKeyType)\n\t\t}\n\t}\n\tswitch jwk.Type {\n\tcase KeyTypeRSA:\n\t\tif err := jwk.validateRSAParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeEC:\n\t\tif err := jwk.validateECParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeOct:\n\t\tif err := jwk.validateOctParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tdefault:\n\t\treturn errors.New(\"KeyType (kty) must be EC, RSA or Oct\")\n\t}\n\n\treturn nil\n}", "func ValidateParams(k, m uint8) (*Params, error) {\n\tif k < 1 {\n\t\treturn nil, errors.New(\"k cannot be zero\")\n\t}\n\n\tif m < 1 {\n\t\treturn nil, errors.New(\"m cannot be zero\")\n\t}\n\n\tif k+m > 255 {\n\t\treturn nil, errors.New(\"(k + m) cannot be bigger than Galois field GF(2^8) - 1\")\n\t}\n\n\treturn &Params{\n\t\tK: k,\n\t\tM: m,\n\t}, nil\n}", "func parseRSAKey(key ssh.PublicKey) (*rsa.PublicKey, error) {\n\tvar sshWire struct {\n\t\tName string\n\t\tE *big.Int\n\t\tN *big.Int\n\t}\n\tif err := ssh.Unmarshal(key.Marshal(), &sshWire); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal key %v: %v\", key.Type(), err)\n\t}\n\treturn &rsa.PublicKey{N: sshWire.N, E: int(sshWire.E.Int64())}, nil\n}", "func GenRSAKey(len int, password string, kmPubFile, kmPrivFile, bpmPubFile, bpmPrivFile *os.File) error {\n\tif len == rsaLen2048 || len == rsaLen3072 {\n\t\tkey, err := rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, kmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), kmPubFile); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tkey, err = rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, bpmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), bpmPubFile); err != nil {\n\t\t\treturn err\n\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"RSA key length must be 2048 or 3084 Bits, but length is: %d\", len)\n}", "func (j *JWKS) generateRSAKey() (crypto.PrivateKey, error) {\n\tif j.bits == 0 {\n\t\tj.bits = 2048\n\t}\n\tif j.bits < 2048 {\n\t\treturn nil, errors.Errorf(`jwks: key size must be at least 2048 bit for algorithm`)\n\t}\n\tkey, err := rsa.GenerateKey(rand.Reader, j.bits)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"jwks: unable to generate RSA key\")\n\t}\n\n\treturn key, nil\n}", "func PrivateKeyValidate(priv *rsa.PrivateKey,) error", "func (jwk *Jwk) validateECParams() error {\n\tif jwk.X == nil {\n\t\treturn errors.New(\"EC Required Param (X) is nil\")\n\t}\n\tif jwk.Y == nil {\n\t\treturn errors.New(\"EC Required Param (Y) is nil\")\n\t}\n\tif jwk.Curve == nil {\n\t\treturn errors.New(\"EC Required Param (Crv) is nil\")\n\t}\n\treturn nil\n}", "func (p Params) Validate() error {\n\tif err := validateTokenCourse(p.TokenCourse); err != nil {\n\t\treturn err\n\t}\n\tif err := validateSubscriptionPrice(p.SubscriptionPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateVPNGBPrice(p.VPNGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateStorageGBPrice(p.StorageGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseVPNGb(p.BaseVPNGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseStorageGb(p.BaseStorageGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateCourseChangeSigners(p.CourseChangeSigners); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewRSA(encoding encodingType) (*RSA, error) {\n\tif encoding == \"\" {\n\t\tencoding = Base64\n\t}\n\treturn &RSA{Encoding: encoding}, nil\n}", "func (me *XsdGoPkgHasElem_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RSAKeyValue; 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.RSAKeyValue.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 (v *PublicParamsManager) Validate() error {\n\tpp := v.PublicParams()\n\tif pp == nil {\n\t\treturn errors.New(\"public parameters not set\")\n\t}\n\treturn pp.Validate()\n}", "func UnmarshalParams(d []byte) (pubKey *signkeys.PublicKey, pubParams *jjm.BlindingParamClient, privateParams []byte, canReissue bool, err error) {\n\tp := new(Params)\n\t_, err = asn1.Unmarshal(d, p)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\tpubkey, err := new(signkeys.PublicKey).Unmarshal(p.PublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\treturn pubkey, &p.PublicParams, p.PrivateParams, p.CanReissue, nil\n}", "func FromRSAPrivateKey(pk *rsa.PrivateKey) *RSAParameters {\n\tvar n, e, d, p, q, dp, dq, qinv string\n\n\tn = toBase64(pk.PublicKey.N)\n\te = toBase64(pk.PublicKey.E)\n\td = toBase64(pk.D)\n\n\tfor i, prime := range pk.Primes {\n\t\tif i == 0 {\n\t\t\tp = toBase64(prime)\n\t\t} else if i == 1 {\n\t\t\tq = toBase64(prime)\n\t\t} else {\n\t\t\tfmt.Println(\"ERROR: more than 2 primes\")\n\t\t}\n\t}\n\n\tdp = toBase64(pk.Precomputed.Dp)\n\tdq = toBase64(pk.Precomputed.Dq)\n\tqinv = toBase64(pk.Precomputed.Qinv)\n\n\tmsRSA := &RSAParameters{\n\t\tModulus: n,\n\t\tExponent: e,\n\t\tD: d,\n\t\tP: p,\n\t\tQ: q,\n\t\tDP: dp,\n\t\tDQ: dq,\n\t\tInverseQ: qinv,\n\t}\n\n\treturn msRSA\n}", "func (jwk *Jwk) validateOctParams() error {\n\tif len(jwk.KeyValue) < 1 {\n\t\treturn errors.New(\"Oct Required Param KeyValue (k) is empty\")\n\t}\n\n\treturn nil\n}", "func (me *XsdGoPkgHasElems_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_RSAKeyValue; 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\tfor _, x := range me.RSAKeyValues {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\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 NewGojwtRSA(nameserver, headerkey, privKeyPath, pubKeyPath, lenbytes string, hours time.Duration) (*Gojwt, error){\n var verifiedRSAKey *rsa.PublicKey\n var signedRSAKey *rsa.PrivateKey\n \n if privKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPrivateKey\n } else if pubKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPublicKey\n }\n verifiedRSAKey, signedRSAKey, err := prepareRSAKeys(privKeyPath, pubKeyPath)\n if err != nil{\n return nil, err\n }\n return &Gojwt{\n pubKeyPath: pubKeyPath,\n privKeyPath: privKeyPath,\n pubRSAKey: verifiedRSAKey,\n privRSAKey: signedRSAKey,\n headerKeyAuth: headerkey,\n numHoursDuration: hours,\n method: \"RSA\",\n lenBytes: lenbytes,\n nameServer: nameserver}, nil\n}", "func InitRSAKeys() {\n\n\tsignBytes, err := ioutil.ReadFile(privKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tsignKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(pubKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n}", "func RSAToPublicJWK(publicKey *rsa.PublicKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPublicJWK, error) {\n\tpublicX509DER, err := x509.MarshalPKIXPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublicX509DERBase64 := base64.RawStdEncoding.EncodeToString(publicX509DER)\n\tpublicThumbprint := sha1.Sum(publicX509DER)\n\tpublicThumbprintBase64 := base64.RawURLEncoding.EncodeToString(publicThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(publicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(publicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tpublicJWK := RSAPublicJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{publicX509DERBase64},\n\t\t\tThumbprintBase64: publicThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t}\n\treturn &publicJWK, nil\n}", "func GenerateRSAKey(bits int) (privateKey, publicKey []byte, err error) {\n\tprvKey, err := rsa.GenerateKey(rand.Reader, bits)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpkixb, err := x509.MarshalPKIXPublicKey(&prvKey.PublicKey)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tprivateKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(prvKey),\n\t})\n\n\tpublicKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: pkixb,\n\t})\n\n\treturn\n}", "func (pr *PasswordRecord) GetKeyRSA(password string) (key rsa.PrivateKey, err error) {\n\tif pr.Type != RSARecord {\n\t\treturn key, errors.New(\"Invalid function for record type\")\n\t}\n\n\terr = pr.ValidatePassword(password)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpassKey, err := derivePasswordKey(password, pr.KeySalt)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaExponentPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAExp, pr.RSAKey.RSAExpIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaExponent, err := padding.RemovePadding(rsaExponentPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimePPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeP, pr.RSAKey.RSAPrimePIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeP, err := padding.RemovePadding(rsaPrimePPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimeQPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeQ, pr.RSAKey.RSAPrimeQIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeQ, err := padding.RemovePadding(rsaPrimeQPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkey.PublicKey = pr.RSAKey.RSAPublic\n\tkey.D = big.NewInt(0).SetBytes(rsaExponent)\n\tkey.Primes = []*big.Int{big.NewInt(0), big.NewInt(0)}\n\tkey.Primes[0].SetBytes(rsaPrimeP)\n\tkey.Primes[1].SetBytes(rsaPrimeQ)\n\n\terr = key.Validate()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func GenerateRSA() (*rsa.PrivateKey, rsa.PublicKey) {\n\treader := rand.Reader\n\tbitSize := 2048\n\tkey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error generating key: %v\", err)\n\t\t// TODO: handle error\n\t}\n\treturn key, key.PublicKey\n}", "func (g *Gossiper) RSAVerifyPMSignature(msg utils.PrivateMessage) bool {\n\thash := utils.HASH_ALGO.New()\n\n\tbytes, e := json.Marshal(msg)\n\tutils.HandleError(e)\n\thash.Write(bytes)\n\thashed := hash.Sum(nil)\n\n\tpubKeyBytes, e := hex.DecodeString(msg.Origin)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\n\te = rsa.VerifyPKCS1v15(pubKey, utils.HASH_ALGO, hashed, msg.Signature)\n\tutils.HandleError(e)\n\tif e == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func RSAToPrivateJWK(privateKey *rsa.PrivateKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPrivateJWK, error) {\n\tprivateX509DER := x509.MarshalPKCS1PrivateKey(privateKey)\n\tprivateX509DERBase64 := base64.RawStdEncoding.EncodeToString(privateX509DER)\n\tprivateThumbprint := sha1.Sum(privateX509DER)\n\tprivateThumbprintBase64 := base64.RawURLEncoding.EncodeToString(privateThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(privateKey.PublicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(privateKey.PublicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tprivateExponentBase64 := base64.RawURLEncoding.EncodeToString(privateKey.D.Bytes())\n\tfirstPrimeFactor := privateKey.Primes[0]\n\tfirstPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(firstPrimeFactor.Bytes())\n\tsecondPrimeFactor := privateKey.Primes[1]\n\tsecondPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(secondPrimeFactor.Bytes())\n\t// precomputed\n\tprivateExpModFirstPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dp.Bytes())\n\tprivateExpModSecondPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dq.Bytes())\n\tsecondPrimeInverseModFirstPrimeBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Qinv.Bytes())\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tprivateJWK := RSAPrivateJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{privateX509DERBase64},\n\t\t\tThumbprintBase64: privateThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t\tPrivateExponentBase64: privateExponentBase64,\n\t\tFirstPrimeFactorBase64: firstPrimeFactorBase64,\n\t\tSecondPrimeFactorBase64: secondPrimeFactorBase64,\n\t\t// precomputed\n\t\tPrivateExpModFirstPrimeMinusOneBase64: privateExpModFirstPrimeMinusOneBase64,\n\t\tPrivateExpModSecondPrimeMinusOneBase64: privateExpModSecondPrimeMinusOneBase64,\n\t\tSecondPrimeInverseModFirstPrimeBase64: secondPrimeInverseModFirstPrimeBase64,\n\t}\n\treturn &privateJWK, nil\n}", "func validatePubKey(publicKey string) error {\n\tpk, err := hex.DecodeString(publicKey)\n\tif err != nil {\n\t\tlog.Debugf(\"validatePubKey: decode hex string \"+\n\t\t\t\"failed for '%v': %v\", publicKey, err)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\tvar emptyPK [identity.PublicKeySize]byte\n\tswitch {\n\tcase len(pk) != len(emptyPK):\n\t\tlog.Debugf(\"validatePubKey: invalid size: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\tcase bytes.Equal(pk, emptyPK[:]):\n\t\tlog.Debugf(\"validatePubKey: key is empty: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\treturn nil\n}", "func (session *Session) GenerateRSAKeyPair(tokenLabel string, tokenPersistent bool, expDate time.Time, bits int) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {\n\tif session == nil || session.Ctx == nil {\n\t\treturn 0, 0, fmt.Errorf(\"session not initialized\")\n\t}\n\ttoday := time.Now()\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{1, 0, 1}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, bits),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),\n\t}\n\n\tpubKey, privKey, err := session.Ctx.GenerateKeyPair(\n\t\tsession.Handle,\n\t\t[]*pkcs11.Mechanism{\n\t\t\tpkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil),\n\t\t},\n\t\tpublicKeyTemplate,\n\t\tprivateKeyTemplate,\n\t)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn pubKey, privKey, nil\n}", "func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) {\n\tk.verifyOnce.Do(k.verifyInit)\n\n\tkontrolKey := k.KontrolKey()\n\n\tif kontrolKey == nil {\n\t\tpanic(\"kontrol key is not set in config\")\n\t}\n\n\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\treturn nil, errors.New(\"invalid signing method\")\n\t}\n\n\tclaims, ok := token.Claims.(*kitekey.KiteClaims)\n\tif !ok {\n\t\treturn nil, errors.New(\"token does not have valid claims\")\n\t}\n\n\tif claims.Issuer != k.Config.KontrolUser {\n\t\treturn nil, fmt.Errorf(\"issuer is not trusted: %s\", claims.Issuer)\n\t}\n\n\treturn kontrolKey, nil\n}", "func (m *PorositySimulationParameters) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBeamDiameter(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryHeight(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryLength(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryWidth(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHatchSpacingValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHeaterTemperature(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLaserWattageValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerRotationAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerThicknessValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMeshLayersPerLayer(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScanSpeedValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSlicingStripeWidthValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartingLayerAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p Params) Validate() error {\n\tif err := validateActiveParam(p.Active); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDelegatorParams(p.DelegatorDistributionSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateLPParams(p.LiquidityProviderSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateMoneyMarketParams(p.MoneyMarkets); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateCheckLtvIndexCount(p.CheckLtvIndexCount)\n}", "func NewRSAPEM() ([]byte, error) {\n\tprivate, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = private.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn marshalToPEM(private)\n}", "func generateRSAKey(p *pkcs11.Ctx,\n\tsession pkcs11.SessionHandle,\n\tgun data.GUN,\n\tpassRetriever notary.PassRetriever,\n\trole data.RoleName,\n) (*LunaPrivateKey, error) {\n\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, 2048),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{0x01, 0x00, 0x01}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, fmt.Sprintf(\"notary-%s;;%s;public\", gun, role)),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, fmt.Sprintf(\"notary-%s;;%s;private\", gun, role)),\n\t}\n\n\tmechanism := []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil)}\n\tpubObjectHandle, privObjectHandle, err := p.GenerateKeyPair(session, mechanism, publicKeyTemplate, privateKeyTemplate)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to generate key pair: %s\", err.Error())\n\t\treturn nil, fmt.Errorf(\"Failed to generate key pair: %v\", err)\n\t}\n\n\tpubKey, _, err := getRSAKeyFromObjectHandle(p, session, pubObjectHandle)\n\tif err != nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, err\n\t}\n\tpubID := []byte(pubKey.ID())\n\terr = setIDForObjectHandles(p, session, pubID, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivateKey := NewLunaPrivateKey(pubID, pubKey, data.RSAPKCS1v15Signature, passRetriever)\n\tif privateKey == nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, errors.New(\"could not initialize new LunaPrivateKey\")\n\t}\n\n\tid := pubKey.ID()\n\n\tcertObjectHandle, err := createCertificate(p, session, gun, role, id, privateKey)\n\tif err != nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, fmt.Errorf(\"Error creating certificate: %v\", err)\n\t}\n\n\tlogrus.Debugf(\"Setting keyID: %s\", id)\n\tprivateKey.keyID = []byte(id)\n\n\tobjectHandles := []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle, certObjectHandle}\n\n\terr = setIDsAndLabels(p, session, gun, role, id, []string{\"public\", \"private\", \"cert\"}, objectHandles)\n\tif err != nil {\n\t\tdestroyObjects(p, session, objectHandles)\n\t\treturn nil, err\n\t}\n\n\treturn privateKey, nil\n}", "func (params Params) Validate() error {\n\tif err := ValidateNicknameParams(params.Nickname); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateDTagParams(params.DTag); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateBioParams(params.Bio); err != nil {\n\t\treturn err\n\t}\n\n\treturn ValidateOracleParams(params.Oracle)\n}", "func GenerateRSAKeyPair(opts GenerateRSAOptions) (*RSAKeyPair, error) {\n\t//creates the private key\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, opts.Bits)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error generating private key: %s\\n\", err)\n\t}\n\n\t//validates the private key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error validating private key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for private key\n\tprivateKeyBlock := pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t}\n\n\t//check to see if we are applying encryption to this key\n\tif opts.Encryption != nil {\n\t\t//check to make sure we have a password specified\n\t\tpass := strings.TrimSpace(opts.Encryption.Password)\n\t\tif pass == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"need a password!\")\n\t\t}\n\t\t//check to make sure we're using a supported PEMCipher\n\t\tencCipher := opts.Encryption.PEMCipher\n\t\tif encCipher != x509.PEMCipherDES &&\n\t\t\tencCipher != x509.PEMCipher3DES &&\n\t\t\tencCipher != x509.PEMCipherAES128 &&\n\t\t\tencCipher != x509.PEMCipherAES192 &&\n\t\t\tencCipher != x509.PEMCipherAES256 {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"invalid PEMCipher\")\n\t\t}\n\t\t//encrypt the private key block\n\t\tencBlock, err := x509.EncryptPEMBlock(rand.Reader, \"RSA PRIVATE KEY\", privateKeyBlock.Bytes, []byte(pass), encCipher)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encrypting pirvate key: %s\\n\", err)\n\t\t}\n\t\t//replaces the starting one with the one we encrypted\n\t\tprivateKeyBlock = *encBlock\n\t}\n\n\t// serializes the public key in a DER-encoded PKIX format (see docs for more)\n\tpublicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up public key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for public key\n\tpublicKeyBlock := pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tHeaders: nil,\n\t\tBytes: publicKeyBytes,\n\t}\n\n\t//returns the created key pair\n\treturn &RSAKeyPair{\n\t\tPrivateKey: string(pem.EncodeToMemory(&privateKeyBlock)),\n\t\tPublicKey: string(pem.EncodeToMemory(&publicKeyBlock)),\n\t}, nil\n}", "func ValidateOracleParams(i interface{}) error {\n\tparams, isOracleParams := i.(OracleParams)\n\tif !isOracleParams {\n\t\treturn fmt.Errorf(\"invalid parameters type: %s\", i)\n\t}\n\n\tif params.AskCount < params.MinCount {\n\t\treturn fmt.Errorf(\"invalid ask count: %d, min count: %d\", params.AskCount, params.MinCount)\n\t}\n\n\tif params.MinCount <= 0 {\n\t\treturn fmt.Errorf(\"invalid min count: %d\", params.MinCount)\n\t}\n\n\tif params.PrepareGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid prepare gas: %d\", params.PrepareGas)\n\t}\n\n\tif params.ExecuteGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid execute gas: %d\", params.ExecuteGas)\n\t}\n\n\terr := params.FeeAmount.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func LoadRSAKey() interfaces.RSAKey {\n\tdeferFunc := logger.LogWithDefer(\"Load RSA keys...\")\n\tdefer deferFunc()\n\n\tsignBytes, err := ioutil.ReadFile(\"config/key/private.key\")\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tprivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error())\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(\"config/key/public.pem\")\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tpublicKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error())\n\t}\n\n\treturn &key{\n\t\tprivate: privateKey, public: publicKey,\n\t}\n}", "func (p Params) Validate() error {\n\tif err := validateActiveParam(p.Active); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDelegatorParams(p.DelegatorDistributionSchedules); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateLPParams(p.LiquidityProviderSchedules)\n}", "func ParsePublicKey(data []byte) (SignatureValidator, error) {\r\n\ttmpKey, err := x509.ParsePKIXPublicKey(data)\r\n\trsaKey, ok := tmpKey.(*rsa.PublicKey)\r\n\tif err != nil || !ok {\r\n\t\treturn nil, errors.New(\"invalid key type, only RSA is supported\")\r\n\t}\r\n\treturn &rsaPublicKey{rsaKey}, nil\r\n}", "func CheckParams(params Setting, passwordType string) bool {\n\n\tminLen := params.MinLength\n\tminSpecials := params.MinSpecialCharacters\n\tminDigits := params.MinDigits\n\tminLowers := params.MinLowercase\n\tminUppers := params.MinUppercase\n\n\tif minLen < AbsoluteMinLen ||\n\t\tminDigits < config[passwordType].MinDigits ||\n\t\tminLowers < config[passwordType].MinLowercase ||\n\t\tminUppers < config[passwordType].MinUppercase ||\n\t\tminSpecials < config[passwordType].MinSpecialCharacters {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func parsePublicKey(pemBytes []byte) (SignatureValidator, error) {\r\n\tgob.Register(rsaPrivateKey{})\r\n\tblock, _ := pem.Decode(pemBytes)\r\n\tif block == nil {\r\n\t\treturn nil, errors.New(\"no key found\")\r\n\t}\r\n\r\n\tswitch block.Type {\r\n\tcase \"PUBLIC KEY\":\r\n\t\treturn ParsePublicKey(block.Bytes)\r\n\tdefault:\r\n\t\treturn nil, fmt.Errorf(\"unsupported key block type %q\", block.Type)\r\n\t}\r\n}", "func ValidateParameters(r *Request) {\n\tif r.ParamsFilled() {\n\t\tv := validator{errors: []string{}}\n\t\tv.validateAny(reflect.ValueOf(r.Params), \"\")\n\n\t\tif count := len(v.errors); count > 0 {\n\t\t\tformat := \"%d validation errors:\\n- %s\"\n\t\t\tmsg := fmt.Sprintf(format, count, strings.Join(v.errors, \"\\n- \"))\n\t\t\tr.Error = apierr.New(\"InvalidParameter\", msg, nil)\n\t\t}\n\t}\n}", "func ValidatePublicKey(k *ecdsa.PublicKey) bool {\n\treturn k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0\n}", "func Validate(accessToken string, configURL string, c *cache.Cache) (bool, error) {\n\n\tjp := new(jwtgo.Parser)\n\tjp.ValidMethods = []string{\n\t\t\"RS256\", \"RS384\", \"RS512\", \"ES256\", \"ES384\", \"ES512\",\n\t\t\"RS3256\", \"RS3384\", \"RS3512\", \"ES3256\", \"ES3384\", \"ES3512\",\n\t}\n\n\t// Validate token against issuer\n\ttt, _ := jwtgo.Parse(accessToken, func(token *jwtgo.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\t// check if publicKey already in cache\n\t\tpub, found := c.Get(\"key\")\n\t\tif found {\n\t\t\t//fmt.Println(\"Using cached pubKey\")\n\t\t\treturn pub, nil\n\t\t}\n\n\t\t// Retrieve Issuer metadata from discovery endpoint\n\t\td := openid.DiscoveryDoc{}\n\n\t\treq, err := http.NewRequest(http.MethodGet, configURL, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclnt := http.Client{}\n\n\t\tr, err := clnt.Do(req)\n\t\tif err != nil {\n\t\t\tclnt.CloseIdleConnections()\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer r.Body.Close()\n\n\t\tif r.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(r.Status)\n\t\t}\n\t\tdec := json.NewDecoder(r.Body)\n\t\tif err = dec.Decode(&d); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Get Public Key from JWK URI\n\t\tresp, err := clnt.Get(d.JwksURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(resp.Status)\n\t\t}\n\n\t\tvar jwk openid.JWKS\n\t\tif err = json.NewDecoder(resp.Body).Decode(&jwk); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar kk crypto.PublicKey\n\t\tfor _, key := range jwk.Keys {\n\t\t\tkk, err = key.DecodePublicKey()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Return the rsa public key for the token validation\n\t\tpubKey := kk.(*rsa.PublicKey)\n\n\t\tc.Set(\"key\", pubKey, cache.DefaultExpiration)\n\n\t\treturn pubKey, nil\n\n\t})\n\n\t//fmt.Println(tt)\n\treturn tt.Valid, nil\n}", "func GetRSAKeys(authserver string) (map[string]rsa.PublicKey, error) {\n\tjwksURI, err := getJwksURI(authserver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting jwks_uri failed: %w\", err)\n\t}\n\n\tkeyList := jwks{}\n\terr = getJSON(jwksURI, &keyList)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching jwks failed: %w\", err)\n\t}\n\n\tkeys := make(map[string]rsa.PublicKey)\n\n\tfor _, key := range keyList.Keys {\n\n\t\tif key.Kty == \"RSA\" {\n\n\t\t\te, err := fromB64(key.E)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from E: %w\", err)\n\t\t\t}\n\t\t\tn, err := fromB64(key.N)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from N: %w\", err)\n\t\t\t}\n\n\t\t\tkeys[key.Kid] = rsa.PublicKey{N: &n, E: int(e.Int64())}\n\n\t\t}\n\t}\n\n\treturn keys, nil\n\n}", "func Validate(params Params) (err error) {\n\tif params.Length <= 0 {\n\t\treturn errors.New(\"Length must be more than 0\")\n\t}\n\tif params.Square <= 0 {\n\t\treturn errors.New(\"Square must be more than 0\")\n\t}\n\treturn nil\n}", "func ValidatePublicKeyRecord(k u.Key, val []byte) error {\n\tkeyparts := bytes.Split([]byte(k), []byte(\"/\"))\n\tif len(keyparts) < 3 {\n\t\treturn errors.New(\"invalid key\")\n\t}\n\n\tpkh := u.Hash(val)\n\tif !bytes.Equal(keyparts[2], pkh) {\n\t\treturn errors.New(\"public key does not match storage key\")\n\t}\n\treturn nil\n}", "func (_WyvernExchange *WyvernExchangeCaller) ValidateOrderParameters(opts *bind.CallOpts, addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _WyvernExchange.contract.Call(opts, out, \"validateOrderParameters_\", addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n\treturn *ret0, err\n}", "func ECDH_PUBLIC_KEY_VALIDATE(W []byte) int {\n\tWP := ECP_fromBytes(W)\n\tres := 0\n\n\tr := NewBIGints(CURVE_Order)\n\n\tif WP.Is_infinity() {\n\t\tres = INVALID_PUBLIC_KEY\n\t}\n\tif res == 0 {\n\n\t\tq := NewBIGints(Modulus)\n\t\tnb := q.nbits()\n\t\tk := NewBIGint(1)\n\t\tk.shl(uint((nb + 4) / 2))\n\t\tk.add(q)\n\t\tk.div(r)\n\n\t\tfor k.parity() == 0 {\n\t\t\tk.shr(1)\n\t\t\tWP.dbl()\n\t\t}\n\n\t\tif !k.isunity() {\n\t\t\tWP = WP.mul(k)\n\t\t}\n\t\tif WP.Is_infinity() {\n\t\t\tres = INVALID_PUBLIC_KEY\n\t\t}\n\n\t}\n\treturn res\n}", "func (m *PaymentServiceItemParam) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOrigin(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentServiceItemID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateParams(paramSpec []GeneratorParam, params map[string]interface{}) error {\n\tallErrs := []error{}\n\tfor ix := range paramSpec {\n\t\tif paramSpec[ix].Required {\n\t\t\tvalue, found := params[paramSpec[ix].Name]\n\t\t\tif !found || IsZero(value) {\n\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"Parameter: %s is required\", paramSpec[ix].Name))\n\t\t\t}\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}", "func RSAVerify(key *rsa.PublicKey, hash crypto.Hash, data, sig []byte) (\n\terr error) {\n\n\th := hash.New()\n\tif _, err := h.Write(data); err != nil {\n\t\treturn err\n\t}\n\treturn rsa.VerifyPKCS1v15(key, hash, h.Sum(nil), sig)\n}", "func rsaEncrypt(pemPubKey, nonce, password []byte) ([]byte, error) {\n\tpubKeyBlock, rest := pem.Decode(pemPubKey)\n\tif len(rest) > 0 {\n\t\treturn nil, fmt.Errorf(\"trailing bytes in public key: %#v\", rest)\n\t}\n\n\tpublicKey, err := x509.ParsePKCS1PublicKey(pubKeyBlock.Bytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse PKCS#1 public key: %w\", err)\n\t}\n\n\treturn rsa.EncryptOAEP(sha1.New(), rand.Reader, publicKey, append(nonce, []byte(password)...), []byte{})\n}", "func (m *WasmParams) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func parseAndCheckParameters(params ...Parameter) (*parameters, error) {\n\tparameters := parameters{\n\t\tlogLevel: zerolog.GlobalLevel(),\n\t}\n\tfor _, p := range params {\n\t\tif params != nil {\n\t\t\tp.apply(&parameters)\n\t\t}\n\t}\n\n\tif parameters.monitor == nil {\n\t\t// Use no-op monitor.\n\t\tparameters.monitor = &noopMonitor{}\n\t}\n\tif parameters.signer == nil {\n\t\treturn nil, errors.New(\"no signer specified\")\n\t}\n\tif parameters.lister == nil {\n\t\treturn nil, errors.New(\"no lister specified\")\n\t}\n\tif parameters.process == nil {\n\t\treturn nil, errors.New(\"no process specified\")\n\t}\n\tif parameters.walletManager == nil {\n\t\treturn nil, errors.New(\"no wallet manager specified\")\n\t}\n\tif parameters.accountManager == nil {\n\t\treturn nil, errors.New(\"no account manager specified\")\n\t}\n\tif parameters.peers == nil {\n\t\treturn nil, errors.New(\"no peers specified\")\n\t}\n\tif parameters.name == \"\" {\n\t\treturn nil, errors.New(\"no name specified\")\n\t}\n\tif parameters.id == 0 {\n\t\treturn nil, errors.New(\"no ID specified\")\n\t}\n\tif parameters.listenAddress == \"\" {\n\t\treturn nil, errors.New(\"no listen address specified\")\n\t}\n\tif len(parameters.serverCert) == 0 {\n\t\treturn nil, errors.New(\"no server certificate specified\")\n\t}\n\tif len(parameters.serverKey) == 0 {\n\t\treturn nil, errors.New(\"no server key specified\")\n\t}\n\n\treturn &parameters, nil\n}", "func CheckAlgorithmIDParamNotNULL(algorithmIdentifier []byte, requiredAlgoID asn1.ObjectIdentifier) error {\n\texpectedAlgoIDBytes, ok := RSAAlgorithmIDToDER[requiredAlgoID.String()]\n\tif !ok {\n\t\treturn errors.New(\"error algorithmID to check is not RSA\")\n\t}\n\n\talgorithmSequence := cryptobyte.String(algorithmIdentifier)\n\n\t// byte comparison of algorithm sequence and checking no trailing data is present\n\tvar algorithmBytes []byte\n\tif algorithmSequence.ReadBytes(&algorithmBytes, len(expectedAlgoIDBytes)) {\n\t\tif bytes.Compare(algorithmBytes, expectedAlgoIDBytes) == 0 && algorithmSequence.Empty() {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// re-parse to get an error message detailing what did not match in the byte comparison\n\talgorithmSequence = cryptobyte.String(algorithmIdentifier)\n\tvar algorithm cryptobyte.String\n\tif !algorithmSequence.ReadASN1(&algorithm, cryptobyte_asn1.SEQUENCE) {\n\t\treturn errors.New(\"error reading algorithm\")\n\t}\n\n\tencryptionOID := asn1.ObjectIdentifier{}\n\tif !algorithm.ReadASN1ObjectIdentifier(&encryptionOID) {\n\t\treturn errors.New(\"error reading algorithm OID\")\n\t}\n\n\tif !encryptionOID.Equal(requiredAlgoID) {\n\t\treturn fmt.Errorf(\"algorithm OID is not equal to %s\", requiredAlgoID.String())\n\t}\n\n\tif algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier missing required NULL parameter\")\n\t}\n\n\tvar nullValue cryptobyte.String\n\tif !algorithm.ReadASN1(&nullValue, cryptobyte_asn1.NULL) {\n\t\treturn errors.New(\"RSA algorithm identifier with non-NULL parameter\")\n\t}\n\n\tif len(nullValue) != 0 {\n\t\treturn errors.New(\"RSA algorithm identifier with NULL parameter containing data\")\n\t}\n\n\t// ensure algorithm is empty and no trailing data is present\n\tif !algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier with trailing data\")\n\t}\n\n\treturn errors.New(\"RSA algorithm appears correct, but didn't match byte-wise comparison\")\n}", "func validateParams(method model.Method, params map[string]interface{}) (bool, error) {\n\tvar notSpecified []model.Parameter\n\tfor _, param := range method.Parameters {\n\t\tvalue := params[param.Name]\n\t\tif param.Required {\n\t\t\tif value != \"\" && value != nil{\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnotSpecified = append(notSpecified, param)\n\t\t\t}\n\t\t} else {\n\t\t\tif value != \"\" && value != nil {\n\t\t\t\t// optional parameters check\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(notSpecified) != 0 {\n\t\tvar paramStr string = \"\"\n\t\tfor _, param := range notSpecified {\n\t\t\tparamStr += fmt.Sprintf(\"'%s', \", param.Name)\n\t\t}\n\t\tmsg := fmt.Sprintf(\"Required parameters are not provided for '%s' method. Please specify: %s\", method.Name, paramStr[:len(paramStr) - 2])\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn false, errors.New(msg)\n\t}\n\treturn true, nil\n}", "func validateServiceParameters(parameters []*Service_Parameter, data *types.Struct) error {\n\tvar errs xerrors.Errors\n\n\tfor _, p := range parameters {\n\t\tvar value *types.Value\n\t\tif data != nil && data.Fields != nil {\n\t\t\tvalue = data.Fields[p.Key]\n\t\t}\n\t\tif err := p.Validate(value); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn errs.ErrorOrNil()\n}", "func GetRSAKey(size int) (data.PrivateKey, error) {\n\traw := map[int][]byte{\n\t\t1024: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDJ8BO2/HOHLJgrb3srafbNRUD8r0SGNJFi5h7t4vxZ4F5oBW/4\nO2/aZmdToinyuCm0eGguK77HAsTfSHqDUoEfuInNg7pPk4F6xa4feQzEeG6P0YaL\n+VbApUdCHLBE0tVZg1SCW97+27wqIM4Cl1Tcsbb+aXfgMaOFGxlyga+a6wIDAQAB\nAoGBAKDWLH2kGMfjBtghlLKBVWcs75PSbPuPRvTEYIIMNf3HrKmhGwtVG8ORqF5+\nXHbLo7vv4tpTUUHkvLUyXxHVVq1oX+QqiRwTRm+ROF0/T6LlrWvTzvowTKtkRbsm\nmqIYEbc+fBZ/7gEeW2ycCfE7HWgxNGvbUsK4LNa1ozJbrVEBAkEA8ML0mXyxq+cX\nCwWvdXscN9vopLG/y+LKsvlKckoI/Hc0HjPyraq5Docwl2trZEmkvct1EcN8VvcV\nvCtVsrAfwQJBANa4EBPfcIH2NKYHxt9cP00n74dVSHpwJYjBnbec5RCzn5UTbqd2\ni62AkQREYhHZAryvBVE81JAFW3nqI9ZTpasCQBqEPlBRTXgzYXRTUfnMb1UvoTXS\nZd9cwRppHmvr/4Ve05yn+AhsjyksdouWxyMqgTxuFhy4vQ8O85Pf6fZeM4ECQCPp\nWv8H4thJplqSeGeJFSlBYaVf1SRtN0ndIBTCj+kwMaOMQXiOsiPNmfN9wG09v2Bx\nYVFJ/D8uNjN4vo+tI8sCQFbtF+Qkj4uSFDZGMESF6MOgsGt1R1iCpvpMSr9h9V02\nLPXyS3ozB7Deq26pEiCrFtHxw2Pb7RJO6GEqH7Dg4oU=\n-----END RSA PRIVATE KEY-----`),\n\t\t2048: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAtKGse3BcxXAp5OkLGYq0HfDcCvgag3R/9e8pHUGsJhkSZFrn\nZWAsAVFKSYaYItf1D/g3izqVDMtMpXZ1chNzaRysnbrb/q7JTbiGzXo9FcshyUc9\ntcB60wFbvsXE2LaxZcKNxLYXbOvf+tdg/P07oPG24fzYI4+rbZ1wyoORbT1ys33Z\nhHyifFvO7rbe69y3HG+xbp7yWYAR4e8Nw9jX8/9sGslAV9vEXOdNL3qlcgsYRGDU\nDsUJsnWaMzjstvUxb8mVf9KG2W039ucgaXgBW/jeP3F1VSYFKLd03LvuJ8Ir5E0s\ncWjwTd59nm0XbbRI3KiBGnAgrJ4iK07HrUkpDQIDAQABAoIBAHfr1k1lfdH+83Fs\nXtgoRAiUviHyMfgQQlwO2eb4kMgCYTmLOJEPVmfRhlZmK18GrUZa7tVaoVYLKum3\nSaXg0AB67wcQ5bmiZTdaSPTmMOPlJpsw1wFxtpmcD0MKnfOa5w++KMzub4L63or0\nrwmHPi1ODLLgYMbLPW7a1eU9kDFLOnx3RRy9a29hQXxGsRYetrIbKmeDi6c+ndQ8\nI5YWObcixxl5GP6CTnEugV7wd2JmXuQRGFdopUwQESCD9VkxDSevQBSPoyZKHxGy\n/d3jf0VNlvwsxhD3ybhw8jTN/cmm2LWmP4jylG7iG7YRPVaW/0s39IZ9DnNDwgWB\n03Yk2gECgYEA44jcSI5kXOrbBGDdV+wTUoL24Zoc0URX33F15UIOQuQsypaFoRJ6\nJ23JWEZN99aquuo1+0BBSfiumbpLwSwfXi0nL3oTzS9eOp1HS7AwFGd/OHdpdMsC\nw2eInRwCh4GrEf508GXo+tSL2NS8+MFVAG2/SjEf06SroQ/rQ87Qm0ECgYEAyzqr\n6YvbAnRBy5GgQlTgxR9r0U8N7lM9g2Tk8uGvYI8zu/Tgia4diHAwK1ymKbl3lf95\n3NcHR+ffwOO+nnfFCvmCYXs4ggRCkeopv19bsCLkfnTBNTxPFh6lyLEnn3C+rcCe\nZAkKLrm8BHGviPIgn0aElMQAbhJxTWfClw/VVs0CgYAlDhfZ1R6xJypN9zx04iRv\nbpaoPQHubrPk1sR9dpl9+Uz2HTdb+PddznpY3vI5p4Mcd6Ic7eT0GATPUlCeAAKH\nwtC74aSx6MHux8hhoiriV8yXNJM/CwTDL+xGsdYTnWFvx8HhmKctmknAIT05QbsH\nG9hoS8HEJPAyhbYpz9eXQQKBgQCftPXQTPXJUe86uLBGMEmK34xtKkD6XzPiA/Hf\n5PdbXG39cQzbZZcT14YjLWXvOC8AE4qCwACaw1+VR+ROyDRy0W1iieD4W7ysymYQ\nXDHDk0gZEEudOE22RlNmCcHnjERsawiN+ISl/5P/sg+OASkdwd8CwZzM43VirP3A\nlNLEqQKBgHqj85n8ew23SR0GX0W1PgowaCHHD1p81y2afs1x7H9R1PNuQsTXKnpf\nvMiG7Oxakj4WDC5M5KsHWqchqKDycT+J1BfLI58Sf2qo6vtaV+4DARNgzcG/WB4b\nVnpsczK/1aUH7iBexuF0YqdPQwzpSvrY0XZcgCFQ52JDn3vjblhX\n-----END RSA PRIVATE KEY-----`),\n\t\t4096: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIJKgIBAAKCAgEAw28m5P1j7Rv1Wy4AicNkR4DXVxJXlPma+c5U/KJzFg0emiyx\nfkGQnUWeFofOI3rgrgK3deQ6yspgavTKWnHs4YeAz2egMSDsobI1OAP7ocPrFhYc\nFB+pTLXm1CkvyxIt9UWPxgc4CGiO1wIlfL8PpFg5vur7sAqbzxKeFx8GikbjFbQg\nd/RMFYeQacuimo9yea9DqjELvwewby3iP81FP9JJKiM3G6+7BiI+pJv65dNLbBUY\nHgKrmBHYg7WVSdmR7pZucEDoBqJcjc+kIHDGMH2vndWhIybEpHxxXdW+DrnPlhGV\n/hqKWw5fqJvhdh0OR1yefCCva0m6mZAKardzqxndFJqJbs1ehXg0luijVRYXaUpP\nuvHaKj+QV2R/PJWxkCLZLFSEAE156QT1sfY5FOh8rYBWBNrJk7X6qUTaF7Jfeo3H\nCF94ioP0Up8bohIu0lH8WPfTxdZ2lvUGSteMEYWBSbKhcbSCOP6a2K4/znSNl/J3\nLV/YcbmuSb7sAp+sZXELarYg/JMNVP4Vo2vh5S4ZCPYtk2or2WY27rMHWQ1vIhjB\nxjuSKzpLx9klusoTHB3wD6K7FwyT4JLUTfxGloSSpOuLG5yp9dAL/i8WHY20w6jP\n7ZYOss6OsQzp5ZqpW5M/0z60NsEOhfFXd1bxPYUP7//6N14XHTg31fg7vykCAwEA\nAQKCAgEAnn+j/K0ggKlfGL67Qv9Lcc4lVwGSNEknDhfvxyB809J6EjHTFYFZJqPS\nbZVgclfypk2fuqYJpHPzNGspPacNpW7+4ba6LX31S8I69R4N0wkQvM3bodp3tLYF\n6eUpVLl+ul/bFZC/OdqKlgewnXZa2j+PPa5Xx1MjQBJqUnggFr8c5no6pu5jUkaq\nsZKsYkuaXOPurbWvQBOdXN3Kk1IIKpWCLwF2bSbdOEFHqrqyBfiSP6rv707dGazH\nezImTEl+2A/6q2GIi/DbvUs8Ye70XVlht1ENqXOEoZ4nVyHFTS4XFC9ZBUdDFEwY\n+qbJeMBh1zBffG4JtqqKAobWW+xCioKVn2ArSzh1/2Q5652yeVVhR+GTSK2yd1uE\n5a5Pc65C8LCRNTz0iHEUESfVO5QnUq9bWShgm0H/LQ3sk8gzQjuBS5Ya523vOl1w\nxRUYxjEFW0382BrG0dn+WE2Yn0z5i2X9+WRgiKrh8tNZ+wNGN3MtZ5mloHsocH4N\nuUIZ6J0x/YruW126b0XA6fE+3taQDmJ4Qj/puU7+sFCs7MXUtd3tClEH1NUalH0T\n5awjZcJnMmGVmtGGfP1DtuEd082mIUuvKZj1vCEiSavwK3JDVl5goxlDpvEgdh2X\no1eSIMMZb6FG5h3dsyyMpXaRobgL+qbLm0XDGwtiIu+d5BE8OQECggEBAPL+FwUB\n2w4bRGzmDNRJm3oDcDlBROn5nFpzzSuXRA8zSrJbNB9s55EqTnZw7xVNa6nUxi9C\nd2Hqcbp9HD8EezlbMWJ4LASlYPzdBpAo5eyvK8YccE1QjlGlP7ZOf4+ekwlreqZ4\nfhRb4r/q49eW3aAWbJPu67MYu1iBMpdINZpMzDdE1wKjRXWu0j7Lr3SXjzgjD94E\nG+4VvJ0xc8WgjM9YSLxFN/5VZd+us7l6V18vOrdPDpAlJuTkmSpP0Xx4oUKJs7X+\n84CEB47GgUqf3bPadS8XRC2slEA+or5BJnPTVQ5YgTeWZE2kD3tLDOVHE7gLmV61\njYy2Icm+sosnfeECggEBAM3lVYO3D5Cw9Z4CkewrzMUxd7sSd5YqHavfEjvFc4Pk\n6Q6hsH1KR4Ai6loB8ugSz2SIS6KoqGD8ExvQxWy4AJf/n39hxb8/9IJ3b6IqBs64\n+ELJ8zw3QheER93FwK/KbawzLES9RkdpvDBSHFFfbGxjHpm+quQ8JcNIHTg43fb+\nTWe+mXYSjIWVCNssHBl5LRmkly37DxvBzu9YSZugESr80xSMDkBmWnpsq2Twh3q4\n2yP6jgfaZtV9AQQ01jkPgqpcuSoHm2qyqfiIr3LkA34OQmzWpyPn17If1DSJhlXo\nClSSl5Guqt9r0ifuBcMbl69OyAgpGr4N5sFxRk0wGkkCggEBAMt34hSqSiAUywYY\n2DNGc28GxAjdU3RMNBU1lF5k6nOD8o9IeWu7CGhwsYTR6hC/ZGCwL0dRc5/E7XhH\n3MgT247ago6+q7U0OfNirGU4Kdc3kwLvu0WyJ4nMQn5IWt4K3XpsyiXtDT3E9yjW\n6fQTev7a6A4zaJ/uHKnufUtaBrBukC3TcerehoIVYi185y1M33sVOOsiK7T/9JD3\n4MZiOqZAeZ9Uop9QKN7Vbd7ox5KHfLYT99DRmzDdDjf04ChG5llN7vJ9Sq6ZX665\nH3g6Ry2bxrYo2EkakoT9Lc77xNQF6Nn7WDAQuWqd7uzBmkm+a4+X/tPkWGOz+rTw\n/pYw+mECggEBAKQiMe1yPUJHD0YLHnB66h44tQ24RwS6RjUA+vQTD2cRUIiNdLgs\nQptvOgrOiuleNV4bGNBuSuwlhsYhw4BLno2NBYTyWEWBolVvCNrpTcv1wFLd0r0p\n/9HnbbLpNhXs9UjU8nFJwYCkVZTfoBtuSmyNB5PgXzLaj/AAyOpMywVe7C3Lz2JE\nnyjOCeVOYIgeBUnv32SUQxMJiQFcDDG3hHgUW+CBVcsYzP/TKT6qUBYQzwD7d8Xi\n4R9HK0xDIpMSPkO47xMGRWrlSoIJ1HNuOSqAC4vgAhWpeFVS8kN/bkuFUtbglVtZ\nNnYs6bdTE9zZXi4uS1/WBK+FPXLv7e8SbaECggEAI2gTDuCm5kVoVJhGzWA5/hmB\nPAUhSQpMHrT8Em4cXss6Q07q9A2l8NuNrZt6kNhwagdng7v7NdPY3ZBl/ntmKmZN\nxWUKzQCtIddW6Z/veO86F15NyBBZFXIOhzvwnrTtS3iX0JP0dlTZTv/Oe3DPk3aq\nsFJtHM6s44ZBYYAgzSAxTdl+80oGmtdrGnSRfRmlav1kjWLAKurXw8FTl9rKgGNA\nUUv/jGSe1DxnEMvtoSwQVjcS0im57vW0x8LEz5eTWMYwkvxGHm0/WU2Yb0I6mL4j\nPWrHwwPdRoF/cPNWa7eTsZBKdVN9iNHSu7yE9owXyHSpesI1IZf8Zq4bqPNpaA==\n-----END RSA PRIVATE KEY-----`),\n\t}\n\tblock, _ := pem.Decode(raw[size])\n\tkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivKey, err := utils.RSAToPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privKey, nil\n}", "func (_WyvernExchange *WyvernExchangeSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func (o *GetSlashingParametersOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateResult(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func NewRSAKeyPair() (*RSAKeyPair, error) {\n\treader := rand.Reader\n\tprivateKey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newRSAKeyPair(privateKey, &privateKey.PublicKey)\n}", "func encryptRSARecord(newRec *PasswordRecord, rsaPriv *rsa.PrivateKey, passKey []byte) (err error) {\n\tif newRec.RSAKey.RSAExpIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedExponent := padding.AddPadding(rsaPriv.D.Bytes())\n\tif newRec.RSAKey.RSAExp, err = symcrypt.EncryptCBC(paddedExponent, newRec.RSAKey.RSAExpIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimePIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeP := padding.AddPadding(rsaPriv.Primes[0].Bytes())\n\tif newRec.RSAKey.RSAPrimeP, err = symcrypt.EncryptCBC(paddedPrimeP, newRec.RSAKey.RSAPrimePIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimeQIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeQ := padding.AddPadding(rsaPriv.Primes[1].Bytes())\n\tnewRec.RSAKey.RSAPrimeQ, err = symcrypt.EncryptCBC(paddedPrimeQ, newRec.RSAKey.RSAPrimeQIV, passKey)\n\treturn\n}", "func IsRsaPublicKey(str string, keylen int) bool {\n\tbb := bytes.NewBufferString(str)\n\tpemBytes, err := ioutil.ReadAll(bb)\n\tif err != nil {\n\t\treturn false\n\t}\n\tblock, _ := pem.Decode(pemBytes)\n\tif block != nil && block.Type != \"PUBLIC KEY\" {\n\t\treturn false\n\t}\n\tvar der []byte\n\n\tif block != nil {\n\t\tder = block.Bytes\n\t} else {\n\t\tder, err = base64.StdEncoding.DecodeString(str)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tkey, err := x509.ParsePKIXPublicKey(der)\n\tif err != nil {\n\t\treturn false\n\t}\n\tpubkey, ok := key.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn false\n\t}\n\tbitlen := len(pubkey.N.Bytes()) * 8\n\treturn bitlen == int(keylen)\n}", "func (m *KeyPair) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with Resource\n\tif err := m.Resource.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *Provider) GetRSAKeys() (key *rsa.PrivateKey, err error) {\n\tif p.key == nil {\n\t\treturn nil, ErrKeyRequired\n\t}\n\n\tvar ok bool\n\tif key, ok = p.key.(*rsa.PrivateKey); !ok {\n\t\treturn nil, fmt.Errorf(\"private key is not RSA but is %T\", p.key)\n\t}\n\n\tvar cert *x509.Certificate\n\tif cert, err = p.GetLeafCertificate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey.PublicKey = *cert.PublicKey.(*rsa.PublicKey)\n\treturn key, nil\n}", "func getRSAKeyFromObjectHandle(p *pkcs11.Ctx, session pkcs11.SessionHandle, objectHandle pkcs11.ObjectHandle) (*data.RSAPublicKey, data.RoleName, error) {\n\n\tattrTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS, []byte{0}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{0}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, []byte{0}),\n\t}\n\n\tattr, err := p.GetAttributeValue(session, objectHandle, attrTemplate)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to get Attribute for: %d\", objectHandle)\n\t\treturn nil, \"\", fmt.Errorf(\"Failed to get attribute %d: %v\", objectHandle, err)\n\t}\n\n\trole := data.CanonicalRootRole\n\n\tvar modulus []byte\n\tvar exponent []byte\n\tfor _, a := range attr {\n\t\tif a.Type == pkcs11.CKA_MODULUS {\n\t\t\tmodulus = a.Value\n\t\t} else if a.Type == pkcs11.CKA_PUBLIC_EXPONENT {\n\t\t\texponent = a.Value\n\t\t} else if a.Type == pkcs11.CKA_LABEL {\n\t\t\tsplit := strings.Split(string(a.Value), \";\")\n\t\t\tif len(split) != 4 {\n\t\t\t\treturn nil, \"\", fmt.Errorf(\"Key contained invalid label.\")\n\t\t\t}\n\t\t\trole = data.RoleName(split[2])\n\t\t}\n\t}\n\n\trsaPubKey, err := getRSAPublicKey(modulus, exponent)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tpubBytes, err := x509.MarshalPKIXPublicKey(rsaPubKey)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to Marshal RSA public key\")\n\t\treturn nil, \"\", err\n\t}\n\treturn data.NewRSAPublicKey(pubBytes), role, nil\n}", "func (_WyvernExchange *WyvernExchangeCallerSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func MustRSAKey() *rsa.PrivateKey {\n\tkey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn key\n}", "func (m *GPGKey) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEmails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExpires(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSubsKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (lib *PKCS11Lib) GenerateRSAKeyPair(bits int, purpose KeyPurpose) (*PKCS11PrivateKeyRSA, error) {\n\treturn lib.GenerateRSAKeyPairOnSlot(lib.Slot.id, nil, nil, bits, purpose)\n}", "func GenerateRSA(bitSize int) (*rsa.PrivateKey, error) {\n\tif bitSize <= 1024 {\n\t\treturn nil, ErrInsecureKeyBitSize\n\t}\n\n\treturn rsa.GenerateKey(rand.Reader, bitSize)\n}", "func fromRSAKey(key ssh.PublicKey) (security.PublicKey, error) {\n\tk, err := parseRSAKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn security.NewRSAPublicKey(k), nil\n}", "func (r *Client) validateTemplateParams(t *Template, params []*Parameter) error {\n\tmissing := map[string]interface{}{}\n\t// copy all wanted params into missing\n\tfor k, v := range t.Parameters {\n\t\tmissing[k] = v\n\t}\n\t// remove items from missing list as found\n\tfor wantedKey := range t.Parameters {\n\t\tfor _, param := range params {\n\t\t\tif param.ParameterKey == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// phew found it\n\t\t\tif *param.ParameterKey == wantedKey {\n\t\t\t\tdelete(missing, wantedKey)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// if any left, then we have an issue\n\tif len(missing) > 0 {\n\t\tkeys := []string{}\n\t\tfor k := range missing {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tkeysCSV := strings.Join(keys, \",\")\n\t\treturn fmt.Errorf(\"missing required input parameters: [%s]\", keysCSV)\n\t}\n\treturn nil\n}", "func (lib *PKCS11Lib) exportRSAPublicKey(session pkcs11.SessionHandle, pubHandle pkcs11.ObjectHandle) (crypto.PublicKey, error) {\n\tlogger.Tracef(\"session=0x%X, obj=0x%X\", session, pubHandle)\n\ttemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS, nil),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, nil),\n\t}\n\texported, err := lib.Ctx.GetAttributeValue(session, pubHandle, template)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tvar modulus = new(big.Int)\n\tmodulus.SetBytes(exported[0].Value)\n\tvar bigExponent = new(big.Int)\n\tbigExponent.SetBytes(exported[1].Value)\n\tif bigExponent.BitLen() > 32 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\tif bigExponent.Sign() < 1 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\texponent := int(bigExponent.Uint64())\n\tresult := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: exponent,\n\t}\n\tif result.E < 2 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\treturn &result, nil\n}", "func (k *KeyInstanceCert) CreateRSAInstance() {\n\tprivateKey, _ := rsa.GenerateKey(rand.Reader, 4096)\n\tk.PrivateKey = privateKey //implicit durch compiler (*k).PrivateKey\n\tpublicKey := privateKey.PublicKey\n\tk.PublicKey = publicKey\n\n\tprivKeyPEM := new(bytes.Buffer)\n\tpem.Encode(privKeyPEM, &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t})\n\tk.PrivateKeyPEM = privKeyPEM\n\n\tpublicKeyPEM := new(bytes.Buffer)\n\tpem.Encode(publicKeyPEM, &pem.Block{\n\t\tType: \"RSA PUBLIC KEY\",\n\t\tBytes: x509.MarshalPKCS1PublicKey(&publicKey),\n\t})\n\tk.PublicKeyPEM = publicKeyPEM\n\n}", "func (asap *ASAP) Validate(jwt jwt.JWT, publicKey cr.PublicKey) error {\n\theader := jwt.(jws.JWS).Protected()\n\tkid := header.Get(KeyID).(string)\n\talg := header.Get(algorithm).(string)\n\n\tsigningMethod, err := getSigningMethod(alg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jwt.Validate(publicKey, signingMethod, validator.GenerateValidator(kid, asap.ServiceID))\n}", "func (o *UIParameter) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := elemental.ValidateRequiredString(\"key\", o.Key); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredString(\"type\", string(o.Type)); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"type\", string(o.Type), []string{\"Boolean\", \"Checkbox\", \"CVSSThreshold\", \"DangerMessage\", \"Duration\", \"Enum\", \"Endpoint\", \"FileDrop\", \"Float\", \"FloatSlice\", \"InfoMessage\", \"Integer\", \"IntegerSlice\", \"JSON\", \"List\", \"Message\", \"Namespace\", \"Password\", \"String\", \"StringSlice\", \"Switch\", \"TagsExpression\", \"Title\", \"WarningMessage\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\t// Custom object validation.\n\tif err := ValidateUIParameters(o); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (pk PublicKey) JWK() JWK {\n\tentry, ok := pk[JwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func (c *Coffin) encryptRSA(data []byte) ([]byte, error) {\n\n\t// If public key is not supplied, return error\n\tif len(c.Opts.PubKey) == 0 {\n\t\treturn emptyByte, ErrNoPubKey\n\t}\n\n\t// Unmarshall the RSA public key\n\trsaKey, err := UnmarshalPublicKey(bytes.NewBuffer(c.Opts.PubKey))\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Encrypt the data\n\thash := sha512.New()\n\tciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, rsaKey, data, nil)\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Return the data\n\treturn ciphertext, nil\n}", "func (r *RSA) Init() {\n\tlog.Infof(\"Generating %d bit RSA key...\", RSA_KEY_LENGTH)\n\n\t// generate RSA key\n\tvar pKey, err = rsa.GenerateKey(rand.Reader, RSA_KEY_LENGTH)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating RSA key:\" + err.Error())\n\t}\n\n\tr.privateKey = pKey\n\n\t// encode key to ASN.1 PublicKey Type\n\tvar key, err2 = asn1.Marshal(r.privateKey.PublicKey)\n\tif err2 != nil {\n\t\tlog.Fatal(\"Error encoding Public RSA key:\" + err2.Error())\n\t}\n\n\t// move public key to array\n\tcopy(r.PublicKey[:], key)\n}", "func validateParams() {\n\tif domain == \"\" {\n\t\tprintAndExit(\"-domain is required!\", true)\n\t}\n\n\tif passLength < 1 {\n\t\tprintAndExit(\"-password-length must be a positive number!\", true)\n\t}\n\n\tif passLength < 8 {\n\t\tfmt.Println(\"WARN: -password-length is too short. We will grant your wish, but this might be a security risk. Consider using longer password.\", false)\n\t}\n}", "func NewRSAKeyPair(name ndn.Name) (PrivateKey, PublicKey, error) {\n\tkeyName := ToKeyName(name)\n\tkey, e := rsa.GenerateKey(rand.Reader, 2048)\n\tif e != nil {\n\t\treturn nil, nil, e\n\t}\n\tpvt, e := NewRSAPrivateKey(keyName, key)\n\tif e != nil {\n\t\treturn nil, nil, e\n\t}\n\tpub, e := NewRSAPublicKey(keyName, &key.PublicKey)\n\tif e != nil {\n\t\treturn nil, nil, e\n\t}\n\treturn pvt, pub, e\n}", "func EncodePrivateKey(key crypto.PrivateKey) (jwk *JWK, err error) {\n\tjwk = new(JWK)\n\tswitch k := key.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tjwk.populateECPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\n\tcase *rsa.PrivateKey:\n\t\tjwk.populateRSAPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\t\tif len(k.Primes) < 2 || len(k.Precomputed.CRTValues) != len(k.Primes)-2 {\n\t\t\treturn nil, errors.New(\"jwk: invalid RSA primes number\")\n\t\t}\n\t\tjwk.P = b64.EncodeToString(k.Primes[0].Bytes())\n\t\tjwk.Q = b64.EncodeToString(k.Primes[1].Bytes())\n\t\tjwk.Dp = b64.EncodeToString(k.Precomputed.Dp.Bytes())\n\t\tjwk.Dq = b64.EncodeToString(k.Precomputed.Dq.Bytes())\n\t\tjwk.Qi = b64.EncodeToString(k.Precomputed.Qinv.Bytes())\n\n\t\tif len(k.Primes) > 2 {\n\t\t\tjwk.Oth = make([]*RSAPrime, len(k.Primes)-2)\n\t\t\tfor i := 0; i < len(k.Primes)-2; i++ {\n\t\t\t\tjwk.Oth[i] = &RSAPrime{\n\t\t\t\t\tR: b64.EncodeToString(k.Primes[i+2].Bytes()),\n\t\t\t\t\tD: b64.EncodeToString(k.Precomputed.CRTValues[i].Exp.Bytes()),\n\t\t\t\t\tT: b64.EncodeToString(k.Precomputed.CRTValues[i].Coeff.Bytes()),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"jwk: unknown private key type: %T\", key)\n\t}\n\n\treturn jwk, nil\n}", "func TestPublicKey(t *testing.T) {\n\tconst jsonkey = `{\"keys\":\n [\n {\"kty\":\"EC\",\n \"crv\":\"P-256\",\n \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\n \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\n \"use\":\"enc\",\n \"kid\":\"1\"},\n\n {\"kty\":\"RSA\",\n \"n\": \"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\",\n \"e\":\"AQAB\",\n \"alg\":\"RS256\",\n \"kid\":\"2011-04-29\"}\n ]\n }`\n\n\tjwt, err := Unmarshal([]byte(jsonkey))\n\tif err != nil {\n\t\tt.Fatal(\"Unmarshal: \", err)\n\t} else if len(jwt.Keys) != 2 {\n\t\tt.Fatalf(\"Expected 2 keys, got %d\", len(jwt.Keys))\n\t}\n\n\tkeys := make([]crypto.PublicKey, len(jwt.Keys))\n\tfor ii, jwt := range jwt.Keys {\n\t\tkeys[ii], err = jwt.DecodePublicKey()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode key %d: %v\", ii, err)\n\t\t}\n\t}\n\n\tif key0, ok := keys[0].(*ecdsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected ECDSA key[0], got %T\", keys[0])\n\t} else if key1, ok := keys[1].(*rsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected RSA key[1], got %T\", keys[1])\n\t} else if key0.Curve != elliptic.P256() {\n\t\tt.Fatal(\"Key[0] is not using P-256 curve\")\n\t} else if !bytes.Equal(key0.X.Bytes(), []byte{0x30, 0xa0, 0x42, 0x4c, 0xd2,\n\t\t0x1c, 0x29, 0x44, 0x83, 0x8a, 0x2d, 0x75, 0xc9, 0x2b, 0x37, 0xe7, 0x6e, 0xa2,\n\t\t0xd, 0x9f, 0x0, 0x89, 0x3a, 0x3b, 0x4e, 0xee, 0x8a, 0x3c, 0xa, 0xaf, 0xec, 0x3e}) {\n\t\tt.Fatalf(\"Bad key[0].X, got %v\", key0.X.Bytes())\n\t} else if !bytes.Equal(key0.Y.Bytes(), []byte{0xe0, 0x4b, 0x65, 0xe9, 0x24,\n\t\t0x56, 0xd9, 0x88, 0x8b, 0x52, 0xb3, 0x79, 0xbd, 0xfb, 0xd5, 0x1e, 0xe8,\n\t\t0x69, 0xef, 0x1f, 0xf, 0xc6, 0x5b, 0x66, 0x59, 0x69, 0x5b, 0x6c, 0xce,\n\t\t0x8, 0x17, 0x23}) {\n\t\tt.Fatalf(\"Bad key[0].Y, got %v\", key0.Y.Bytes())\n\t} else if key1.E != 0x10001 {\n\t\tt.Fatalf(\"Bad key[1].E: %d\", key1.E)\n\t} else if !bytes.Equal(key1.N.Bytes(), []byte{0xd2, 0xfc, 0x7b, 0x6a, 0xa, 0x1e,\n\t\t0x6c, 0x67, 0x10, 0x4a, 0xeb, 0x8f, 0x88, 0xb2, 0x57, 0x66, 0x9b, 0x4d, 0xf6,\n\t\t0x79, 0xdd, 0xad, 0x9, 0x9b, 0x5c, 0x4a, 0x6c, 0xd9, 0xa8, 0x80, 0x15, 0xb5,\n\t\t0xa1, 0x33, 0xbf, 0xb, 0x85, 0x6c, 0x78, 0x71, 0xb6, 0xdf, 0x0, 0xb, 0x55,\n\t\t0x4f, 0xce, 0xb3, 0xc2, 0xed, 0x51, 0x2b, 0xb6, 0x8f, 0x14, 0x5c, 0x6e, 0x84,\n\t\t0x34, 0x75, 0x2f, 0xab, 0x52, 0xa1, 0xcf, 0xc1, 0x24, 0x40, 0x8f, 0x79, 0xb5,\n\t\t0x8a, 0x45, 0x78, 0xc1, 0x64, 0x28, 0x85, 0x57, 0x89, 0xf7, 0xa2, 0x49, 0xe3,\n\t\t0x84, 0xcb, 0x2d, 0x9f, 0xae, 0x2d, 0x67, 0xfd, 0x96, 0xfb, 0x92, 0x6c, 0x19,\n\t\t0x8e, 0x7, 0x73, 0x99, 0xfd, 0xc8, 0x15, 0xc0, 0xaf, 0x9, 0x7d, 0xde, 0x5a,\n\t\t0xad, 0xef, 0xf4, 0x4d, 0xe7, 0xe, 0x82, 0x7f, 0x48, 0x78, 0x43, 0x24, 0x39,\n\t\t0xbf, 0xee, 0xb9, 0x60, 0x68, 0xd0, 0x47, 0x4f, 0xc5, 0xd, 0x6d, 0x90, 0xbf,\n\t\t0x3a, 0x98, 0xdf, 0xaf, 0x10, 0x40, 0xc8, 0x9c, 0x2, 0xd6, 0x92, 0xab, 0x3b,\n\t\t0x3c, 0x28, 0x96, 0x60, 0x9d, 0x86, 0xfd, 0x73, 0xb7, 0x74, 0xce, 0x7, 0x40,\n\t\t0x64, 0x7c, 0xee, 0xea, 0xa3, 0x10, 0xbd, 0x12, 0xf9, 0x85, 0xa8, 0xeb, 0x9f,\n\t\t0x59, 0xfd, 0xd4, 0x26, 0xce, 0xa5, 0xb2, 0x12, 0xf, 0x4f, 0x2a, 0x34, 0xbc,\n\t\t0xab, 0x76, 0x4b, 0x7e, 0x6c, 0x54, 0xd6, 0x84, 0x2, 0x38, 0xbc, 0xc4, 0x5, 0x87,\n\t\t0xa5, 0x9e, 0x66, 0xed, 0x1f, 0x33, 0x89, 0x45, 0x77, 0x63, 0x5c, 0x47, 0xa,\n\t\t0xf7, 0x5c, 0xf9, 0x2c, 0x20, 0xd1, 0xda, 0x43, 0xe1, 0xbf, 0xc4, 0x19, 0xe2,\n\t\t0x22, 0xa6, 0xf0, 0xd0, 0xbb, 0x35, 0x8c, 0x5e, 0x38, 0xf9, 0xcb, 0x5, 0xa, 0xea,\n\t\t0xfe, 0x90, 0x48, 0x14, 0xf1, 0xac, 0x1a, 0xa4, 0x9c, 0xca, 0x9e, 0xa0, 0xca, 0x83}) {\n\t\tt.Fatal(\"Bad key[1].N, got %v\", key1.N.Bytes())\n\t}\n}", "func IsRsaPub(str string, params ...string) bool {\n\tif len(params) == 1 {\n\t\tlen, _ := ToInt(params[0])\n\t\treturn IsRsaPublicKey(str, int(len))\n\t}\n\n\treturn false\n}", "func rsaPublicKeyFromPem(publicKeyPem string) (*rsa.PublicKey, error) {\n\tblock, _ := pem.Decode([]byte(publicKeyPem))\n\n\tif block == nil {\n\t\treturn nil, errors.New(\"RSA Public Key From Pem Fail: \" + \"Pem Block Nil\")\n\t}\n\n\tif key, err := x509.ParsePKIXPublicKey(block.Bytes); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn key.(*rsa.PublicKey), nil\n\t}\n}", "func CheckParameters(r *rest.Request, needed_fields []string) (bool, map[string]string) {\n\tvar result map[string]string\n\tresult = make(map[string]string)\n\tfor _, field := range needed_fields {\n\t\tvalues, _ := r.URL.Query()[field]\n\t\tif len(values) < 1 {\n\t\t\treturn false, result\n\t\t}\n\t\tresult[field] = values[0]\n\t}\n\treturn true, result\n}", "func GenerateKeyPair(bits int) (keypair *KeyPair, err error) {\n\tkeypair = new(KeyPair)\n\tkeypair.PublicKey = new(PublicKey)\n\tkeypair.PrivateKey = new(PrivateKey)\n\n\tif bits == 0 {\n\t\terr = errors.New(\"RSA modulus size must not be zero.\")\n\t\treturn\n\t}\n\tif bits%8 != 0 {\n\t\terr = errors.New(\"RSA modulus size must be a multiple of 8.\")\n\t\treturn\n\t}\n\n\tfor limit := 0; limit < 1000; limit++ {\n\t\tvar tempKey *rsa.PrivateKey\n\t\ttempKey, err = rsa.GenerateKey(rand.Reader, bits)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif len(tempKey.Primes) != 2 {\n\t\t\terr = errors.New(\"RSA package generated a weird set of primes (i.e. not two)\")\n\t\t\treturn\n\t\t}\n\n\t\tp := tempKey.Primes[0]\n\t\tq := tempKey.Primes[1]\n\n\t\tif p.Cmp(q) == 0 {\n\t\t\terr = errors.New(\"RSA keypair factors were equal. This is really unlikely dependent on the bitsize and it appears something horrible has happened.\")\n\t\t\treturn\n\t\t}\n\t\tif gcd := new(big.Int).GCD(nil, nil, p, q); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\terr = errors.New(\"RSA primes were not relatively prime!\")\n\t\t\treturn\n\t\t}\n\n\t\tmodulus := new(big.Int).Mul(p, q)\n\n\t\tpublicExp := big.NewInt(3)\n\t\t//publicExp := big.NewInt(65537)\n\n\t\t//totient = (p-1) * (q-1)\n\t\ttotient := new(big.Int)\n\t\ttotient.Sub(p, big.NewInt(1))\n\t\ttotient.Mul(totient, new(big.Int).Sub(q, big.NewInt(1)))\n\n\t\tif gcd := new(big.Int).GCD(nil, nil, publicExp, totient); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tprivateExp := new(big.Int).ModInverse(publicExp, totient)\n\t\tkeypair.PublicKey.Modulus = modulus\n\t\tkeypair.PrivateKey.Modulus = modulus\n\t\tkeypair.PublicKey.PublicExp = publicExp\n\t\tkeypair.PrivateKey.PrivateExp = privateExp\n\t\treturn\n\t}\n\terr = errors.New(\"Failed to generate a within the limit!\")\n\treturn\n\n}", "func rsaEqual(priv *rsa.PrivateKey, x crypto.PrivateKey) bool {\n\txx, ok := x.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\tif !(priv.PublicKey.N.Cmp(xx.N) == 0 && priv.PublicKey.E == xx.E) || priv.D.Cmp(xx.D) != 0 {\n\t\treturn false\n\t}\n\tif len(priv.Primes) != len(xx.Primes) {\n\t\treturn false\n\t}\n\tfor i := range priv.Primes {\n\t\tif priv.Primes[i].Cmp(xx.Primes[i]) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p Params) Validate() error {\n\tif err := validateCreateWhoisPrice(p.CreateWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateUpdateWhoisPrice(p.UpdateWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDeleteWhoisPrice(p.DeleteWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SolvePuzzleRSA(ciphertext []byte, puzzle crypto.Puzzle) (message []byte, err error) {\n\tif puzzle == nil {\n\t\terr = fmt.Errorf(\"Puzzle cannot be nil, what are you solving\")\n\t\treturn\n\t}\n\n\tvar key []byte\n\tif key, err = puzzle.Solve(); err != nil {\n\t\terr = fmt.Errorf(\"Error solving auction puzzle: %s\", err)\n\t\treturn\n\t}\n\n\tvar privkey *rsa.PrivateKey\n\tif privkey, err = x509.ParsePKCS1PrivateKey(key); err != nil {\n\t\terr = fmt.Errorf(\"Error when parsing private key with pkcs#1 encoding: %s\", err)\n\t\treturn\n\t}\n\n\tif message, err = privkey.Decrypt(rand.Reader, ciphertext, nil); err != nil {\n\t\terr = fmt.Errorf(\"Error when decrypting puzzle message: %s\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func ValidateVolumeParameters(volParam map[string]map[string]string) {\n\tvar err error\n\tfor vol, params := range volParam {\n\t\tif Inst().ConfigMap != \"\" {\n\t\t\tparams[authTokenParam], err = Inst().S.GetTokenFromConfigMap(Inst().ConfigMap)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t}\n\t\tStep(fmt.Sprintf(\"get volume: %s inspected by the volume driver\", vol), func() {\n\t\t\terr = Inst().V.ValidateCreateVolume(vol, params)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t})\n\t}\n}", "func JWTValidator(certificates map[string]CertificateList) jwt.Keyfunc {\n\treturn func(token *jwt.Token) (interface{}, error) {\n\n\t\tvar certificateList CertificateList\n\t\tvar kid string\n\t\tvar ok bool\n\n\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\tif kid, ok = token.Header[\"kid\"].(string); !ok {\n\t\t\treturn nil, fmt.Errorf(\"field 'kid' is of invalid type %T, should be string\", token.Header[\"kid\"])\n\t\t}\n\n\t\tif certificateList, ok = certificates[kid]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"kid '%s' not found in certificate list\", kid)\n\t\t}\n\n\t\tfor _, certificate := range certificateList {\n\t\t\treturn certificate.PublicKey, nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"no certificate candidates for kid '%s'\", kid)\n\t}\n}", "func (o *GetPublishersOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func CreateRSA() {\n\tgenRsaKeys(2048)\n}", "func NewRSAWriter(w io.Writer, n, e int64) *RSAWriter {\n\tnbig := big.NewInt(n)\n\treturn &RSAWriter{\n\t\tw: w,\n\t\tn: nbig,\n\t\te: big.NewInt(e),\n\t\tbytes: uint64(nbig.BitLen() / 8),\n\t}\n}" ]
[ "0.6804986", "0.6333782", "0.6148202", "0.58484894", "0.5737118", "0.56840175", "0.56579584", "0.5655421", "0.5614205", "0.5572611", "0.55541784", "0.55131155", "0.5499171", "0.54608613", "0.54498476", "0.54304063", "0.54144347", "0.5405987", "0.5393092", "0.5390702", "0.53462625", "0.5334125", "0.53277487", "0.5247343", "0.5177483", "0.5123732", "0.50823134", "0.5064948", "0.5038374", "0.501143", "0.49910355", "0.49870384", "0.49861157", "0.4980661", "0.4968173", "0.496773", "0.49629343", "0.49623448", "0.4955299", "0.49375123", "0.4934826", "0.49337405", "0.4921632", "0.49155584", "0.49076322", "0.48847792", "0.4881764", "0.48783225", "0.48647138", "0.48641956", "0.48604876", "0.4857553", "0.48419955", "0.48280326", "0.48242316", "0.48180294", "0.48159996", "0.48097938", "0.47866696", "0.47842884", "0.4781471", "0.47814524", "0.47794113", "0.4778422", "0.47778773", "0.47692925", "0.4752889", "0.47488612", "0.47268263", "0.47158548", "0.47144553", "0.47138888", "0.4713881", "0.47120875", "0.47115016", "0.4707539", "0.47052005", "0.470187", "0.4700956", "0.46978357", "0.46965668", "0.46892947", "0.46808147", "0.4678981", "0.46773466", "0.4676616", "0.4674257", "0.46549058", "0.465321", "0.4650981", "0.46494725", "0.4625706", "0.46246135", "0.46190426", "0.46115395", "0.4594625", "0.4592362", "0.458648", "0.45761552", "0.45720804" ]
0.82881474
0
NewIndexDB creates a new instance of IndexDB
NewIndexDB создает новый экземпляр IndexDB
func NewIndexDB(db store.DB, recordStore *RecordDB) *IndexDB { return &IndexDB{db: db, recordStore: recordStore} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateIndexDB(langName string, dbT DBType) IndexDB {\n\t// TODO 暂时只实现了内存存储,一次性的。\n\treturn initMenDB(langName)\n}", "func NewIndex(addr, name, typ string, md *index.Metadata) (*Index, error) {\n\n\tfmt.Println(\"Get a new index: \", addr, name)\n client := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\t//MaxIdleConnsPerHost: 200,\n\t\t\tMaxIdleConnsPerHost: 2000000,\n\t\t},\n\t\tTimeout: 2500000 * time.Millisecond,\n\t}\n\tconn, err := elastic.NewClient(elastic.SetURL(addr), elastic.SetHttpClient(client))\n\tif err != nil {\n fmt.Println(\"Get error here\");\n\t\treturn nil, err\n\t}\n\tret := &Index{\n\t\tconn: conn,\n\t\tmd: md,\n\t\tname: name,\n\t\ttyp: typ,\n\t}\n fmt.Println(\"get here ======\");\n\n\treturn ret, nil\n\n}", "func NewIndex(addrs []string, pass string, temporary int, name string, md *index.Metadata) *Index {\n\n\tret := &Index{\n\n\t\thosts: addrs,\n\n\t\tmd: md,\n\t\tpassword: pass,\n\t\ttemporary: temporary,\n\n\t\tname: name,\n\n\t\tcommandPrefix: \"FT\",\n\t}\n\tif md != nil && md.Options != nil {\n\t\tif opts, ok := md.Options.(IndexingOptions); ok {\n\t\t\tif opts.Prefix != \"\" {\n\t\t\t\tret.commandPrefix = md.Options.(IndexingOptions).Prefix\n\t\t\t}\n\t\t}\n\t}\n\t//ret.pool.MaxActive = ret.pool.MaxIdle\n\n\treturn ret\n\n}", "func New(path string) (*Index, error) {\n\tkvdb, err := pudge.Open(path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Index{\n\t\tdb: kvdb,\n\t\tpath: path,\n\t}, nil\n}", "func (es *Repository) NewIndex(ctx context.Context, index string) (error){\n\tsvc := es.client.CreateIndex(\"ethan\")\n\n\t_, err := svc.Do(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\n\treturn &documentIndex{\n\t\tindex: map[string][]byte{},\n\t\topts: opts,\n\t}\n}", "func New() *Index {\n\treturn &Index{Version: Version}\n}", "func (s *shard) initIndexDatabase() error {\n\tvar err error\n\tstoreOption := kv.DefaultStoreOption(filepath.Join(s.path, indexParentDir))\n\ts.indexStore, err = newKVStoreFunc(storeOption.Path, storeOption)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.forwardFamily, err = s.indexStore.CreateFamily(\n\t\tforwardIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(tagindex.SeriesForwardMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.invertedFamily, err = s.indexStore.CreateFamily(\n\t\tinvertedIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(tagindex.SeriesInvertedMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.indexDB, err = newIndexDBFunc(\n\t\tcontext.TODO(),\n\t\tfilepath.Join(s.path, metaDir),\n\t\ts.metadata, s.forwardFamily,\n\t\ts.invertedFamily)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewIndex() Index {\n\tnewIndex := Index{}\n\tnewIndex.Setup()\n\treturn newIndex\n}", "func (s *shard) initIndexDatabase() error {\n\tvar err error\n\tstoreOption := kv.DefaultStoreOption(filepath.Join(s.path, indexParentDir))\n\ts.indexStore, err = newKVStoreFunc(storeOption.Path, storeOption)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.forwardFamily, err = s.indexStore.CreateFamily(\n\t\tforwardIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(invertedindex.SeriesForwardMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.invertedFamily, err = s.indexStore.CreateFamily(\n\t\tinvertedIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(invertedindex.SeriesInvertedMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.indexDB, err = newIndexDBFunc(\n\t\tcontext.TODO(),\n\t\tfilepath.Join(s.path, metaDir),\n\t\ts.metadata, s.forwardFamily,\n\t\ts.invertedFamily)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func New(indexRegistry *registry.IndexRegistry, options ...func(*Index)) (I *Index, err error) {\n\tI = &Index{\n\t\tindexRegistry: indexRegistry,\n\t}\n\n\tfor _, option := range options {\n\t\toption(I)\n\t}\n\n\treturn\n}", "func New(path string) (ip *Indexio, err error) {\n\tvar i Indexio\n\t// Initialize functions map for marshaling and unmarshaling\n\tfm := turtleDB.NewFuncsMap(marshal, unmarshal)\n\t// Create new instance of turtleDB\n\tif i.db, err = turtleDB.New(\"indexio\", path, fm); err != nil {\n\t\treturn\n\t}\n\t// Initialize indexes bucket\n\tif err = i.db.Update(initBucket); err != nil {\n\t\treturn\n\t}\n\t// Assign ip as a pointer to i\n\tip = &i\n\treturn\n}", "func New(ds datastore.TxnDatastore, api *apistruct.FullNodeStruct) (*Index, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Index{\n\t\tapi: api,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\tindex: IndexSnapshot{\n\t\t\tMiners: make(map[string]Slashes),\n\t\t},\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}),\n\t}\n\tif err := s.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.start()\n\treturn s, nil\n}", "func newQueueIndex(dataDir string) (*queueIndex, error) {\n\tindexFile := path.Join(dataDir, cIndexFileName)\n\tindexArena, err := newArena(indexFile, cIndexFileSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &queueIndex{\n\t\tindexFile: indexFile,\n\t\tindexArena: indexArena,\n\t}, nil\n}", "func NewIndex(kind IndexKind, table string) Index {\n\treturn &index{\n\t\tkind: kind,\n\t\ttable: table,\n\t}\n}", "func NewIndex() *Index {\n\treturn &Index{root: &node{}}\n}", "func NewDb(storeType StoreType, dataDir string) (*Db, error) {\n\n\tvar store *genji.DB\n\tvar err error\n\n\tswitch storeType {\n\tcase StoreTypeMemory:\n\t\tstore, err = genji.Open(\":memory:\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error opening memory store: \", err)\n\t\t}\n\n\tcase StoreTypeBolt:\n\t\tdbFile := path.Join(dataDir, \"data.db\")\n\t\tstore, err = genji.Open(dbFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\tcase StoreTypeBadger:\n\t\tlog.Fatal(\"Badger not currently supported\")\n\t\t/*\n\t\t\t // uncomment the following to enable badger support\n\t\t\t\t// Create a badger engine\n\t\t\t\tdbPath := path.Join(dataDir, \"badger\")\n\t\t\t\tng, err := badgerengine.NewEngine(badger.DefaultOptions(dbPath))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\t// Pass it to genji\n\t\t\t\tstore, err = genji.New(context.Background(), ng)\n\t\t*/\n\n\tdefault:\n\t\tlog.Fatal(\"Unknown store type: \", storeType)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS meta (id INT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating meta table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS nodes (id TEXT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating nodes table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_nodes_type: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating edges table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_edge_up ON edges(up)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_edge_up: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_edge_down ON edges(down)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_edge_down: %w\", err)\n\t}\n\n\tdb := &Db{store: store}\n\treturn db, db.initialize()\n}", "func NewDb() *Db { //s interface{}\n\td := &Db{\n\t\tarr: make(Lister, 0, 100),\n\t\tupdate: time.Now().UnixNano(),\n\t}\n\treturn d\n}", "func New(ctx context.Context, ng engine.Engine) (*DB, error) {\n\treturn newDatabase(ctx, ng, database.Options{Codec: msgpack.NewCodec()})\n}", "func New(pg *pg.DB, index Index) *Model {\n\tInitTokenize()\n\treturn &Model{\n\t\tPG: pg,\n\t\tIndex: index,\n\t\tFiles: make(map[string]int),\n\t\tWords: make(map[string]int),\n\t}\n}", "func newIndex(name string) (index *ind) {\n\tindex = new(ind)\n\tindex.name = name\n\tindex.Storage = map[string][]string{}\n\tindex.Domains = map[string]bool{}\n\treturn\n}", "func New(ctx context.Context, dirPath string, opts *Options) (*DB, error) {\n\tvar (\n\t\trepo storage.Repository\n\t\terr error\n\t\tdbCloser io.Closer\n\t)\n\tif opts == nil {\n\t\topts = defaultOptions()\n\t}\n\n\tif opts.Logger == nil {\n\t\topts.Logger = log.Noop\n\t}\n\n\tlock := multex.New()\n\tmetrics := newMetrics()\n\topts.LdbStats.CompareAndSwap(nil, &metrics.LevelDBStats)\n\n\tlocker := func(addr swarm.Address) func() {\n\t\tlock.Lock(addr.ByteString())\n\t\treturn func() {\n\t\t\tlock.Unlock(addr.ByteString())\n\t\t}\n\t}\n\n\tif dirPath == \"\" {\n\t\trepo, dbCloser, err = initInmemRepository(locker)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// only perform migration if not done already\n\t\tif _, err := os.Stat(path.Join(dirPath, indexPath)); err != nil {\n\t\t\terr = performEpochMigration(ctx, dirPath, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\trepo, dbCloser, err = initDiskRepository(ctx, dirPath, locker, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tsharkyBasePath := \"\"\n\tif dirPath != \"\" {\n\t\tsharkyBasePath = path.Join(dirPath, sharkyPath)\n\t}\n\terr = migration.Migrate(\n\t\trepo.IndexStore(),\n\t\tlocalmigration.AllSteps(sharkyBasePath, sharkyNoOfShards, repo.ChunkStore()),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcacheObj, err := initCache(ctx, opts.CacheCapacity, repo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger := opts.Logger.WithName(loggerName).Register()\n\n\tdb := &DB{\n\t\tmetrics: metrics,\n\t\tlogger: logger,\n\t\tbaseAddr: opts.Address,\n\t\trepo: repo,\n\t\tlock: lock,\n\t\tcacheObj: cacheObj,\n\t\tretrieval: noopRetrieval{},\n\t\tpusherFeed: make(chan *pusher.Op),\n\t\tquit: make(chan struct{}),\n\t\tbgCacheLimiter: make(chan struct{}, 16),\n\t\tdbCloser: dbCloser,\n\t\tbatchstore: opts.Batchstore,\n\t\tvalidStamp: opts.ValidStamp,\n\t\tevents: events.NewSubscriber(),\n\t\treserveBinEvents: events.NewSubscriber(),\n\t\topts: workerOpts{\n\t\t\twarmupDuration: opts.WarmupDuration,\n\t\t\twakeupDuration: opts.ReserveWakeUpDuration,\n\t\t},\n\t\tdirectUploadLimiter: make(chan struct{}, pusher.ConcurrentPushes),\n\t\tinFlight: new(util.WaitingCounter),\n\t}\n\n\tif db.validStamp == nil {\n\t\tdb.validStamp = postage.ValidStamp(db.batchstore)\n\t}\n\n\tif opts.ReserveCapacity > 0 {\n\t\trs, err := reserve.New(\n\t\t\topts.Address,\n\t\t\trepo.IndexStore(),\n\t\t\topts.ReserveCapacity,\n\t\t\topts.RadiusSetter,\n\t\t\tlogger,\n\t\t\tfunc(ctx context.Context, store internal.Storage, addrs ...swarm.Address) error {\n\t\t\t\tdefer func() { db.metrics.CacheSize.Set(float64(db.cacheObj.Size())) }()\n\n\t\t\t\tdb.lock.Lock(cacheAccessLockKey)\n\t\t\t\tdefer db.lock.Unlock(cacheAccessLockKey)\n\n\t\t\t\treturn cacheObj.MoveFromReserve(ctx, store, addrs...)\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdb.reserve = rs\n\n\t\tdb.metrics.StorageRadius.Set(float64(rs.Radius()))\n\t\tdb.metrics.ReserveSize.Set(float64(rs.Size()))\n\t}\n\tdb.metrics.CacheSize.Set(float64(db.cacheObj.Size()))\n\n\t// Cleanup any dirty state in upload and pinning stores, this could happen\n\t// in case of dirty shutdowns\n\terr = errors.Join(\n\t\tupload.CleanupDirty(db),\n\t\tpinstore.CleanupDirty(db),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func dbNew() *DB {\n\treturn &DB{\n\t\tdata: make(map[string]string),\n\t}\n}", "func NewIndexDriver(root string) sql.IndexDriver {\n\treturn NewDriver(root, pilosa.DefaultClient())\n}", "func NewIndex(storage storages.Storage) Index {\n\treturn &multiIndex{index: storage}\n}", "func New(data []byte) *Index {}", "func NewIndex(f *os.File, c Config) (*Index, error) {\n\tidx := &Index{\n\t\tfile: f,\n\t}\n\n\tfi, err := os.Stat(f.Name())\n\tif err != nil {\n\t\treturn nil, lib.Wrap(err, \"Unable to get file stats\")\n\t}\n\n\tidx.size = uint64(fi.Size())\n\tif err = os.Truncate(\n\t\tf.Name(), int64(c.Segment.MaxIndexBytes),\n\t); err != nil {\n\t\treturn nil, lib.Wrap(err, \"Unable to truncate file\")\n\t}\n\n\tif idx.mmap, err = gommap.Map(\n\t\tidx.file.Fd(),\n\t\tgommap.PROT_READ|gommap.PROT_WRITE,\n\t\tgommap.MAP_SHARED,\n\t); err != nil {\n\t\treturn nil, lib.Wrap(err, \"Unable to create gommap map\")\n\t}\n\n\treturn idx, nil\n}", "func CreateIndex(context *web.AppContext) *web.AppError {\n\n\tdb := context.MDB\n\tvar input model.Index\n\tjson.NewDecoder(context.Body).Decode(&input)\n\n\terr := db.Session.DB(\"\").C(input.Target).EnsureIndex(input.Index)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error creating index [%+v]\", input)\n\t\treturn &web.AppError{err, message, http.StatusInternalServerError}\n\t}\n\n\treturn nil\n}", "func New(data []byte) *Index", "func NewIndexStorage(cfg *config.Storage, dir string, log *logging.Logger) (IndexStorage, error) {\n\tsecure := true\n\tif strings.HasPrefix(cfg.Host, \"localhost\") || strings.HasPrefix(cfg.Host, \"127.0.0.1\") {\n\t\tsecure = false\n\t}\n\n\tclient, err := minio.New(cfg.Host, cfg.Key, cfg.Secret, secure)\n\tif err != nil {\n\t\treturn IndexStorage{}, err\n\t}\n\n\treturn IndexStorage{cfg, dir, client, log.With(\"storage\", cfg.Bucket)}, nil\n}", "func NewIndex(path, name string) (*Index, error) {\n\terr := validateName(name)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"validating name\")\n\t}\n\n\treturn &Index{\n\t\tpath: path,\n\t\tname: name,\n\t\tfields: make(map[string]*Field),\n\n\t\tnewAttrStore: newNopAttrStore,\n\t\tcolumnAttrs: nopStore,\n\n\t\tbroadcaster: NopBroadcaster,\n\t\tStats: stats.NopStatsClient,\n\t\tlogger: logger.NopLogger,\n\t\ttrackExistence: true,\n\t}, nil\n}", "func NewDb(db *sql.DB, driverName string) *DB {\n return &DB{DB: db, driverName: driverName, Mapper: mapper()}\n}", "func NewIndex(physicalID int64, tblInfo *model.TableInfo, indexInfo *model.IndexInfo) table.Index {\n\tindex := &index{\n\t\tidxInfo: indexInfo,\n\t\ttblInfo: tblInfo,\n\t\t// The prefix can't encode from tblInfo.ID, because table partition may change the id to partition id.\n\t\tprefix: tablecodec.EncodeTableIndexPrefix(physicalID, indexInfo.ID),\n\t}\n\treturn index\n}", "func CreateNewIndex(url string, alias string) (string, error) {\n\t// create our day-specific name\n\tphysicalIndex := fmt.Sprintf(\"%s_%s\", alias, time.Now().Format(\"2006_01_02\"))\n\tidx := 0\n\n\t// check if it exists\n\tfor true {\n\t\tresp, err := http.Get(fmt.Sprintf(\"%s/%s\", url, physicalIndex))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// not found, great, move on\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\tbreak\n\t\t}\n\n\t\t// was found, increase our index and try again\n\t\tidx++\n\t\tphysicalIndex = fmt.Sprintf(\"%s_%s_%d\", alias, time.Now().Format(\"2006_01_02\"), idx)\n\t}\n\n\t// initialize our index\n\tcreateURL := fmt.Sprintf(\"%s/%s\", url, physicalIndex)\n\t_, err := MakeJSONRequest(http.MethodPut, createURL, indexSettings, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// all went well, return our physical index name\n\tlog.WithField(\"index\", physicalIndex).Info(\"created index\")\n\treturn physicalIndex, nil\n}", "func newDbIterator(typeName []byte, it iterator, db *leveldb.DB) (*DbIterator, error) {\n\n\tidx := &DbIterator{typeName: typeName, it: it, db: db}\n\n\treturn idx, nil\n}", "func New(ctx context.Context, ng engine.Engine, opts Options) (*Database, error) {\n\tif opts.Codec == nil {\n\t\treturn nil, errors.New(\"missing codec\")\n\t}\n\n\tdb := Database{\n\t\tng: ng,\n\t\tCodec: opts.Codec,\n\t}\n\n\tntx, err := db.ng.Begin(ctx, engine.TxOptions{\n\t\tWritable: true,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer ntx.Rollback()\n\n\terr = db.initInternalStores(ntx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = ntx.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &db, nil\n}", "func NewDB() *DB {\n\treturn &DB{}\n}", "func newDatabase(s *Server) *Database {\n\treturn &Database{\n\t\tserver: s,\n\t\tusers: make(map[string]*DBUser),\n\t\tpolicies: make(map[string]*RetentionPolicy),\n\t\tshards: make(map[uint64]*Shard),\n\t\tseries: make(map[string]*Series),\n\t}\n}", "func (d *Driver) Create(\n\tdb, table, id string,\n\texpressions []sql.Expression,\n\tconfig map[string]string,\n) (sql.Index, error) {\n\t_, err := mkdir(d.root, db, table, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config == nil {\n\t\tconfig = make(map[string]string)\n\t}\n\n\texprs := make([]string, len(expressions))\n\tfor i, e := range expressions {\n\t\texprs[i] = e.String()\n\t}\n\n\tcfg := index.NewConfig(db, table, id, exprs, d.ID(), config)\n\terr = index.WriteConfigFile(d.configFilePath(db, table, id), cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidx, err := d.newPilosaIndex(db, table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmapping := newMapping(d.mappingFilePath(db, table, id))\n\tprocessingFile := d.processingFilePath(db, table, id)\n\tif err := index.WriteProcessingFile(\n\t\tprocessingFile,\n\t\t[]byte{processingFileOnCreate},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPilosaIndex(idx, mapping, cfg), nil\n}", "func New(config *Config) (Database, error) {\n\tdb, err := connectToDB(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"Successfully connected to db\")\n\n\terr = migrateDB(config, db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"Successfully ran migrations\")\n\n\tsqlxDB := sqlx.NewDb(db, config.Driver)\n\n\tbaseDB := database{\n\t\tdb: sqlxDB,\n\t}\n\n\treturn &queries{\n\t\tauthorsQueries{baseDB},\n\t\tpostsQueries{baseDB},\n\t}, nil\n}", "func (b backend) New(ctx context.Context, l log.Interface, cfg *config.Config) (persist.Database, error) {\n\tusername, password, host, port, db :=\n\t\tcfg.Database.Postgres.Username,\n\t\tcfg.Database.Postgres.Password,\n\t\tcfg.Database.Postgres.Host,\n\t\tcfg.Database.Postgres.Port,\n\t\tcfg.Database.Postgres.DB\n\n\tconnString := fmt.Sprintf(\n\t\t\"postgres://%s:%s@%s:%d/%s\",\n\t\tusername,\n\t\tpassword,\n\t\thost,\n\t\tport,\n\t\tdb,\n\t)\n\n\tconn, err := pgxpool.Connect(ctx, connString)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(err, \"failed to connect to postgres\")\n\t}\n\n\tq := gen.New(conn)\n\n\treturn &database{\n\t\tqueries: q,\n\t}, nil\n}", "func New(db *bolt.DB) *kvq.DB {\n\treturn kvq.NewDB(&DB{db})\n}", "func New(dsn string, maxConn int) dao.DB {\n\treturn &db{\n\t\tDB: open(dsn, maxConn),\n\t}\n}", "func NewIndexBuilder(cfg *Config, g *GitRepo) *IndexBuilder {\n\treturn &IndexBuilder{\n\t\tcfg: cfg,\n\t\tg: g,\n\t\tmetadataCommit: make(commitInfoMap),\n\t}\n}", "func New(tb testing.TB, dir string, ver string, logger func(string)) (*DB, error) {\n\tdb, err := doNew(tb, dir, ver, logger)\n\tif err != nil && tb != nil {\n\t\ttb.Fatal(\"failed initializing database: \", err)\n\t}\n\treturn db, err\n}", "func New(config *connect.Config) Db {\n\tvar db Db\n\t// first find db in dbMap by DatabaseName\n\tdb = dbMap[config.DatabaseName]\n\t// find\n\tif db != nil {\n\t\treturn db\n\t}\n\t// not find in dbMap - New\n\tswitch config.DbType {\n\tcase connect.MONGODB:\n\t\t// init mongodb\n\t\tdb = mongo.New(config)\n\t}\n\tdbMap[config.DatabaseName] = db\n\treturn db\n}", "func NewIndex(name string, columns []string, indexType IndexType) Index {\n\treturn Index{\n\t\tName: name,\n\t\tColumns: columns,\n\t\tType: indexType,\n\t}\n}", "func CreateIndex(excludedPaths []string) (Index, error) {\n\tglog.V(1).Infof(\"CreateIndex(%v)\", excludedPaths)\n\n\tmapping := bleve.NewIndexMapping()\n\tif len(excludedPaths) > 0 {\n\t\tcustomMapping := bleve.NewDocumentMapping()\n\t\tfor _, path := range excludedPaths {\n\t\t\tpaths := strings.Split(path, \".\")\n\t\t\tpathToMapping(paths, customMapping)\n\t\t}\n\t\tmapping.DefaultMapping = customMapping\n\t}\n\tindex, err := bleve.NewMemOnly(mapping)\n\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tbatch := index.NewBatch()\n\n\treturn &bleveIndex{\n\t\tindex: index,\n\t\taddInc: 0,\n\t\tbatch: batch,\n\t}, nil\n}", "func (db *Database) CreateIndex(label, property string) (*Index, error) {\n\turi := join(db.Url, \"schema/index\", label)\n\tpayload := indexRequest{[]string{property}}\n\tresult := Index{db: db}\n\tne := NeoError{}\n\tresp, err := db.Session.Post(uri, payload, &result, &ne)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch resp.Status() {\n\tcase 200:\n\t\treturn &result, nil // Success\n\tcase 405:\n\t\treturn nil, NotAllowed\n\t}\n\treturn nil, ne\n}", "func newDatabase(count int) (*database, error) {\n\tdb, err := sql.Open(\"postgres\", fmt.Sprintf(`host=%s port=%s user=%s\n\t\tpassword=%s dbname=%s sslmode=disable`,\n\t\thost, port, user, password, dbname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"connected to psql client, host: %s\\n\", host)\n\n\treturn &database{\n\t\tdb: db,\n\t\terrChan: make(chan error, count),\n\t}, nil\n}", "func NewIndexBuilder() *IndexBuilder {\n\treturn &IndexBuilder{\n\t\tcontentPostings: make(map[ngram][]uint32),\n\t\tnamePostings: make(map[ngram][]uint32),\n\t\tbranches: make(map[string]int),\n\t}\n}", "func New(data []byte) []*Index {\n\treturn NewWithReader(bytes.NewReader(data))\n}", "func New(size int) *DB {\n\treturn &DB{\n\t\tdocs: make(map[int][]byte, size),\n\t\tall: intset.NewBitSet(0),\n\t}\n}", "func NewIndex(unique bool, columns []Column) *Index {\n\treturn &Index{\n\t\tbtree: btree.NewBTreeG[Doc](func(a, b Doc) bool {\n\t\t\treturn Order(a, b, columns, !unique) < 0\n\t\t}),\n\t}\n}", "func (dbclient *CouchDatabase) CreateNewIndexWithRetry(indexdefinition string, designDoc string) error {\n\t//get the number of retries\n\tmaxRetries := dbclient.CouchInstance.Conf.MaxRetries\n\n\t_, err := retry.Invoke(\n\t\tfunc() (interface{}, error) {\n\t\t\texists, err := dbclient.IndexDesignDocExists(designDoc)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn dbclient.CreateIndex(indexdefinition)\n\t\t},\n\t\tretry.WithMaxAttempts(maxRetries),\n\t)\n\treturn err\n}", "func NewIndexed() *Indexed {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn &Indexed{\n\t\tsize: 0,\n\t}\n}", "func NewIndex(buf string) (*Index, error) {\n\tindex := &Index{}\n\terr := yaml.Unmarshal([]byte(buf), index)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn index, nil\n}", "func (d *Driver) Create(db, table, id string, expressions []sql.Expression, config map[string]string) (sql.Index, error) {\n\t_, err := mkdir(d.root, db, table, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texprs := make([]string, len(expressions))\n\tfor i, e := range expressions {\n\t\texprs[i] = e.String()\n\t}\n\n\tcfg := index.NewConfig(db, table, id, exprs, d.ID(), config)\n\terr = index.WriteConfigFile(d.configFilePath(db, table, id), cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPilosaIndex(d.mappingFilePath(db, table, id), d.client, cfg), nil\n}", "func NewIndex(mapping IndexMapping, opts ...IndexOption) *Index {\n\tindex := &Index{\n\t\tIndexMapping: mapping,\n\t\tpopulateBatchSize: defaultPopulateBatchSize,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(index)\n\t}\n\n\treturn index\n}", "func newDBStore(db *couchdb.CouchDatabase, dbName string) *dbstore {\n\treturn &dbstore{dbName, db}\n}", "func New(db *sql.DB, maxGatewayCount int) DB {\n\treturn database{\n\t\tdb: db,\n\t\tmaxGatewayCount: maxGatewayCount,\n\t}\n}", "func NewDb() *Db {\n\treturn &Db{\n\t\tmake(map[string]*TitleInfo),\n\t\tmake(map[string]*EpisodeInfo),\n\t\tmake(map[string][]string),\n\t}\n}", "func NewIndex(texts []string, name string) *Index {\n\treturn &Index{texts: texts, name: name}\n}", "func newDB(client *gorm.DB) (*DB, error) {\n\tif client == nil {\n\t\treturn nil, fmt.Errorf(\"Mysql: could not connect\")\n\t}\n\tdb := &DB{\n\t\tclient: client,\n\t}\n\treturn db, nil\n}", "func NewIndex(data []byte) (*Index, error) {\n\tvar i Index\n\tdec := gob.NewDecoder(bytes.NewBuffer(data))\n\tif err := dec.Decode(&i); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &i, nil\n}", "func NewDB(e *entities.DB) *DB {\n\treturn &DB{e: e}\n}", "func NewIndexFile() *IndexFile {\n\treturn &IndexFile{}\n}", "func (s *searcher) CreateIndex() error {\n\tcolor.Cyan(\"[start] initialize index.\")\n\t// get user\n\tuser, reload, err := s.getUser()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\n\t// check to whether exist starred items or not.\n\tvar isNewIndex bool\n\tif err := s.db.Update(func(tx *bolt.Tx) error {\n\t\tvar err error\n\t\tbucket := tx.Bucket([]byte(starredBucketName(s.gitToken)))\n\t\tif bucket == nil {\n\t\t\tbucket, err = tx.CreateBucket([]byte(starredBucketName(s.gitToken)))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tisNewIndex = true\n\t\t} else {\n\t\t\tisNewIndex = false\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\tClearAll()\n\t\tcolor.Yellow(\"[err] collapse db file, so delete db file\")\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\n\t// read old database.\n\tvar oldStarredList []*git.Starred\n\toldStarredMap := map[string]*git.Starred{}\n\tif !isNewIndex {\n\t\t// read old starred from db\n\t\ts.db.View(func(tx *bolt.Tx) error {\n\t\t\tbucket := tx.Bucket([]byte(starredBucketName(s.gitToken)))\n\t\t\tbucket.ForEach(func(k, v []byte) error {\n\t\t\t\tvar starred *git.Starred\n\t\t\t\tif err := json.Unmarshal(v, &starred); err != nil {\n\t\t\t\t\tcolor.Yellow(\"[err] parsing %s\", string(k))\n\t\t\t\t} else {\n\t\t\t\t\toldStarredList = append(oldStarredList, starred)\n\t\t\t\t\toldStarredMap[starred.FullName] = starred\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\n\t\t// write old starred to index\n\t\tfor _, starred := range oldStarredList {\n\t\t\tif err := s.index.Index(starred.FullName, starred); err != nil {\n\t\t\t\tcolor.Yellow(\"[err] indexing %s\", starred.FullName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// are you all ready?\n\tif !reload && !isNewIndex {\n\t\tcount, _ := s.index.DocCount()\n\t\tcolor.Green(\"[success][using cache] %d items\", count)\n\t\treturn nil\n\t}\n\n\t// reload new starred list.\n\tnewStarredList, err := s.git.ListStarredAll()\n\tif err != nil {\n\t\tcolor.Yellow(\"[err] don't getting starred list %s\", err.Error())\n\t\tif !isNewIndex {\n\t\t\tcount, _ := s.index.DocCount()\n\t\t\tcolor.Yellow(\"[fail][using cache] %d items\", count)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"[err] CreateIndex %w\", err)\n\t}\n\tnewStarredMap := map[string]*git.Starred{}\n\tfor _, starred := range newStarredList {\n\t\tnewStarredMap[starred.FullName] = starred\n\t}\n\n\t// update and insert\n\tif isNewIndex {\n\t\tcolor.White(\"[refresh] all repositories\")\n\t\ts.git.SetReadme(newStarredList)\n\t\ts.writeDBAndIndex(newStarredList)\n\t} else {\n\t\t// insert or update starred\n\t\tvar insertList []*git.Starred\n\t\tvar updateList []*git.Starred\n\t\tfor _, newStarred := range newStarredList {\n\t\t\tif oldStarred, ok := oldStarredMap[newStarred.FullName]; !ok {\n\t\t\t\tinsertList = append(insertList, newStarred)\n\t\t\t\tcolor.White(\"[insert] %s repository pushed_at %s\",\n\t\t\t\t\tnewStarred.FullName, newStarred.PushedAt.Format(time.RFC3339))\n\t\t\t} else {\n\t\t\t\tif oldStarred.PushedAt.Unix() != newStarred.PushedAt.Unix() &&\n\t\t\t\t\toldStarred.CachedAt.Unix() < time.Now().Add(-24*7*time.Hour).Unix() { // after 7 days.\n\t\t\t\t\tupdateList = append(updateList, newStarred)\n\t\t\t\t\tcolor.White(\"[update] %s repository pushed_at %s\",\n\t\t\t\t\t\tnewStarred.FullName, newStarred.PushedAt.Format(time.RFC3339))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// insert\n\t\ts.git.SetReadme(insertList)\n\t\ts.writeDBAndIndex(insertList)\n\n\t\t// update\n\t\ts.git.SetReadme(updateList)\n\t\ts.writeDBAndIndex(updateList)\n\n\t\t// delete starred\n\t\tvar deleteList []*git.Starred\n\t\tfor _, oldStarred := range oldStarredList {\n\t\t\tif _, ok := newStarredMap[oldStarred.FullName]; !ok {\n\t\t\t\tdeleteList = append(deleteList, oldStarred)\n\t\t\t\tcolor.White(\"[delete] %s repository pushed_at %s\",\n\t\t\t\t\toldStarred.FullName, oldStarred.PushedAt.Format(time.RFC3339))\n\t\t\t}\n\t\t}\n\t\t// delete\n\t\ts.deleteDBAndIndex(deleteList)\n\t}\n\n\t// rewrite a user to db\n\tuserData, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\ts.db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(userBucketName))\n\t\tbucket.Put([]byte(s.gitToken), userData)\n\t\treturn nil\n\t})\n\n\tcount, _ := s.index.DocCount()\n\tcolor.Green(\"[success][new reload] %d items\", count)\n\treturn nil\n}", "func newDatabase(info extraInfo, db *sql.DB) *database {\n\treturn &database{\n\t\tname: info.dbName,\n\t\tdriverName: info.driverName,\n\t\tdb: db,\n\t}\n}", "func New(metainfo *Client, encStore *encryption.Store) *DB {\n\treturn &DB{\n\t\tmetainfo: metainfo,\n\t\tencStore: encStore,\n\t}\n}", "func New(config *config.ServerConfig, html *render.HTML) http.Handler {\n\treturn &indexController{config, html}\n}", "func (b Factory) New(ctx context.Context, name string, l log.Interface, cfg *config.Config) (Database, error) {\n\tbackend, ok := b[name]\n\tif !ok {\n\t\treturn nil, errwrap.Wrap(ErrDatabaseNotFound, name)\n\t}\n\n\tdb, err := backend.New(ctx, l, cfg)\n\n\treturn db, errwrap.Wrap(err, \"failed to create backend\")\n}", "func New(dl logbook.Logbook, databaseName string) (*Database, error) {\n\tdb := &Database{\n\t\tDlog: dl,\n\t}\n\n\t// Check if data folder exists\n\t_, err := os.Stat(config.DBFolder)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t// If folder does not exist, create it\n\t\t\terr := os.Mkdir(config.DBFolder, 0777)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"error\")\n\t\t\t}\n\t\t}\n\t}\n\n\terr = os.Chdir(config.DBFolder)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"error\")\n\t}\n\n\tf, err := os.Create(databaseName)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"error\")\n\t}\n\n\tdefer f.Close()\n\n\tdb.DatabaseName = databaseName\n\tdb.Version = 001\n\tdb.File = f\n\tdb.Data = map[string][]byte{}\n\n\twr := bufio.NewWriter(f)\n\n\t_, err = fmt.Fprintf(wr, \"DolceDB.%d\", config.DBVersion)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\twr.Flush()\n\n\terr = db.RebuildMap()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func New(cfg config.DB) (*gorm.DB, error) {\n\tdb, err := database.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := db.AutoMigrate(\n\t\trepository.Client{},\n\t\trepository.Deal{},\n\t\trepository.Position{},\n\t\trepository.OHLCV{},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func CreateDB(path string, nbuckets uint32) (*Database,error){\r\n\tdb,err := godbm.Create(path,nbuckets)\r\n\treturn &Database{DB:db},err\r\n}", "func New(path string) (*DB, error) {\n\tdb, err := bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\treturn &DB{Bolt: db}, err\n}", "func CreateBleveIndex(indexPath string, forceCreate, allowAppend bool) (bleve.Index, error) {\n\t// Create a new index.\n\tmapping := bleve.NewIndexMapping()\n\tindex, err := bleve.New(indexPath, mapping)\n\tif err == bleve.ErrorIndexPathExists {\n\t\tcommon.Log.Error(\"Bleve index %q exists.\", indexPath)\n\t\tif forceCreate {\n\t\t\tcommon.Log.Info(\"Removing %q.\", indexPath)\n\t\t\tremoveIndex(indexPath)\n\t\t\tindex, err = bleve.New(indexPath, mapping)\n\t\t} else if allowAppend {\n\t\t\tcommon.Log.Info(\"Opening existing %q.\", indexPath)\n\t\t\tindex, err = bleve.Open(indexPath)\n\t\t}\n\t}\n\treturn index, err\n}", "func NewMainDataIndex() (*DataIndex, error) {\n\tif mainDataIndex != nil {\n\t\treturn mainDataIndex, nil\n\t}\n\n\ti := &DataIndex{Name: mainIndexName}\n\terr := error(nil)\n\n\ti.Http, err = NewHttpClient(i.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.BlobStore, err = NewS3Store(\"datadex.archives\", i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmainDataIndex = i\n\treturn mainDataIndex, nil\n}", "func NewIndexConnection(context Context) *IndexConnection {\n\tsize := context.GetScanCap()\n\tif size <= 0 {\n\t\tsize = _ENTRY_CAP\n\t}\n\n\trv := &IndexConnection{\n\t\tcontext: context,\n\t}\n\tnewEntryExchange(&rv.sender, size)\n\treturn rv\n}", "func NewSimpleDB() *SimpleDB {\n\tindex := make(map[string]int64)\n\treturn &SimpleDB{\n\t\tindex: index,\n\t}\n}", "func CreateNew(dbFile, feeXPub string) error {\n\tlog.Infof(\"Initializing new database at %s\", dbFile)\n\n\tdb, err := bolt.Open(dbFile, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to open db file: %w\", err)\n\t}\n\n\tdefer db.Close()\n\n\t// Create all storage buckets of the VSP if they don't already exist.\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t// Create parent bucket.\n\t\tvspBkt, err := tx.CreateBucket(vspBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(vspBktK), err)\n\t\t}\n\n\t\t// Initialize with initial database version (1).\n\t\terr = vspBkt.Put(versionK, uint32ToBytes(initialVersion))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Info(\"Generating ed25519 signing key\")\n\n\t\t// Generate ed25519 key\n\t\t_, signKey, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to generate signing key: %w\", err)\n\t\t}\n\t\terr = vspBkt.Put(privateKeyK, signKey.Seed())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Generate a secret key for initializing the cookie store.\n\t\tlog.Info(\"Generating cookie secret\")\n\t\tsecret := make([]byte, 32)\n\t\t_, err = rand.Read(secret)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = vspBkt.Put(cookieSecretK, secret)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Info(\"Storing extended public key\")\n\t\t// Store fee xpub\n\t\terr = vspBkt.Put(feeXPubK, []byte(feeXPub))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create ticket bucket.\n\t\t_, err = vspBkt.CreateBucket(ticketBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(ticketBktK), err)\n\t\t}\n\n\t\t// Create vote change bucket.\n\t\t_, err = vspBkt.CreateBucket(voteChangeBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(voteChangeBktK), err)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Database initialized\")\n\n\treturn nil\n}", "func (fact FileFactory) CreateDB(ctx context.Context, nbf *types.NomsBinFormat, urlObj *url.URL, params map[string]interface{}) (datas.Database, types.ValueReadWriter, tree.NodeStore, error) {\n\tsingletonLock.Lock()\n\tdefer singletonLock.Unlock()\n\n\tif s, ok := singletons[urlObj.Path]; ok {\n\t\treturn s.ddb, s.vrw, s.ns, nil\n\t}\n\n\tpath, err := url.PathUnescape(urlObj.Path)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tpath = filepath.FromSlash(path)\n\tpath = urlObj.Host + path\n\n\terr = validateDir(path)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tvar useJournal bool\n\tif params != nil {\n\t\t_, useJournal = params[ChunkJournalParam]\n\t}\n\n\tvar newGenSt *nbs.NomsBlockStore\n\tq := nbs.NewUnlimitedMemQuotaProvider()\n\tif useJournal && chunkJournalFeatureFlag {\n\t\tnewGenSt, err = nbs.NewLocalJournalingStore(ctx, nbf.VersionString(), path, q)\n\t} else {\n\t\tnewGenSt, err = nbs.NewLocalStore(ctx, nbf.VersionString(), path, defaultMemTableSize, q)\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\toldgenPath := filepath.Join(path, \"oldgen\")\n\terr = validateDir(oldgenPath)\n\tif err != nil {\n\t\tif !errors.Is(err, os.ErrNotExist) {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\terr = os.Mkdir(oldgenPath, os.ModePerm)\n\t\tif err != nil && !errors.Is(err, os.ErrExist) {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\toldGenSt, err := nbs.NewLocalStore(ctx, newGenSt.Version(), oldgenPath, defaultMemTableSize, q)\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tst := nbs.NewGenerationalCS(oldGenSt, newGenSt)\n\t// metrics?\n\n\tvrw := types.NewValueStore(st)\n\tns := tree.NewNodeStore(st)\n\tddb := datas.NewTypesDatabase(vrw, ns)\n\n\tsingletons[urlObj.Path] = singletonDB{\n\t\tddb: ddb,\n\t\tvrw: vrw,\n\t\tns: ns,\n\t}\n\n\treturn ddb, vrw, ns, nil\n}", "func NewLogIndex() indices.Index { return &logIndex{} }", "func InitDB(db *mgo.Database) {\n\tfor i := range workIndexes {\n\t\terr := db.C(workIndexes[i].Name).EnsureIndex(workIndexes[i].Index)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}\n}", "func newDBStore(db *leveldbhelper.DBHandle, dbName string) *store {\n\treturn &store{db, dbName}\n}", "func (i *IndexedDB) Open(\n\tctx context.Context,\n\tname string,\n\tversion int,\n\tupgrader func(d *DatabaseUpdate, oldVersion, newVersion int) error,\n) (*Database, error) {\n\tvar db *Database\n\terrCh := make(chan error, 1)\n\tputErr := func(err error) {\n\t\tselect {\n\t\tcase errCh <- err:\n\t\tdefault:\n\t\t}\n\t}\n\todbReq := i.val.Call(\"open\", name, version)\n\todbReq.Set(\"onupgradeneeded\", js.FuncOf(\n\t\tfunc(th js.Value, dats []js.Value) interface{} {\n\t\t\tevent := dats[0]\n\t\t\t// event is an IDBVersionChangeEvent\n\t\t\toldVersion := event.Get(\"oldVersion\").Int()\n\t\t\tnewVersion := event.Get(\"newVersion\").Int()\n\t\t\tdb = &Database{val: event.Get(\"target\").Get(\"result\")}\n\t\t\tif err := upgrader(&DatabaseUpdate{Database: db}, oldVersion, newVersion); err != nil {\n\t\t\t\tputErr(err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t))\n\todbReq.Set(\"onerror\", js.FuncOf(\n\t\tfunc(th js.Value, dats []js.Value) interface{} {\n\t\t\to := dats[0]\n\t\t\tgo putErr(errors.New(o.\n\t\t\t\tGet(\"target\").\n\t\t\t\tGet(\"error\").\n\t\t\t\tGet(\"message\").\n\t\t\t\tString(),\n\t\t\t))\n\t\t\treturn nil\n\t\t},\n\t))\n\todbReq.Set(\"onsuccess\", js.FuncOf(\n\t\tfunc(th js.Value, dats []js.Value) interface{} {\n\t\t\to := dats[0]\n\t\t\tif db == nil {\n\t\t\t\tdb = NewDatabase(o.Get(\"target\").Get(\"result\"))\n\t\t\t}\n\t\t\tgo putErr(nil)\n\t\t\treturn nil\n\t\t},\n\t))\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase err := <-errCh:\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn db, nil\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tdb: db,\n\t}\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tdb: db,\n\t}\n}", "func NewIndexFile() *IndexFile {\n\treturn &IndexFile{\n\t\tAPIVersion: APIVersionV1,\n\t\tGenerated: time.Now(),\n\t\tEntries: map[string]VersionedBundle{},\n\t\tPublicKeys: []string{},\n\t}\n}", "func newIndexWithTempPath(name string) *Index {\n\tpath, err := ioutil.TempDir(\"\", \"pilosa-index-\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tindex, err := NewIndex(path, name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn index\n}", "func New(cfg config.Config, log *logrus.Logger) error {\n\tvar tpl bytes.Buffer\n\tvars := map[string]interface{}{\n\t\t\"typename\": getTypeName(cfg.Repository.URL),\n\t}\n\n\tindexMappingTemplate, _ := template.New(\"geo_mapping\").Parse(`{\n\t\t\"mappings\": {\n\t\t\t\"{{ .typename }}\": {\n\t\t\t\t\"properties\": {\n\t\t\t\t\t\"geometry\": {\n\t\t\t\t\t\t\"type\": \"geo_shape\"\n\t\t\t\t\t},\n \"collection\": {\n \"type\": \"text\",\n \"fielddata\": true\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`)\n\n\tindexMappingTemplate.Execute(&tpl, vars)\n\n\tctx := context.Background()\n\n\tclient, err := createClient(&cfg.Repository)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tindexName := getIndexName(cfg.Repository.URL)\n\n\tcreateIndex, err := client.CreateIndex(indexName).Body(tpl.String()).Do(ctx)\n\tif err != nil {\n\t\terrorText := fmt.Sprintf(\"Cannot create repository: %v\\n\", err)\n\t\tlog.Errorf(errorText)\n\t\treturn errors.New(errorText)\n\t}\n\tif !createIndex.Acknowledged {\n\t\treturn errors.New(\"CreateIndex was not acknowledged. Check that timeout value is correct.\")\n\t}\n\n\tlog.Debug(\"Creating Repository\" + cfg.Repository.URL)\n\tlog.Debug(\"Type: \" + cfg.Repository.Type)\n\tlog.Debug(\"URL: \" + cfg.Repository.URL)\n\n\treturn nil\n}", "func NewDb(context Context) Db {\n\treturn &dbImpl{\n\t\tcontext: context,\n\t}\n}", "func createNewDB(log *logrus.Entry, cnf *Config) error {\n\tvar err error\n\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\",\n\t\tcnf.DBHost, cnf.DBPort, cnf.DBUser, cnf.DBPassword, cnf.DBName)\n\n\tdb, err = sql.Open(\"postgres\", psqlInfo)\n\n\tif err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to connect to db\")\n\t}\n\n\t//try to ping the db\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to ping db\")\n\t}\n\n\tif err = helpers.MigrateDB(db, cnf.SQLMigrationDir); err != nil {\n\t\treturn err\n\t}\n\n\tboil.SetDB(db)\n\n\treturn nil\n}", "func MakeIndex() error {\n\n\treturn nil\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tUsers: users.New(db),\n\t\tSessions: sessions.New(db),\n\t\tWorkouts: workouts.New(db),\n\t\tExercises: exercises.New(db),\n\t}\n}", "func NewDB(filename string) (*DB, error) {\n\tdb, err := bbolt.Open(filename, 0600, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DB{db: db}, nil\n}", "func NewDB(filename string) (*DB, error) {\n\tdb, err := bbolt.Open(filename, 0600, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DB{db: db}, nil\n}", "func NewDB(conf *Config) (db *DB, err error) {\n\tdb = new(DB)\n\tdb.DB, err = sql.Open(\"postgres\", conf.OpenDBURL())\n\t// TODO (kostyarin): configure db: max idle, max open, lifetime, etc\n\t// using hardcoded values, or keeping the values in\n\t// the Config\n\treturn\n}", "func NewDB(now string) *DB {\n\treturn &DB{\n\t\tmeasurements: make(map[string]*Measurement),\n\t\tseries: make(map[uint32]*Series),\n\t\tNow: mustParseTime(now),\n\t}\n}", "func NewDB() *DB {\n\td := new(DB)\n\td.Init()\n\treturn d\n}" ]
[ "0.7321358", "0.7077958", "0.6995988", "0.695568", "0.68397", "0.6816478", "0.6716526", "0.6652811", "0.664919", "0.66478133", "0.6618617", "0.65940624", "0.65865254", "0.6480771", "0.64426786", "0.64285284", "0.6395965", "0.6346326", "0.6320402", "0.6302338", "0.6245616", "0.6229138", "0.6229036", "0.6227165", "0.6216742", "0.62113667", "0.62079114", "0.61823666", "0.61355436", "0.6129097", "0.6122665", "0.6116569", "0.6085264", "0.6084873", "0.6073171", "0.60626656", "0.6062655", "0.6054751", "0.6035376", "0.60221463", "0.60142946", "0.6013382", "0.6008504", "0.6005906", "0.60041696", "0.598034", "0.5979987", "0.59794205", "0.59765387", "0.59749043", "0.59669274", "0.5958867", "0.5944028", "0.5937026", "0.5934278", "0.59282666", "0.5928084", "0.5923825", "0.5922406", "0.59070027", "0.5904967", "0.5895931", "0.589264", "0.58860415", "0.58817416", "0.5878981", "0.58744156", "0.5870218", "0.58676565", "0.58663297", "0.58654636", "0.58592546", "0.58508784", "0.5846602", "0.5836341", "0.5830796", "0.5826649", "0.5826275", "0.5825539", "0.58185136", "0.5812588", "0.5812295", "0.58083177", "0.57965535", "0.5793704", "0.5791699", "0.57855976", "0.57855976", "0.5776348", "0.5771741", "0.5768051", "0.57653564", "0.5762999", "0.5758795", "0.57551694", "0.57548374", "0.57548374", "0.5750265", "0.57494247", "0.57161283" ]
0.7238606
1
UpdateLastKnownPulse must be called after updating TopSyncPulse
UpdateLastKnownPulse должен вызываться после обновления TopSyncPulse
func (i *IndexDB) UpdateLastKnownPulse(ctx context.Context, topSyncPulse insolar.PulseNumber) error { i.lock.Lock() defer i.lock.Unlock() indexes, err := i.ForPulse(ctx, topSyncPulse) if err != nil && err != ErrIndexNotFound { return errors.Wrapf(err, "failed to get indexes for pulse: %d", topSyncPulse) } for idx := range indexes { inslogger.FromContext(ctx).Debugf("UpdateLastKnownPulse. pulse: %d, object: %s", topSyncPulse, indexes[idx].ObjID.DebugString()) if err := i.setLastKnownPN(topSyncPulse, indexes[idx].ObjID); err != nil { return errors.Wrapf(err, "can't setLastKnownPN. objId: %s. pulse: %d", indexes[idx].ObjID.DebugString(), topSyncPulse) } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (trd *trxDispatcher) updateLastSeenBlock() {\n\t// get the current value\n\tlsb := trd.blkObserver.Load()\n\tlog.Noticef(\"last seen block is #%d\", lsb)\n\n\t// make the change in the database so the progress persists\n\terr := repo.UpdateLastKnownBlock((*hexutil.Uint64)(&lsb))\n\tif err != nil {\n\t\tlog.Errorf(\"could not update last seen block; %s\", err.Error())\n\t}\n}", "func (l *Latency) UpdateLast(m Metadata) { l.update(m, true) }", "func (m *PulseManager) Set(ctx context.Context, newPulse insolar.Pulse) error {\n\tm.setLock.Lock()\n\tdefer m.setLock.Unlock()\n\tif m.stopped {\n\t\treturn errors.New(\"can't call Set method on PulseManager after stop\")\n\t}\n\n\tctx, logger := inslogger.WithField(ctx, \"new_pulse\", newPulse.PulseNumber.String())\n\tlogger.Debug(\"received pulse\")\n\n\tctx, span := instracer.StartSpan(\n\t\tctx, \"PulseManager.Set\", trace.WithSampler(trace.AlwaysSample()),\n\t)\n\tspan.AddAttributes(\n\t\ttrace.Int64Attribute(\"pulse.PulseNumber\", int64(newPulse.PulseNumber)),\n\t)\n\tdefer span.End()\n\n\t// Dealing with node lists.\n\tlogger.Debug(\"dealing with node lists.\")\n\t{\n\t\tfromNetwork := m.NodeNet.GetAccessor(newPulse.PulseNumber).GetWorkingNodes()\n\t\tif len(fromNetwork) == 0 {\n\t\t\tlogger.Errorf(\"received zero nodes for pulse %d\", newPulse.PulseNumber)\n\t\t\treturn nil\n\t\t}\n\t\ttoSet := make([]insolar.Node, 0, len(fromNetwork))\n\t\tfor _, n := range fromNetwork {\n\t\t\ttoSet = append(toSet, insolar.Node{ID: n.ID(), Role: n.Role()})\n\t\t}\n\t\terr := m.NodeSetter.Set(newPulse.PulseNumber, toSet)\n\t\tif err != nil {\n\t\t\tpanic(errors.Wrap(err, \"call of SetActiveNodes failed\"))\n\t\t}\n\t}\n\n\tstoragePulse, err := m.PulseAccessor.Latest(ctx)\n\tif err == pulse.ErrNotFound {\n\t\tstoragePulse = *insolar.GenesisPulse\n\t} else if err != nil {\n\t\treturn errors.Wrap(err, \"call of GetLatestPulseNumber failed\")\n\t}\n\n\tfor _, d := range m.dispatchers {\n\t\td.ClosePulse(ctx, storagePulse)\n\t}\n\n\terr = m.JetModifier.Clone(ctx, storagePulse.PulseNumber, newPulse.PulseNumber, false)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to clone jet.Tree fromPulse=%v toPulse=%v\", storagePulse.PulseNumber, newPulse.PulseNumber)\n\t}\n\n\tif err := m.PulseAppender.Append(ctx, newPulse); err != nil {\n\t\treturn errors.Wrap(err, \"call of AddPulse failed\")\n\t}\n\n\terr = m.LogicRunner.OnPulse(ctx, storagePulse, newPulse)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, d := range m.dispatchers {\n\t\td.BeginPulse(ctx, newPulse)\n\t}\n\n\treturn nil\n}", "func updateLastAppended(s *followerReplication, req *pb.AppendEntriesRequest) {\n\t// Mark any inflight logs as committed\n\tif logs := req.Entries; len(logs) > 0 {\n\t\tlast := logs[len(logs)-1]\n\t\tatomic.StoreUint64(&s.nextIndex, last.Index+1)\n\t\ts.commitment.match(s.peer.ID, last.Index)\n\t}\n\n\t// Notify still leader\n\ts.notifyAll(true)\n}", "func (svr *Server) update(){\n\tmsg := svr.queue.Dequeue()\n\tif msg != nil {\n\t\t// fmt.Println(\"server receives msg with vecClocks: \", msg.Vec)\n\t\t// fmt.Println(\"server has vecClocks: \", svr.vecClocks)\n\t\tsvr.vecClockCond.L.Lock()\n\t\tfor svr.vecClocks[msg.Id] != msg.Vec[msg.Id]-1 || !smallerEqualExceptI(msg.Vec, svr.vecClocks, msg.Id) {\n\t\t\tif svr.vecClocks[msg.Id] > msg.Vec[msg.Id]-1 {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsvr.vecClockCond.Wait()\n\t\t}\n\t\t// update timestamp and write to local memory\n\t\tsvr.vecClocks[msg.Id] = msg.Vec[msg.Id]\n\t\t// fmt.Println(\"server increments vecClocks: \", svr.vecClocks)\n\t\tsvr.vecClockCond.Broadcast()\n\t\tsvr.vecClockCond.L.Unlock()\n\t\tif err := d.WriteString(msg.Key,msg.Val); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}", "func (p *Peer) UpdateLastAnnouncedBlock(blkHash *chainhash.Hash) {\n\tlog.Tracef(\"Updating last blk for peer %v, %v\", p.addr, blkHash)\n\n\tp.statsMtx.Lock()\n\tp.lastAnnouncedBlock = blkHash\n\tp.statsMtx.Unlock()\n}", "func (pb *PBServer) tick() {\n view, ok := pb.vs.Get()\n now := time.Now()\n if !ok {\n if now.Sub(pb.lastGetViewTime) > viewservice.PingInterval * viewservice.DeadPings / 2 {\n pb.staleView = true\n }\n return\n } else {\n pb.lastGetViewTime = now\n pb.staleView = false\n }\n\n // fmt.Printf(\"viewnum: %d, me: %s, p: %s, b: %s\\n\", view.Viewnum, pb.me, view.Primary, view.Backup)\n pb.mu.Lock()\n defer pb.mu.Unlock()\n update_view := true\n if view.Primary == pb.me {\n if view.Backup == \"\" {\n update_view = true\n } else if view.Backup != pb.view.Backup {\n snapshot := SnapshotArgs{pb.values}\n var reply SnapshotReply\n ok := call(view.Backup, \"PBServer.SendSnapshot\", &snapshot, &reply)\n if !ok {\n fmt.Printf(\"Failed to call PBServer.SendSnapshot on backup: '%s'\\n\", view.Backup)\n update_view = false\n } else if reply.Err == OK {\n fmt.Printf(\"Successfully send snapshot to backup: '%s'\\n\", view.Backup)\n update_view = true\n } else {\n fmt.Printf(\"Failed to send snapshot to backup '%s': %s\\n\", view.Backup, reply.Err)\n update_view = false\n }\n }\n }\n // if view.Backup == pb.Me {\n // if pb.view.Backup != pb.Me {\n // \n // }\n // }\n if update_view {\n pb.view = view\n }\n pb.vs.Ping(pb.view.Viewnum)\n}", "func (svr *Server) update(){\n\tmsg := svr.queue.Dequeue()\n\tif msg != nil {\n\t\t// fmt.Println(\"server receives msg with vec_clock: \", msg.Vec)\n\t\t// fmt.Println(\"server has vec_clock: \", svr.vec_clock)\n\t\tsvr.vec_clock_cond.L.Lock()\n\t\tfor svr.vec_clock[msg.Id] != msg.Vec[msg.Id]-1 || !smallerEqualExceptI(msg.Vec, svr.vec_clock, msg.Id) {\n\t\t\tsvr.vec_clock_cond.Wait()\n\t\t\tif svr.vec_clock[msg.Id] > msg.Vec[msg.Id]-1 {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// update timestamp and write to local memory\n\t\tsvr.vec_clock[msg.Id] = msg.Vec[msg.Id]\n\t\t// fmt.Println(\"server increments vec_clock: \", svr.vec_clock)\n\t\tsvr.vec_clock_cond.Broadcast()\n\t\tsvr.vec_clock_cond.L.Unlock()\n\t\tsvr.m_data_lock.Lock()\n\t\tsvr.m_data[msg.Key] = msg.Val\n\t\tsvr.m_data_lock.Unlock()\n\t}\n}", "func (e *Endpoint) UpdateLastConnection() {\n\te.LastConnection = time.Now().UTC()\n}", "func (mmOnPulseFromConsensus *GatewayMock) OnPulseFromConsensusAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmOnPulseFromConsensus.afterOnPulseFromConsensusCounter)\n}", "func (p *Peer) runUpdateSyncing() {\n\ttimer := time.NewTimer(p.streamer.syncUpdateDelay)\n\tdefer timer.Stop()\n\n\tselect {\n\tcase <-timer.C:\n\tcase <-p.streamer.quit:\n\t\treturn\n\t}\n\n\tkad := p.streamer.delivery.kad\n\tpo := chunk.Proximity(p.BzzAddr.Over(), kad.BaseAddr())\n\n\tdepth := kad.NeighbourhoodDepth()\n\n\tlog.Debug(\"update syncing subscriptions: initial\", \"peer\", p.ID(), \"po\", po, \"depth\", depth)\n\n\t// initial subscriptions\n\tp.updateSyncSubscriptions(syncSubscriptionsDiff(po, -1, depth, kad.MaxProxDisplay))\n\n\tdepthChangeSignal, unsubscribeDepthChangeSignal := kad.SubscribeToNeighbourhoodDepthChange()\n\tdefer unsubscribeDepthChangeSignal()\n\n\tprevDepth := depth\n\tfor {\n\t\tselect {\n\t\tcase _, ok := <-depthChangeSignal:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// update subscriptions for this peer when depth changes\n\t\t\tdepth := kad.NeighbourhoodDepth()\n\t\t\tlog.Debug(\"update syncing subscriptions\", \"peer\", p.ID(), \"po\", po, \"depth\", depth)\n\t\t\tp.updateSyncSubscriptions(syncSubscriptionsDiff(po, prevDepth, depth, kad.MaxProxDisplay))\n\t\t\tprevDepth = depth\n\t\tcase <-p.streamer.quit:\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Debug(\"update syncing subscriptions: exiting\", \"peer\", p.ID())\n}", "func (rf *Raft) pulse() {\n\tfor rf.isLeader() {\n\t\t// Start send AppendEntries RPC to the rest of cluster\n\t\tfor ii := range rf.peers {\n\t\t\tif ii == rf.me {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo func(i int) {\n\t\t\t\targs := rf.makeAppendEntriesArgs(i)\n\t\t\t\treply := AppendEntriesReply{}\n\t\t\t\trf.sendAppendEntries(i, &args, &reply)\n\t\t\t\trf.appendEntriesReplyHandler <- reply\n\t\t\t}(ii)\n\t\t}\n\n\t\ttime.Sleep(time.Duration(HeartBeatsInterval) * time.Millisecond)\n\t}\n}", "func (f *Input) syncLastPollFiles(ctx context.Context) {\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\n\t// Encode the number of known files\n\tif err := enc.Encode(len(f.knownFiles)); err != nil {\n\t\tf.Errorw(\"Failed to encode known files\", zap.Error(err))\n\t\treturn\n\t}\n\n\t// Encode each known file\n\tfor _, fileReader := range f.knownFiles {\n\t\tif err := enc.Encode(fileReader); err != nil {\n\t\t\tf.Errorw(\"Failed to encode known files\", zap.Error(err))\n\t\t}\n\t}\n\n\tif err := f.persister.Set(ctx, knownFilesKey, buf.Bytes()); err != nil {\n\t\tf.Errorw(\"Failed to sync to database\", zap.Error(err))\n\t}\n}", "func (s *Storage) GetPulseByPrev(prevPulse models.Pulse) (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetPulseByPrevDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulse models.Pulse\n\terr := s.db.Where(\"prev_pulse_number = ?\", prevPulse.PulseNumber).First(&pulse).Error\n\treturn pulse, err\n}", "func (mmOnPulseFromPulsar *GatewayMock) OnPulseFromPulsarAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmOnPulseFromPulsar.afterOnPulseFromPulsarCounter)\n}", "func (buf *queueBuffer) updateLast(newNode *messageNode) {\n\tif buf.last != nil {\n\t\tbuf.last.next = newNode\n\t}\n\tbuf.last = newNode\n}", "func (huo *HistorytakingUpdateOne) AddPulse(i int) *HistorytakingUpdateOne {\n\thuo.mutation.AddPulse(i)\n\treturn huo\n}", "func (s *Storage) GetNextSavedPulse(fromPulseNumber models.Pulse, completedOnly bool) (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetNextSavedPulseDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulses []models.Pulse\n\tdb := s.db.Where(\"pulse_number > ?\", fromPulseNumber.PulseNumber)\n\tif completedOnly {\n\t\tdb = db.Where(\"is_complete = ?\", true)\n\t}\n\terr := db.Order(\"pulse_number asc\").Limit(1).Find(&pulses).Error\n\tif err != nil {\n\t\treturn models.Pulse{}, err\n\t}\n\tif len(pulses) == 0 {\n\t\treturn models.Pulse{}, nil\n\t}\n\treturn pulses[0], err\n}", "func (pb *PBServer) tick() {\n\tpb.Lock()\n\tdefer pb.Unlock()\n\n\t// Your code here.\n\tnewView, err := pb.vs.Ping(pb.curView.Viewnum)\n\tif err != nil {\n\t\tlog.Printf(\"ping view service error:%v\", err)\n\t\treturn\n\t}\n\n\tif newView.Viewnum == pb.curView.Viewnum { // no change\n\t\treturn\n\t}\n\n\tif newView.Primary != \"\" && newView.Primary == pb.me {\n\t\tif newView.Backup != \"\" && pb.curView.Backup != newView.Backup { // backup changed\n\t\t\terr := pb.clone(newView.Viewnum, newView.Backup)\n\t\t\tif err != nil { // backup not ready\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tpb.curView = newView\n}", "func (rf *Raft) updateLastApplied() {\n\trf.lock(\"UpdateLastApplied\")\n\tdefer rf.unlock(\"UpdateLastApplied\")\n\tfor rf.lastApplied < rf.commitIndex {\n\t\trf.lastApplied += 1\n\t\tcommand := rf.log[rf.lastApplied].Command\n\t\tapplyMsg := ApplyMsg{true, command, rf.lastApplied}\n\t\t// DPrintf(\"updateLastApplied, server[%d]\", rf.me)\n\t\trf.applyCh <- applyMsg\n\t\t// DPrintf(\"final apply from server[%d], his state is %v\", rf.me, rf.state)\n\t}\n\n}", "func (c *MhistConnector) Update() {\n\tfor {\n\t\tmessage := <-c.brokerChannel\n\t\tmeasurement := proto.MeasurementFromModel(&models.Raw{\n\t\t\tValue: message.Measurement,\n\t\t})\n\t\terr := c.writeStream.Send(&proto.MeasurementMessage{\n\t\t\tName: message.Channel,\n\t\t\tMeasurement: measurement,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Writing to MHIST StoreStream failed: %v\", err)\n\t\t}\n\t\tlog.Printf(\"Message added to MHIST:\\nName: %s,\\nMeasurement: %s,\\nTimestamp: %d\", message.Channel, string(message.Measurement), message.Timestamp)\n\t}\n}", "func (m *Dash) Update() error {\n\n\tif m.roomba == nil {\n\t\treturn fmt.Errorf(\"roomba not initialized\")\n\t}\n\n\tt := time.NewTicker(1000 * time.Millisecond)\n\tsg := []byte{constants.SENSOR_GROUP_6, constants.SENSOR_GROUP_101}\n\tpg := [][]byte{constants.PACKET_GROUP_6, constants.PACKET_GROUP_101}\n\n\tfor {\n\t\t<-t.C\n\t\tfmt.Printf(\"%s\\n\", time.Now().Format(\"2006/01/02 150405\"))\n\n\t\t// Iterate through the packet groups. Sensor group 100 does not work as advertised.\n\t\t// Use sensor group, 6 and 101 instead.\n\t\tfor grp := 0; grp < 2; grp++ {\n\t\t\td, e := m.roomba.Sensors(sg[grp])\n\t\t\tfmt.Println(\"Raw:%v Len:%v\", d, len(d))\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\n\t\t\ti := byte(0)\n\t\t\tfor _, p := range pg[grp] {\n\t\t\t\tpktL := constants.SENSOR_PACKET_LENGTH[p]\n\n\t\t\t\tif pktL == 1 {\n\t\t\t\t\tfmt.Printf(\"%25s: %v \\n\", constants.SENSORS_NAME[p], d[i])\n\t\t\t\t}\n\t\t\t\tif pktL == 2 {\n\n\t\t\t\t\tfmt.Printf(\"%25s: %v \\n\", constants.SENSORS_NAME[p], int16(d[i])<<8|int16(d[i+1]))\n\t\t\t\t}\n\t\t\t\ti = i + pktL\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *RouterController) updateLastSyncProcessed() {\n\tlastSyncProcessed := c.endpointsListConsumed && c.routesListConsumed &&\n\t\t(c.Namespaces == nil || c.filteredByNamespace)\n\tif err := c.Plugin.SetLastSyncProcessed(lastSyncProcessed); err != nil {\n\t\tutilruntime.HandleError(err)\n\t}\n}", "func (s *Storage) SavePulse(pulse models.Pulse) error {\n\ttimer := prometheus.NewTimer(SavePulseDuration)\n\tdefer timer.ObserveDuration()\n\n\terr := s.db.Set(\"gorm:insert_option\", \"\"+\n\t\t\"ON CONFLICT (pulse_number) DO UPDATE SET prev_pulse_number=EXCLUDED.prev_pulse_number, \"+\n\t\t\"next_pulse_number=EXCLUDED.next_pulse_number, timestamp=EXCLUDED.timestamp\",\n\t).Create(&pulse).Error\n\treturn errors.Wrap(err, \"error while saving pulse\")\n}", "func (bbo *TabularBBO) LastUpdate(s []float64, a int, r float64, rng *mathlib.Random) {\n\t// If ready to update, update and wipe the states, actions, and rewards.\n\tif bbo.ep.LastUpdate(s, a, r) {\n\t\tbbo.episodeLimitReached(rng)\n\t}\n}", "func (hu *HistorytakingUpdate) AddPulse(i int) *HistorytakingUpdate {\n\thu.mutation.AddPulse(i)\n\treturn hu\n}", "func (_XStaking *XStakingCaller) LastUpdateTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"lastUpdateTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (pb *PBServer) tick() {\n pb.mu.Lock()\n // Your code here\n v := pb.view\n pb.view, _ = pb.vs.Ping(pb.view.Viewnum)\n if pb.view.Viewnum > v.Viewnum && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n// if v.Backup != pb.view.Backup && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n args := &CopyArgs{}\n reply := CopyReply{}\n args.KV = pb.kv\n args.Serials = pb.serials\n fmt.Printf(\"######%s copy database\\n\", pb.me)\n for true {\n ok := call(pb.view.Backup, \"PBServer.ForwardComplete\", args, &reply)\n if ok {\n break\n }\n }\n }\n pb.mu.Unlock()\n// DPrintf(\"tick! %s %d\\n\", pb.me, pb.view.Viewnum);\n}", "func (pb *PBServer) tick() {\n\n newview, err := pb.vs.Ping(pb.view.Viewnum)\n if err != nil {\n fmt.Printf(\"view serivice unreachable!, error %s\\n\", err)\n return;\n }\n\n if pb.view.Viewnum != newview.Viewnum {\n fmt.Printf(\"view changed from \\n%s ==>\\n%s\\n\",pb.view, newview)\n if (pb.view.Primary == pb.me &&\n newview.Primary == pb.me &&\n pb.view.Backup != newview.Backup &&\n newview.Backup != \"\") {\n // backup changes and I'm still primary \n pb.view = newview\n fmt.Printf(\"new backup is %s\\n\", newview.Backup)\n pb.syncWithBackup()\n }\n }\n // only when pb is in the view, proceed to new view\n if pb.me == newview.Primary || pb.me == newview.Backup {\n pb.view = newview\n } else {\n fmt.Printf(\"I'm not in the view, keep trying\\n\")\n }\n}", "func (this *metaUsbSvc) LastUpdate() (time.Time) {\n\treturn this.Usb.LastUpdate()\n}", "func (rf *Raft) updateLastCommit() {\n\t// rf.lock(\"updateLastCommit\")\n\t// defer rf.unlock(\"updateLastCommit\")\n\tmatchIndexCopy := make([]int, len(rf.matchIndex))\n\tcopy(matchIndexCopy, rf.matchIndex)\n\t// for i := range rf.matchIndex {\n\t//\tDPrintf(\"matchIndex[%d] is %d\", i, rf.matchIndex[i])\n\t// }\n\n\t// sort.Sort(sort.IntSlice(matchIndexCopy))\n\tsort.Sort(sort.Reverse(sort.IntSlice(matchIndexCopy)))\n\tN := matchIndexCopy[len(matchIndexCopy)/2]\n\t// for i := range rf.log {\n\t//\tDPrintf(\"server[%d] %v\", rf.me, rf.log[i])\n\t// }\n\t// for i := range rf.matchIndex {\n\t// \tDPrintf(\"server[%d]'s matchindex is %v\", i, rf.matchIndex[i])\n\t// }\n\t// Check\n\tN = Min(N, rf.getLastIndex())\n\n\tif N > rf.commitIndex && rf.log[N].LogTerm == rf.currentTerm && rf.state == LEADER {\n\t\trf.commitIndex = N\n\t\t// DPrintf(\"updateLastCommit from server[%d]\", rf.me)\n\t\trf.notifyApplyCh <- struct{}{}\n\n\t}\n\n}", "func (p *Peer) LastPingMicros() int64 {\n\tp.statsMtx.RLock()\n\tlastPingMicros := p.lastPingMicros\n\tp.statsMtx.RUnlock()\n\n\treturn lastPingMicros\n}", "func (db *DB) SetLastPulseAsLightMaterial(ctx context.Context, pulsenum core.PulseNumber) error {\n\treturn db.Update(ctx, func(tx *TransactionManager) error {\n\t\treturn tx.set(ctx, prefixkey(scopeIDSystem, []byte{sysLastPulseAsLightMaterial}), pulsenum.Bytes())\n\t})\n}", "func (rf *Raft) UpdateLastApplied() {\n\t////fmt.Print(\"update the last applied index for peer %d\\n\", rf.me)\n\tfor rf.commitIndex > rf.lastApplied {\n\t\trf.lastApplied += 1\n\t\tlog := rf.logEntries[rf.lastApplied]\n\t\tapplyMsg := ApplyMsg{\n\t\t\tCommandValid: true,\n\t\t\tCommand: log.Command,\n\t\t\tCommandIndex: rf.lastApplied,\n\t\t}\n\t\trf.applyCh <- applyMsg\n\t}\n}", "func (x *x509Handler) update(u *workload.X509SVIDResponse) {\n\tx.mtx.Lock()\n\tdefer x.mtx.Unlock()\n\n\tif reflect.DeepEqual(u, x.latest) {\n\t\treturn\n\t}\n\n\tx.latest = u\n\n\t// Don't block if the channel is full\n\tselect {\n\tcase x.changes <- struct{}{}:\n\t\tbreak\n\tdefault:\n\t\tbreak\n\t}\n}", "func (ch Channel) PolyAftertouch(key, pressure uint8) []byte {\n\treturn channelMessage2(ch.Index(), 10, key, pressure)\n}", "func (ps pulseSlave) Pulse(p syncosc.Pulse) error {\n\tfmt.Printf(\"%d\\n\", p.Count)\n\treturn nil\n}", "func (s *Storage) CompletePulse(pulseNumber int64) error {\n\ttimer := prometheus.NewTimer(CompletePulseDuration)\n\tdefer timer.ObserveDuration()\n\treturn s.db.Transaction(func(tx *gorm.DB) error {\n\t\tpulse := models.Pulse{PulseNumber: pulseNumber}\n\t\tupdate := tx.Model(&pulse).Update(models.Pulse{IsComplete: true})\n\t\tif update.Error != nil {\n\t\t\treturn errors.Wrap(update.Error, \"error while updating pulse completeness\")\n\t\t}\n\t\trowsAffected := update.RowsAffected\n\t\tif rowsAffected == 0 {\n\t\t\treturn errors.Errorf(\"try to complete not existing pulse with number %d\", pulseNumber)\n\t\t}\n\t\tif rowsAffected != 1 {\n\t\t\treturn errors.Errorf(\"several rows were affected by update for pulse with number %d to complete, it was not expected\", pulseNumber)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (m *MockRemotePeer) UpdateLastNotice(blkHash types.BlockID, blkNumber types.BlockNo) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdateLastNotice\", blkHash, blkNumber)\n}", "func TrackStreams() {\n // Sleep until the time is a multiple of the refresh period\n now := time.Now()\n wakeUpTime := now.Truncate(config.Timing.Period).Add(config.Timing.Period)\n fmt.Print(\"Waiting...\")\n time.Sleep(wakeUpTime.Sub(now))\n fmt.Println(\"Go\")\n\n // Start periodic updates\n ticker := time.NewTicker(config.Timing.Period)\n Update() // Update immediately, since ticker waits for next interval\n for {\n <-ticker.C\n Update()\n }\n}", "func (c *Core) restoreLatestSync() error {\n\t// Load all pins from the datastore.\n\tq := query.Query{\n\t\tPrefix: SyncPrefix,\n\t}\n\tresults, err := c.DS.Query(context.Background(), q)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer results.Close()\n\n\tvar count int\n\tfor r := range results.Next() {\n\t\tif r.Error != nil {\n\t\t\treturn fmt.Errorf(\"cannot read latest syncs: %w\", r.Error)\n\t\t}\n\t\tent := r.Entry\n\t\t_, lastCid, err := cid.CidFromBytes(ent.Value)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Failed to decode latest sync CID\", \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif lastCid == cid.Undef {\n\t\t\tcontinue\n\t\t}\n\t\tpeerID, err := peer.Decode(strings.TrimPrefix(ent.Key, SyncPrefix))\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Failed to decode peer ID of latest sync\", \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = c.LS.SetLatestSync(peerID, lastCid)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Failed to set latest sync\", \"err\", err, \"peer\", peerID)\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Debugw(\"Set latest sync\", \"provider\", peerID, \"cid\", lastCid)\n\t\tcount++\n\t}\n\tlogger.Infow(\"Loaded latest sync for providers\", \"count\", count)\n\treturn nil\n}", "func (tk *timekeeper) updateSyncCount(cmd Message, ts Timestamp) {\n\n\tstreamId := cmd.(*MsgStream).GetStreamId()\n\tmeta := cmd.(*MsgStream).GetMutationMeta()\n\n\tbucketNewTsReqd := tk.streamBucketNewTsReqdMap[streamId]\n\tbucketFlushInProgressMap := tk.streamBucketFlushInProgressMap[streamId]\n\tbucketTsListMap := tk.streamBucketTsListMap[streamId]\n\tbucketFlushEnabledMap := tk.streamBucketFlushEnabledMap[streamId]\n\tbucketSyncCountMap := tk.streamBucketSyncCountMap[streamId]\n\n\t//update sync count for this bucket\n\tif syncCount, ok := (*bucketSyncCountMap)[meta.bucket]; ok {\n\t\tsyncCount++\n\t\tif syncCount >= SYNC_COUNT_TS_TRIGGER &&\n\t\t\t(*bucketNewTsReqd)[meta.bucket] == true {\n\t\t\t//generate new stability timestamp\n\t\t\tcommon.Debugf(\"Timekeeper::handleSync \\n\\tGenerating new Stability \"+\n\t\t\t\t\"TS: %v Bucket: %v Stream: %v. SyncCount: %v\", ts,\n\t\t\t\tmeta.bucket, streamId, syncCount)\n\n\t\t\tnewTs := CopyTimestamp(ts)\n\t\t\ttsList := (*bucketTsListMap)[meta.bucket]\n\n\t\t\t//if there is no flush already in progress for this bucket\n\t\t\t//no pending TS in list and flush is not disabled, send new TS\n\t\t\tif (*bucketFlushInProgressMap)[meta.bucket] == false &&\n\t\t\t\t(*bucketFlushEnabledMap)[meta.bucket] == true &&\n\t\t\t\ttsList.Len() == 0 {\n\t\t\t\tgo tk.sendNewStabilityTS(newTs, meta.bucket, streamId)\n\t\t\t} else {\n\t\t\t\t//store the ts in list\n\t\t\t\tcommon.Debugf(\"Timekeeper::handleSync \\n\\tAdding TS: %v to Pending \"+\n\t\t\t\t\t\"List for Bucket: %v Stream: %v.\", ts, meta.bucket, streamId)\n\t\t\t\ttsList.PushBack(newTs)\n\t\t\t}\n\t\t\t(*bucketSyncCountMap)[meta.bucket] = 0\n\t\t\t(*bucketNewTsReqd)[meta.bucket] = false\n\t\t} else {\n\t\t\tcommon.Tracef(\"Timekeeper::handleSync \\n\\tUpdating Sync Count for Bucket: %v \"+\n\t\t\t\t\"Stream: %v. SyncCount: %v.\", meta.bucket, streamId, syncCount)\n\t\t\t//update only if its less than trigger count, otherwise it makes no\n\t\t\t//difference. On long running systems, syncCount may overflow otherwise\n\t\t\tif syncCount < SYNC_COUNT_TS_TRIGGER {\n\t\t\t\t(*bucketSyncCountMap)[meta.bucket] = syncCount\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//add a new counter for this bucket\n\t\tcommon.Debugf(\"Timekeeper::handleSync \\n\\tAdding new Sync Count for Bucket: %v \"+\n\t\t\t\"Stream: %v. SyncCount: %v.\", meta.bucket, streamId, syncCount)\n\t\t(*bucketSyncCountMap)[meta.bucket] = 1\n\t}\n}", "func (s *followerReplication) setLastContact() {\n\ts.lastContactLock.Lock()\n\ts.lastContact = time.Now()\n\ts.lastContactLock.Unlock()\n}", "func (m *MockStreamFlowController) UpdateHighestReceived(arg0 protocol.ByteCount, arg1 bool) error {\n\tret := m.ctrl.Call(m, \"UpdateHighestReceived\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *PulseManager) Current() (*core.Pulse, error) {\n\tpulseNum := m.db.GetCurrentPulse()\n\tentropy, err := m.db.GetEntropy(pulseNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpulse := core.Pulse{\n\t\tPulseNumber: pulseNum,\n\t\tEntropy: *entropy,\n\t}\n\treturn &pulse, nil\n}", "func (kv *ShardKV) tick() {\n DPrintf(\"Server %s called tick function! Current max_config_in_log is %d\", kv.id, kv.max_config_in_log)\n kv.mu.Lock()\n defer kv.mu.Unlock()\n\n new_config := kv.sm.Query(-1)\n kv.max_config_in_log = int(math.Max(float64(kv.max_config_in_log), float64(kv.curr_config.Num)))\n if new_config.Num > kv.max_config_in_log { // change this to kv.max_config_in_log\n DPrintf2(\"Server %s Configuration is old! Putting configs from %d to %d in log\", kv.id, kv.max_config_in_log +1, new_config.Num)\n for config_num := kv.max_config_in_log +1; config_num <= new_config.Num; config_num++{\n kv.max_config_in_log = config_num\n kv.startReconfiguration(kv.sm.Query(config_num))\n } \n }\n // DPrintf(\"Server %s ending tick function\", kv.id)\n}", "func (m *DomainMonitor) Update() {\n\tm.mutex.Lock()\n\tif !m.closed && m.instance != nil {\n\t\tm.instance.Poll()\n\t}\n\tm.mutex.Unlock()\n}", "func (o *Wireless) SetLastSeen(v float32) {\n\to.LastSeen = &v\n}", "func (sm *ShardMaster) update() {\n\tvar noop Op\n\tnoop.ProposedConfig.Num = 0\n\t// Concatenate first 16 digits of current time with\n\t// first 3 digits of sm.me\n\t// Using 3 digits of sm.me allows for a thousand peers\n\t// Using 16 digits of the time means it won't repeat for about 115 days\n\t// Using both time and \"me\" means it's probably unique\n\t// Using 19 digits means it will fit in a uint64\n\ttimeDigits := uint64(time.Now().UnixNano() % 10000000000000000)\n\tmeDigits := uint64(sm.me % 1000)\n\tnoop.ID = timeDigits*1000 + meDigits\n\n\tupdated := false\n\tfor !updated && !sm.dead {\n\t\tsm.px.Start(sm.maxSequenceCommitted+1, noop)\n\t\t// Wait until its Status is decided\n\t\tdecided := false\n\t\tvar decidedValue interface{}\n\t\ttoWait := 25 * time.Millisecond\n\t\tfor !decided && !sm.dead {\n\t\t\tdecided, decidedValue = sm.px.Status(sm.maxSequenceCommitted + 1)\n\t\t\tif !decided {\n\t\t\t\ttime.Sleep(toWait)\n\t\t\t\t//if toWait < 2*time.Second {\n\t\t\t\t//\ttoWait *= 2\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\n\t\tif sm.dead {\n\t\t\tbreak\n\t\t}\n\n\t\t// Get the decided configuration for this sequence\n\t\tdecidedConfig := decidedValue.(Op).ProposedConfig\n\t\t// If the decided value has the chosen unique ID, ours was accepted and we are updated\n\t\t// Otherwise, store decided configuration (if it's not another no-op)\n\t\tif decidedValue.(Op).ID == noop.ID {\n\t\t\tupdated = true\n\t\t} else {\n\t\t\tif decidedConfig.Num > 0 {\n\t\t\t\tsm.addConfig(decidedConfig)\n\t\t\t}\n\t\t}\n\t\tsm.maxSequenceCommitted++\n\t}\n\tsm.px.Done(sm.maxSequenceCommitted)\n}", "func (d *Decoder) Pulse() Pulse {\n\tvar p pulse\n\tfor {\n\t\tp = <-d.c\n\t\tif p.sec == 0 {\n\t\t\td.decodeDate(p.l, uint32(p.h))\n\t\t\tbreak\n\t\t}\n\t\tif d.date.Sec >= 0 || p.sec < 0 {\n\t\t\td.date.Sec = p.sec\n\t\t\tbreak\n\t\t}\n\t}\n\treturn Pulse{d.date, p.stamp}\n}", "func (h *Handler) Sync(to []*key.Identity) (*Beacon, error) {\n\th.Lock()\n\th.syncing = true\n\th.Unlock()\n\tdefer func() {\n\t\th.Lock()\n\t\th.syncing = false\n\t\th.Unlock()\n\t}()\n\tvar nextRound uint64\n\tvar nextTime int64\n\tvar err error\n\tvar lastBeacon *Beacon\n\tlastBeacon, err = h.store.Last()\n\tif err == ErrNoBeaconSaved {\n\t\treturn nil, errors.New(\"no genesis block stored. BUG\")\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnextRound, nextTime = NextRound(h.conf.Clock.Now().Unix(), h.conf.Group.Period, h.conf.Group.GenesisTime)\n\tif lastBeacon.Round+1 == nextRound {\n\t\t// next round will build on the one we have - no need to sync\n\t\treturn lastBeacon, nil\n\t}\n\t// Reason to try multiple times is when syncing, we might leave the sync\n\t// after the targeted time. It shouldn't happen though often.\n\tfor trial := 0; trial < SyncRetrial; trial++ {\n\t\t// there is a gap - we need to sync with other peers\n\t\tlastBeacon, err := h.syncFrom(to, lastBeacon)\n\t\tif err != nil {\n\t\t\th.l.Error(\"sync\", \"failed\", \"from\", lastBeacon.Round)\n\t\t}\n\t\tif lastBeacon != nil {\n\t\t\tnextRound, nextTime = NextRound(h.conf.Clock.Now().Unix(), h.conf.Group.Period, h.conf.Group.GenesisTime)\n\t\t\tif lastBeacon.Round+1 == nextRound {\n\t\t\t\t// next round will build on the one we have - no need to sync\n\t\t\t\th.l.Debug(\"sync\", \"done\", \"upto\", lastBeacon.Round, \"next_time\", nextTime)\n\t\t\t\treturn lastBeacon, nil\n\t\t\t}\n\t\t\th.l.Debug(\"sync\", \"incomplete\", \"want\", nextRound-1, \"has\", lastBeacon.Round)\n\t\t} else {\n\t\t\th.l.Error(\"after_sync\", \"nil_beacon\")\n\t\t}\n\t\th.l.Debug(\"sync_incomplete\", \"try_again\", fmt.Sprintf(\"%d/%d\", trial, SyncRetrial))\n\t\t//h.conf.Clock.Sleep(SyncRetrialWait)\n\t}\n\th.l.Error(\"sync\", \"failed\", \"network_down_or_BUG\")\n\treturn lastBeacon, errors.New(\"impossible to sync to current round: network is down?\")\n}", "func (o *ObservedDataType) SetLastObserved(t interface{}) error {\n\tts, _ := timestamp.ToString(t, \"micro\")\n\to.LastObserved = ts\n\treturn nil\n}", "func updateLastSeen(id string) {\n\tnow := time.Now()\n\n\t/* Make sure we have a Implant for this ID */\n\tIMPLANTS.ContainsOrAdd(id, NewImplant(id))\n\n\t/* Get the Implant to update */\n\tv, ok := IMPLANTS.Get(id)\n\tif !ok {\n\t\tlog.Printf(\"[ID-%v] Forgotten too fast\", id)\n\t\treturn\n\t}\n\ti, ok := v.(*Implant)\n\tif !ok {\n\t\tlog.Panicf(\"wrong type of implant: %T\", v)\n\t}\n\n\ti.l.Lock()\n\tdefer i.l.Unlock()\n\t/* Log if this is the first time we've seen this implant */\n\tif i.seen.IsZero() {\n\t\tlog.Printf(\"[ID-%v] Hello.\", id)\n\t}\n\n\t/* Update timestamp if the one we have is newer */\n\tif now.After(i.seen) {\n\t\ti.seen = now\n\t}\n}", "func getLastKnownPosition(txn *badger.Txn, pn insolar.PulseNumber) (uint32, error) {\n\tkey := lastKnownRecordPositionKey{pn: pn}\n\n\tfullKey := append(key.Scope().Bytes(), key.ID()...)\n\n\titem, err := txn.Get(fullKey)\n\tif err != nil {\n\t\tif err == badger.ErrKeyNotFound {\n\t\t\treturn 0, ErrNotFound\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tbuff, err := item.ValueCopy(nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn binary.BigEndian.Uint32(buff), nil\n}", "func (self *IoStatsBuilder) Update(current map[int]*IoAmount, now time.Time) {\n\tseconds := now.Sub(self.lastMeasurement).Seconds()\n\tvar total IoAmount\n\tfor pid, amt := range current {\n\t\ttotal.Increment(amt)\n\t\tdelete(self.lastPids, pid)\n\t}\n\tfor _, amt := range self.lastPids {\n\t\tself.deadUsage.Increment(amt)\n\t}\n\ttotal.Increment(&self.deadUsage)\n\tself.lastPids = current\n\tself.lastMeasurement = now\n\tdiff := self.Total.update(&total)\n\tif seconds > 0 {\n\t\trate := diff.rate(seconds)\n\t\tself.RateMax.TakeMax(rate)\n\t\trate.weightSquared(seconds)\n\t\tself.weightedSumSquared.Increment(rate)\n\t\tif t := now.Sub(self.start).Seconds(); t > 0 {\n\t\t\tself.RateDev = self.weightedSumSquared.computeStdDev(\n\t\t\t\t&self.Total, t)\n\t\t}\n\t}\n}", "func (t *AudioPlayer) Update(a *app.App, deltaTime time.Duration) {\n\n\tif time.Now().Sub(t.lastUpdate) < 100*time.Millisecond {\n\t\treturn\n\t}\n\tt.pc1.UpdateTime()\n\tt.pc2.UpdateTime()\n\tt.pc3.UpdateTime()\n\tt.pc4.UpdateTime()\n\tt.lastUpdate = time.Now()\n}", "func (bot *ExchangeBot) signalUpdate(token string) {\n\tvar signal *UpdateSignal\n\tif bot.IsFailed() {\n\t\tsignal = &UpdateSignal{\n\t\t\tToken: token,\n\t\t\tState: nil,\n\t\t\tBytes: []byte{},\n\t\t}\n\t} else {\n\t\tsignal = &UpdateSignal{\n\t\t\tToken: token,\n\t\t\tState: bot.State(),\n\t\t\tBytes: bot.StateBytes(),\n\t\t}\n\t}\n\tfor _, ch := range bot.updateChans {\n\t\tselect {\n\t\tcase ch <- signal:\n\t\tdefault:\n\t\t}\n\t}\n}", "func (c *Core) watchSyncFinished(onSyncFin <-chan golegs.SyncFinished) {\n\tfor syncFin := range onSyncFin {\n\t\tif _, err := c.PS.Get(context.Background(), syncFin.Cid); err != nil {\n\t\t\t// skip if data is not stored\n\t\t\tcontinue\n\t\t}\n\n\t\texist, _ := c.checkCidCached(syncFin.Cid)\n\t\tif exist {\n\t\t\t// seen cid before, skip\n\t\t\tcontinue\n\t\t}\n\n\t\tmetrics.Counter(context.Background(), metrics.ProviderNotificationCount, syncFin.PeerID.String(), 1)()\n\n\t\t// Persist the latest sync\n\t\terr := c.DS.Put(context.Background(), datastore.NewKey(SyncPrefix+syncFin.PeerID.String()), syncFin.Cid.Bytes())\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Error persisting latest sync\", \"err\", err, \"peer\", syncFin.PeerID)\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Debugw(\"Persisted latest sync\", \"peer\", syncFin.PeerID, \"cid\", syncFin.Cid)\n\t}\n\tclose(c.watchDone)\n}", "func (huo *HistorytakingUpdateOne) SetPulse(i int) *HistorytakingUpdateOne {\n\thuo.mutation.ResetPulse()\n\thuo.mutation.SetPulse(i)\n\treturn huo\n}", "func (q *SimpleQueue) SubscriberSetLastRead(ctx context.Context, user cn.CapUser,\n\tsubscriber string, id int64,\n\tsaveMode cn.SaveMode) (err *mft.Error) {\n\n\tif !q.Subscribers.mx.TryLock(ctx) {\n\t\treturn GenerateError(10032000)\n\t}\n\n\tif q.UseDefaultSaveModeForce {\n\t\tsaveMode = q.DefaultSaveMode\n\t} else if saveMode == cn.QueueSetDefaultMode {\n\t\tsaveMode = q.DefaultSaveMode\n\t}\n\n\tif saveMode != cn.NotSaveSaveMode &&\n\t\tsaveMode != cn.SaveImmediatelySaveMode &&\n\t\tsaveMode != cn.SaveMarkSaveMode &&\n\t\tsaveMode != cn.SaveWaitSaveMode {\n\t\treturn GenerateError(10032002, saveMode)\n\t}\n\n\tisChanged := false\n\tvar chWait chan bool\n\tv, ok := q.Subscribers.SubscribersInfo[subscriber]\n\tif !ok && id != 0 {\n\t\tv = &SimpleQueueSubscriberInfo{\n\t\t\tStartDt: time.Now(),\n\t\t\tLastID: id,\n\t\t\tLastDt: time.Now(),\n\t\t}\n\t\tq.Subscribers.SubscribersInfo[subscriber] = v\n\n\t\tisChanged = true\n\t} else if v.LastID < id && id != 0 {\n\t\tv.LastID = id\n\t\tv.LastDt = time.Now()\n\n\t\tisChanged = true\n\t} else if ok && id == 0 {\n\t\tdelete(q.Subscribers.SubscribersInfo, subscriber)\n\t}\n\n\tif !isChanged {\n\t\tq.Subscribers.mx.Unlock()\n\t\treturn nil\n\t}\n\n\tif saveMode == cn.SaveWaitSaveMode {\n\t\tchWait = make(chan bool, 1)\n\t\tq.Subscribers.SaveWait = append(q.Subscribers.SaveWait, chWait)\n\t}\n\n\tif saveMode == cn.SaveMarkSaveMode {\n\t\tq.Subscribers.ChangesRv = q.IDGenerator.RvGetPart()\n\t}\n\n\tq.Subscribers.mx.Unlock()\n\n\tif saveMode == cn.SaveImmediatelySaveMode {\n\t\terr = q.SaveSubscribers(ctx, user)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tif saveMode == cn.SaveWaitSaveMode {\n\t\tif chWait != nil {\n\t\t\tselect {\n\t\t\tcase <-chWait:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn GenerateError(10032001)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p *Participant) newSignedUpdate() {\n\t// Check that this function was not called by error.\n\tif p.engine.SiblingIndex() > state.QuorumSize {\n\t\tp.log.Error(\"error call on newSignedUpdate\")\n\t\treturn\n\t}\n\n\t// Generate the entropy for this round of random numbers.\n\tvar entropy state.Entropy\n\tcopy(entropy[:], siacrypto.RandomByteSlice(state.EntropyVolume))\n\n\tsp, err := p.engine.BuildStorageProof()\n\tif err == state.ErrEmptyQuorum {\n\t\tp.log.Debug(\"could not build storage proof:\", err)\n\t} else if err != nil {\n\t\tp.log.Error(sialog.AddCtx(err, \"failed to construct storage proof\"))\n\t\treturn\n\t}\n\thb := delta.Heartbeat{\n\t\tParentBlock: p.engine.Metadata().ParentBlock,\n\t\tEntropy: entropy,\n\t\tStorageProof: sp,\n\t}\n\n\tsignature, err := p.secretKey.SignObject(hb)\n\tif err != nil {\n\t\tp.log.Error(\"failed to sign heartbeat:\", err)\n\t\treturn\n\t}\n\n\t// Create the update with the heartbeat and heartbeat signature.\n\tp.engineLock.RLock()\n\tupdate := Update{\n\t\tHeight: p.engine.Metadata().Height,\n\t\tHeartbeat: hb,\n\t\tHeartbeatSignature: signature,\n\t}\n\tp.engineLock.RUnlock()\n\n\t// Attach all of the script inputs to the update, clearing the list of\n\t// script inputs in the process.\n\tp.updatesLock.Lock()\n\tupdate.ScriptInputs = p.scriptInputs\n\tp.scriptInputs = nil\n\tp.updatesLock.Unlock()\n\n\t// Attach all of the update advancements to the signed heartbeat and sign\n\t// them.\n\tp.updatesLock.Lock()\n\tupdate.UpdateAdvancements = p.updateAdvancements\n\tp.updateAdvancements = nil\n\tfor _, ua := range update.UpdateAdvancements {\n\t\tuas, err := p.secretKey.SignObject(ua)\n\t\tif err != nil {\n\t\t\t// log an error\n\t\t\tcontinue\n\t\t}\n\t\tupdate.AdvancementSignatures = append(update.AdvancementSignatures, uas)\n\t}\n\tp.updatesLock.Unlock()\n\n\t// Sign the update and create a SignedUpdate object with ourselves as the\n\t// first signatory.\n\tupdateSignature, err := p.secretKey.SignObject(update)\n\tsu := SignedUpdate{\n\t\tUpdate: update,\n\t\tSignatories: make([]byte, 1),\n\t\tSignatures: make([]siacrypto.Signature, 1),\n\t}\n\tsu.Signatories[0] = p.engine.SiblingIndex()\n\tsu.Signatures[0] = updateSignature\n\n\t// Add the heartbeat to our own heartbeat map.\n\tupdateHash, err := siacrypto.HashObject(update)\n\tif err != nil {\n\t\tp.log.Error(\"failed to hash update:\", err)\n\t\treturn\n\t}\n\tp.updatesLock.Lock()\n\tp.updates[p.engine.SiblingIndex()][updateHash] = update\n\tp.updatesLock.Unlock()\n\n\t// Broadcast the SignedUpdate to the network.\n\tp.broadcast(network.Message{\n\t\tProc: \"Participant.HandleSignedUpdate\",\n\t\tArgs: su,\n\t})\n}", "func LastUpdateTime(t time.Time) Precondition { return lastUpdateTime(t) }", "func (c *Connection) PongReceiver() {\n\tc.lastResponse = time.Now()\n\tc.logger.Debugf(\"\\n[Connection][PongReceiver] Actualizacion de ultima respuesta %s\", c.lastResponse.Format(time.RFC3339))\n}", "func (t *Pitch) Update(a *app.App, deltaTime time.Duration) {}", "func (t *Pitch) Update(a *app.App, deltaTime time.Duration) {}", "func (s *Storage) GetPulse(pulseNumber int64) (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetPulseDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulse models.Pulse\n\terr := s.db.Where(\"pulse_number = ?\", pulseNumber).First(&pulse).Error\n\tif err != nil {\n\t\treturn pulse, err\n\t}\n\n\tpulse = s.updateNextPulse(pulse)\n\tpulse = s.updatePrevPulse(pulse)\n\n\treturn pulse, err\n}", "func defaultOr(latestPoll *metav1.Time, pollingInterval time.Duration, creationTimestamp time.Time, now time.Time) time.Duration {\n\tif latestPoll.IsZero() {\n\t\tlatestPoll = &metav1.Time{Time: creationTimestamp}\n\t}\n\n\tremaining := latestPoll.Add(pollingInterval).Sub(now)\n\t// sync ahead of the default interval in the case where now + default sync is after the last sync plus the interval\n\tif remaining < queueinformer.DefaultResyncPeriod {\n\t\treturn remaining\n\t}\n\t// return the default sync period otherwise: the next sync cycle will check again\n\treturn queueinformer.DefaultResyncPeriod\n}", "func (NilUGauge) Update(v uint64) {}", "func (tr *Tracker) SetLastSync(t time.Time) {\n\ttr.status.LastUpdated.LastSync = t\n}", "func (u updates) Last(l UpdateLabels) prometheus.Gauge {\n\treturn u.last.WithLabelValues(l.Values()...)\n}", "func Update () {\n // Compute the current time rounded to the interval\n roundTime := time.Now().Round(config.Timing.Period)\n unixTimeString := strconv.FormatInt(roundTime.Unix(), 10);\n\n // Query Twitch for each filter's streams, and assemble a map of unique\n // streams along with all filters which found them\n taggedStreams := make(map[string]*taggedStream)\n filters := database.GetAllFilters()\n for _, filter := range filters {\n // Make appropriate Twitch query\n var sr *twitchapi.GetStreamsResponse\n if filter.QueryType == database.QueryTypeStreams {\n sr = twitchapi.AllStreams(filter.QueryParam)\n }\n //} else if filter.QueryType == database.QueryTypeFollows {\n // sr = twitchapi.FollowedStreams(filter.QueryParam)\n //}\n // Assimilate all recieved streams into our tagged stream map\n for _, s := range sr.Streams {\n id := s.ChannelId\n if _, seen := taggedStreams[id]; !seen { // Idiom to check if in map\n taggedStreams[id] = &taggedStream{Stream:s}\n }\n taggedStreams[id].AppendFilter(filter.ID)\n }\n database.UpdateFilter(filter.ID, roundTime)\n }\n\n // For each (stream, filters) pair, grab and save a snapshot to the DB\n for _, sf := range taggedStreams {\n stream := sf.Stream\n channelName := stream.ChannelDisplayName\n status := stream.Status\n fmt.Printf(\"(%v) %v: %v\\n\", len(sf.FilterIds), channelName, status)\n\n // Query Twitch for the channel's most recent (current) archive video ID\n archive := twitchapi.ChannelRecentArchive(stream.ChannelId)\n\n // If this snapshot doesn't correspond to the most recent archive, then\n // either the streamer has disabled archiving, the archive somehow isn't\n // accessible yet, or something else. So, store no VOD for this thumb.\n vodID := \"\"\n vodSeconds := 0\n vodTime := roundTime\n if archive != nil {\n if archive.Broadcast_Id == stream.Id {\n vodID = archive.Id\n vodSeconds = int(roundTime.Sub(archive.Created_At_Time).Seconds())\n //vodTime = archive.Created_At_Time\n } else {\n fmt.Printf(\"recent archive is not current stream\\n\")\n }\n } else {\n fmt.Printf(\"recent archive was nil\\n\")\n }\n\n // Download stream preview image from Twitch\n imagePath := config.Path.ImagesRelative + \"/\" +\n stream.ChannelName + \"_\" + unixTimeString + \".jpg\"\n imageDLPath := config.Path.Root + imagePath\n imageUrl := stream.Preview\n DownloadImage(imageUrl, imageDLPath)\n\n // Finally, store new info for this stream in the DB\n database.AddThumbToDB(\n roundTime, stream.ChannelName, stream.ChannelDisplayName,\n vodSeconds, vodID, imagePath, vodTime, stream.Status,\n stream.Viewers, sf.FilterIds)\n\n // Query Twitch for the channel's recent clips.\n // Commented out 2022-02-14 due to helix API migration and we don't even\n // or prune these clips anyways.\n //cr := twitchapi.TopClipsDay(stream.ChannelName)\n //for _, clip := range cr.Clips {\n // database.AddClipToDB(clip.TrackingId, clip.Created_At_Time,\n // clip.Thumbnails.Small, clip.Url, stream.ChannelName)\n //}\n }\n\n // Delete old streams (and their thumbs, follows, image files) from the DB\n database.PruneOldStreams(roundTime)\n\n RegenerateFilterPages()\n\n // TODO: Occasionally check for \"stray\" data:\n // (Also perform this check on app startup)\n // Follows whose stream or filter no longer exists\n // Have to check for each one.\n // Thumbs whose stream no longer exists\n // Total of streams NumThumbs != # thumbs\n // Image files whose thumb no longer exists\n // # image files != # thumbs\n\n fmt.Printf(\"update finish\\n\")\n /*fmt.Printf(\"%v deleted\\n\", numDeleted)\n fmt.Printf(\"%v thumbs \\n\", database.NumThumbs())\n fmt.Printf(\"%v jpg files\\n\", NumFilesInDir(config.Path.Images))\n fmt.Printf(\"%v distinct channels\\n\", len(database.DistinctChannels()))*/\n}", "func (vs *ViewServer) tick() {\n\t// Your code here.\n\tvs.mu.Lock()\n\tif vs.view.Viewnum == vs.primaryAck {\n\t\tcurrentTime := time.Now()\n\t\t// primary liveness check\n\t\tif vs.view.Primary != \"\" {\n\t\t\tprimaryLastPingTime := vs.pingTrack[vs.view.Primary]\n\t\t\t//log.Printf(\"[viewserver]tick, primary last ping: %+v\", primaryLastPingTime)\n\t\t\tif primaryLastPingTime.Add(PingInterval * DeadPings).Before(currentTime) {\n\t\t\t\tvs.view.Primary = \"\"\n\t\t\t}\n\t\t}\n\n\t\t// backup liveness check\n\t\tif vs.view.Backup != \"\" {\n\t\t\tbackupLastPingTime := vs.pingTrack[vs.view.Backup]\n\t\t\t//log.Printf(\"[viewserver]tick, backup last ping: %+v\", backupLastPingTime)\n\t\t\tif backupLastPingTime.Add(PingInterval * DeadPings).Before(currentTime) {\n\t\t\t\tvs.view.Backup = \"\"\n\t\t\t}\n\t\t}\n\n\t\tif vs.view.Primary == \"\" && vs.view.Backup != \"\" {\n\t\t\t//promote backup to primary\n\t\t\tvs.view.Primary = vs.view.Backup\n\t\t\tvs.view.Backup = \"\"\n\t\t\tvs.view.Viewnum += 1\n\t\t\tlog.Printf(\"[viewserver]tick, promote backup to primary, primary: %s\", vs.view.Primary)\n\t\t}\n\t}\n\tvs.mu.Unlock()\n}", "func (mmUpdate *StorageMock) UpdateAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmUpdate.afterUpdateCounter)\n}", "func waitForStatsChange(b IRolloutBalancer, rolloutType string, wantedLen int) {\n\tdeadline := time.After(500 * time.Millisecond)\n\tfor {\n\t\tstats := b.Stats(StatsOptions{RolloutType: rolloutType})\n\t\tif len(stats) == wantedLen {\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase <-deadline:\n\t\t\tpanic(fmt.Errorf(\"stats not changed! Last stats: %#v\", stats))\n\t\tcase <-time.After(1 * time.Millisecond):\n\t\t\t// poll stats\n\t\t}\n\t}\n}", "func (r *Raft) heartbeat(replication *followerReplication, stopCh chan struct{}) {\n\tvar failures uint64\n\treq := pb.AppendEntriesRequest{\n\t\tTerm: replication.currentTerm,\n\t\tLeader: r.transport.EncodePeer(r.localID, r.localAddr),\n\t}\n\tvar resp pb.AppendEntriesResponse\n\tfor {\n\t\t// Wait for the next heartbeat interval or forced notify\n\t\tselect {\n\t\tcase <-replication.notifyCh:\n\t\tcase <-randomTimeout(r.config().HeartbeatTimeout / 10): // [100ms, 200ms]\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\t}\n\n\t\treplication.peerLock.RLock()\n\t\tpeer := replication.peer\n\t\treplication.peerLock.RUnlock()\n\n\t\tif err := r.transport.AppendEntries(peer.ID, peer.Address, &req, &resp); err != nil {\n\t\t\tklog.Errorf(fmt.Sprintf(\"failed to heartbeat from %s/%s to %s/%s err:%v\",\n\t\t\t\tr.localID, r.localAddr, peer.ID, peer.Address, err))\n\t\t\tr.observe(FailedHeartbeatObservation{PeerID: peer.ID, LastContact: replication.LastContact()})\n\n\t\t\t// backoff\n\t\t\tfailures++\n\t\t\tselect {\n\t\t\tcase <-time.After(backoff(failureWait, failures, maxFailureScale)):\n\t\t\tcase <-stopCh:\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tif failures > 0 {\n\t\t\t\tr.observe(ResumedHeartbeatObservation{PeerID: peer.ID})\n\t\t\t}\n\n\t\t\treplication.setLastContact()\n\t\t\tfailures = 0\n\t\t\treplication.notifyAll(resp.Success)\n\t\t}\n\t}\n}", "func (sv *Server) maybeScheduleReSync(note pushtypes.PushNote, ref string, fromBeginning bool) error {\n\n\trepoName := note.GetRepoName()\n\tlocalRefHash := plumbing2.ZeroHash\n\n\t// Get the local hash of the reference\n\tlocalRef, err := note.GetTargetRepo().Reference(plumbing2.ReferenceName(ref), false)\n\tif err != nil && err != plumbing2.ErrReferenceNotFound {\n\t\treturn err\n\t} else if localRef != nil {\n\t\tlocalRefHash = localRef.Hash()\n\t}\n\n\t// Get the network hash of the reference\n\trepoState := note.GetTargetRepo().GetState()\n\trepoRefHash := plumbing2.ZeroHash\n\tif netRef := repoState.References.Get(ref); !netRef.IsNil() {\n\t\trepoRefHash = plumbing.BytesToHash(netRef.Hash)\n\t}\n\n\t// Check if the note's pushed reference local hash and the network hash match.\n\t// If yes, no resync needs to happen.\n\tif bytes.Equal(localRefHash[:], repoRefHash[:]) {\n\t\tsv.log.Debug(\"Abandon ref resync; local and network state match\", \"Repo\", repoName, \"Ref\", ref)\n\t\treturn nil\n\t}\n\n\t// Get last synchronized\n\trefLastSyncHeight, err := sv.logic.RepoSyncInfoKeeper().GetRefLastSyncHeight(repoName, ref)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the last successful synced reference height equal the last successful synced\n\t// height for the entire repo, it means something unnatural/external messed up\n\t// the repo history. We react by resyncing the reference from the beginning.\n\trepoLastUpdated := repoState.UpdatedAt.UInt64()\n\tif !fromBeginning && refLastSyncHeight == repoLastUpdated {\n\t\trefLastSyncHeight = repoState.CreatedAt.UInt64()\n\t}\n\n\t// If sync from beginning is requested, start from the parent\n\t// repo's time of creation\n\tif fromBeginning {\n\t\trefLastSyncHeight = repoState.CreatedAt.UInt64()\n\t}\n\n\tsv.log.Debug(\"Scheduling reference for resync\", \"Repo\", repoName, \"Ref\", ref)\n\n\t// Add the repo to the refsync watcher\n\tif err := sv.refSyncer.Watch(repoName, ref, refLastSyncHeight, repoLastUpdated); err != nil {\n\t\treturn fmt.Errorf(\"%s: reference is still being resynchronized (try again later)\", ref)\n\t}\n\n\treturn nil\n}", "func (p *rpioPoller) poll() {\npollLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-p.ticker.C:\n\t\t\t// Read pins and handle edge detection\n\t\t\tfor pin, registration := range p.registeredPins {\n\t\t\t\tif pin.EdgeDetected() {\n\t\t\t\t\tgo registration.callback(registration.edge)\n\t\t\t\t}\n\t\t\t}\n\t\tcase newRegistration := <-p.newPin:\n\t\t\t// Add pin registration to pins to poll\n\t\t\tp.registeredPins[newRegistration.pin] = newRegistration\n\t\tcase registrationToRemove := <-p.removePin:\n\t\t\t// Remove pin registration from pins to poll\n\t\t\tdelete(p.registeredPins, registrationToRemove)\n\t\tcase newPollFreq := <-p.newPollFreq:\n\t\t\t// Update the ticker polling frequency\n\t\t\tp.ticker.Reset(newPollFreq)\n\t\tcase <-p.stop:\n\t\t\tbreak pollLoop\n\t\t}\n\t}\n}", "func (m *PacketParserMock) MinimockGetPulsePacketDone() bool {\n\tfor _, e := range m.GetPulsePacketMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.GetPulsePacketMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetPulsePacketCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcGetPulsePacket != nil && mm_atomic.LoadUint64(&m.afterGetPulsePacketCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (f *lightFetcher) checkUpdateStats(p *peer, newEntry *updateStatsEntry) {\n\tnow := mclock.Now()\n\tfp := f.peers[p]\n\tif fp == nil {\n\t\tp.Log().Debug(\"Unknown peer to check update stats\")\n\t\treturn\n\t}\n\n\tif newEntry != nil && fp.firstUpdateStats == nil {\n\t\tfp.firstUpdateStats = newEntry\n\t}\n\tfor fp.firstUpdateStats != nil && fp.firstUpdateStats.time <= now-mclock.AbsTime(blockDelayTimeout) {\n\t\tf.handler.backend.serverPool.adjustBlockDelay(p.poolEntry, blockDelayTimeout)\n\t\tfp.firstUpdateStats = fp.firstUpdateStats.next\n\t}\n\tif fp.confirmedTd != nil {\n\t\tfor fp.firstUpdateStats != nil && fp.firstUpdateStats.td.Cmp(fp.confirmedTd) <= 0 {\n\t\t\tf.handler.backend.serverPool.adjustBlockDelay(p.poolEntry, time.Duration(now-fp.firstUpdateStats.time))\n\t\t\tfp.firstUpdateStats = fp.firstUpdateStats.next\n\t\t}\n\t}\n}", "func (hu *HistorytakingUpdate) SetPulse(i int) *HistorytakingUpdate {\n\thu.mutation.ResetPulse()\n\thu.mutation.SetPulse(i)\n\treturn hu\n}", "func (r *volumeReactor) syncAll() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tfor _, c := range r.claims {\n\t\tr.changedObjects = append(r.changedObjects, c)\n\t}\n\tfor _, v := range r.volumes {\n\t\tr.changedObjects = append(r.changedObjects, v)\n\t}\n\tr.changedSinceLastSync = 0\n}", "func (kv *DisKV) tick() {\n\t// Your code here.\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\tnconfig := kv.sm.Query(-1)\n\tif nconfig.Num > kv.Current.Num {\n\t\tif nconfig.Num > kv.Current.Num+1 {\n\t\t\tnconfig = kv.sm.Query(kv.Current.Num + 1)\n\t\t}\n\t\tkv.reconfigure(nconfig)\n\t} else {\n\t\top := Op{Type: \"Heartbeat\", View: kv.me, Ck: rand.Int63()}\n\t\tkv.Seq++\n\t\tseq := kv.Seq\n\n\t\tkv.px.Start(seq, op)\n\t\txop := kv.getOp(seq)\n\t\tkv.process(xop, seq, 0)\n\t}\n}", "func (pb *PBServer) tick() {\n\tnextView, err := pb.vs.Ping(pb.viewNum)\n\tif err == nil {\n\t\t//log.Printf(\"Server [%s] New View num is [%d], Primary is [%s] \", pb.me, nextView.Viewnum, nextView.Primary)\n\t\tif pb.me == nextView.Primary && pb.backup != nextView.Backup {\n\t\t\targs := new(CopyArgs)\n\t\t\targs.Data = pb.data\n\t\t\targs.HandlResult = pb.handleResult\n\t\t\treply := new(CopyReply)\n\t\t\tcall(nextView.Backup, \"PBServer.Copy\", args, reply)\n\t\t}\n\t\tpb.viewNum = nextView.Viewnum\n\t\tpb.primary = nextView.Primary\n\t\tpb.backup = nextView.Backup\n\t\tpb.pingFail = 0\n\t} else {\n\t\tpb.pingFail += 1\n\t\tif pb.pingFail > viewservice.DeadPings {\n\t\t\tpb.primary = \"\"\n\t\t\tpb.backup = \"\"\n\t\t\tpb.viewNum = 0\n\t\t}\n\t}\n}", "func (mmGetPulsePacket *PacketParserMock) GetPulsePacketAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmGetPulsePacket.afterGetPulsePacketCounter)\n}", "func (vs *ViewServer) tick(){\n\t// Your code here.\n\tvs.mu.Lock()\n\tnow := time.Now()\n\ttimeWindow := DeadPings * PingInterval\n\n\t// check if we can get the primary server\n\tif now.Sub(vs.pingTime[vs.currentView.Primary]) >= timeWindow && vs.primaryACK == true{\n\t\t// primary already ACK currentView -> update view using backup\n\t\tupdate(vs, vs.currentView.Backup, vs.idleServer)\n\t}\n\n\t// check recent pings from backup server\n\tif now.Sub(vs.pingTime[vs.currentView.Backup]) >= timeWindow && vs.backupACK == true{\n\t\t// check if there's an idle server\n\t\tif vs.idleServer != \"\"{\n\t\t\t// use idle server as backup\n\t\t\tupdate(vs, vs.currentView.Primary, vs.idleServer)\n\t\t}\n\t}\n\n\t// check pings from idle server\n\tif now.Sub(vs.pingTime[vs.idleServer]) >= timeWindow{\n\t\tvs.idleServer = \"\"\n\t} else {\n\t\tif vs.primaryACK == true && vs.idleServer != \"\" && vs.currentView.Backup == \"\"{\n\t\t\t// no backup -> use idle server\n\t\t\tupdate(vs, vs.currentView.Primary, vs.idleServer)\n\t\t}\n\t}\n\n\tvs.mu.Unlock()\n}", "func (_m *MockServiceClient) UpdateLastConnected(id string, time int64) error {\n\tret := _m.Called(id, time)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, int64) error); ok {\n\t\tr0 = rf(id, time)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (p *Player) syncPlayerInfo() {\n\tvar pladd []play.PIAddPlayer\n\tvar plrem []play.PIRemovePlayer\n\tvar pllat []play.PIUpdateLatency\n\n\t// check for any players that we already got\n\tfor uid, c := range p.waitingForPlayers {\n\t\tselect {\n\t\tcase _, ok := <-c:\n\t\t\tif ok {\n\t\t\t\t// we are the first to see this change\n\t\t\t\tclose(c)\n\t\t\t}\n\n\t\t\t// we know about this player\n\t\t\tdelete(p.waitingForPlayers, uid)\n\t\t\tp.knownPlayers[uid] = true\n\t\tdefault:\n\t\t\t// not sent yet, ignore\n\t\t}\n\t}\n\n\t// check for any new players\n\tif p.joined {\n\t\tpladd = make([]play.PIAddPlayer, 0, len(players))\n\t\tfor _, p := range players {\n\t\t\tpladd = append(pladd, play.PIAddPlayer{\n\t\t\t\tUUID: p.UUID,\n\t\t\t\tName: p.Username,\n\t\t\t\tGamemode: 0,\n\t\t\t\tPing: int32(p.Ping.Milliseconds()),\n\t\t\t})\n\t\t}\n\t} else {\n\t\t// the player has a list of everyone, only send updates\n\t\tpladd = make([]play.PIAddPlayer, 0, len(newPlayers))\n\t\tplrem = make([]play.PIRemovePlayer, 0, len(leftPlayers))\n\n\t\tfor _, p := range newPlayers {\n\t\t\tpladd = append(pladd, play.PIAddPlayer{\n\t\t\t\tUUID: p.UUID,\n\t\t\t\tName: p.Username,\n\t\t\t\tGamemode: 0,\n\t\t\t\tPing: int32(p.Ping),\n\t\t\t})\n\t\t}\n\n\t\tfor _, p := range leftPlayers {\n\t\t\tplrem = append(plrem, play.PIRemovePlayer{UUID: p.UUID})\n\t\t}\n\t}\n\n\t// update latencies\n\tfor _, p := range players {\n\t\tif p.PingChanged {\n\t\t\tpllat = append(pllat, play.PIUpdateLatency{\n\t\t\t\tUUID: p.UUID,\n\t\t\t\tPing: int32(p.Ping),\n\t\t\t})\n\t\t}\n\t}\n\n\tif len(pladd) > 0 {\n\t\t// insert all the players we are waiting for to\n\t\t// the map\n\t\tdone := make(chan bool)\n\t\tp.SendChan(play.PlayerInfo{ AddPlayer: pladd }, done)\n\t\tfor _, p := range newPlayers {\n\t\t\tp.waitingForPlayers[p.UUID] = done\n\t\t}\n\t}\n\n\tif len(plrem) > 0 {\n\t\tp.Send(play.PlayerInfo{ RemovePlayer: plrem })\n\t}\n\n\tif len(pllat) > 0 {\n\t\tp.Send(play.PlayerInfo{ UpdateLatency: pllat })\n\t}\n}", "func (kcp *KCP) Update() {\n\tcurrentTime := millisecond()\n\tif kcp.updated == 0 {\n\t\tkcp.updated = 1\n\t\tkcp.tsFlush = currentTime\n\t}\n\n\tslap := timediff(currentTime, kcp.tsFlush)\n\tif slap >= 10000 || slap < -10000 {\n\t\tkcp.tsFlush = currentTime\n\t\tslap = 0\n\t}\n\n\tif slap >= 0 {\n\t\tkcp.tsFlush += kcp.interval\n\t\tif timediff(currentTime, kcp.tsFlush) >= 0 {\n\t\t\tkcp.tsFlush = currentTime + kcp.interval\n\t\t}\n\n\t\tkcp.flush()\n\t}\n}", "func (s *Storage) GetSequentialPulse() (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetSequentialPulseDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulses []models.Pulse\n\terr := s.db.Where(\"is_sequential = ?\", true).Order(\"pulse_number desc\").Limit(1).Find(&pulses).Error\n\tif err != nil {\n\t\treturn models.Pulse{}, err\n\t}\n\tif len(pulses) == 0 {\n\t\treturn models.Pulse{}, nil\n\t}\n\treturn pulses[0], err\n}", "func (oc *Operachain) Sync() {\n\tfor {\n\t\t//requestVersion\n\t\ttime.Sleep(time.Second)\n\n\t\tfor _, node := range oc.KnownAddress {\n\t\t\tif node != oc.MyAddress {\n\t\t\t\tpayload := gobEncode(HeightMsg{oc.KnownHeight, oc.MyAddress})\n\t\t\t\treqeust := append(commandToBytes(\"rstBlocks\"), payload...)\n\t\t\t\toc.sendData(node, reqeust)\n\t\t\t}\n\t\t}\n\t}\n}", "func setLastKnownPosition(txn *badger.Txn, pn insolar.PulseNumber, position uint32) error {\n\tlastPositionKey := lastKnownRecordPositionKey{pn: pn}\n\tparsedPosition := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(parsedPosition, position)\n\n\tfullKey := append(lastPositionKey.Scope().Bytes(), lastPositionKey.ID()...)\n\n\treturn txn.Set(fullKey, parsedPosition)\n}", "func (s *Server) timing() {\n\tt := time.Now().Unix()\n\tif t > s.lastPulse {\n\t\ts.lastPulse = t\n\t\tfor _, m := range mobs {\n\t\t\tm.Pulse()\n\t\t}\n\t\tfor _, cl := range s.clients {\n\t\t\tcl.Pulse()\n\t\t}\n\t}\n\tif t > s.nextTick {\n\t\ts.nextTick = t + rand.Int63n(tickLength) + tickLength\n\t\tfor _, m := range mobs {\n\t\t\tm.Tick()\n\t\t}\n\t\tfor _, cl := range s.clients {\n\t\t\tcl.Tick()\n\t\t}\n\t}\n}", "func UpdateRoutine(freq, timeout time.Duration) {\n\tticker := time.NewTicker(freq)\n\t// new request every config.DefaultRequestsTimeout time\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tconfirm := 1\n\t\tfor ; true; <-ticker.C {\n\t\t\t// retrieve the last block\n\t\t\tlastBlockTmp, err := dataCollection.GetLastBlockNumber(timeout)\n\t\t\tif confirm > 0 {\n\t\t\t\tconfirm--\n\t\t\t\twg.Done()\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tatomic.StoreUint64(&lastBlock, lastBlockTmp)\n\t\t}\n\t}()\n\twg.Wait()\n}", "func (mr *MockRemotePeerMockRecorder) UpdateLastNotice(blkHash, blkNumber interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateLastNotice\", reflect.TypeOf((*MockRemotePeer)(nil).UpdateLastNotice), blkHash, blkNumber)\n}", "func (aa *agent) updateCommunicationTime(new time.Time) {\n\t// only update if new time is not in the future, and either the old time is invalid or new time > old time\n\taa.lock.Lock()\n\tdefer aa.lock.Unlock()\n\tif last, err := ptypes.Timestamp(aa.adapter.LastCommunication); !new.After(time.Now()) && (err != nil || new.After(last)) {\n\t\ttimestamp, err := ptypes.TimestampProto(new)\n\t\tif err != nil {\n\t\t\treturn // if the new time cannot be encoded, just ignore it\n\t\t}\n\n\t\taa.adapter.LastCommunication = timestamp\n\t}\n}", "func (b *bucket) updateLongestRun(value uint32) {\n\tcardinalityEstimation := findRun(value) + 1\n\n\tif b.cardinalityEstimation < cardinalityEstimation {\n\t\tb.cardinalityEstimation = cardinalityEstimation\n\t}\n}", "func (mmGetPulseNumber *PacketParserMock) GetPulseNumberAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmGetPulseNumber.afterGetPulseNumberCounter)\n}", "func (pb *PBServer) tick() {\n\tpb.mu.Lock()\n defer pb.mu.Unlock()\n\n\tvar viewnum uint\n\tif pb.me == pb.view.Primary || pb.me == pb.view.Backup {\n\t\tviewnum = pb.view.Viewnum\n\t} else {\n\t\tviewnum = 0\n\t}\n\n\tview, err := pb.vs.Ping(viewnum)\n\tif err != nil {\n\t\tlogger.Debug(err)\n\t}\n\n\t// migrate the data if new backup appears\n\tif view.Backup != \"\" && pb.view.Backup != view.Backup && pb.me == view.Primary {\n args := MigrateArgs{Db: pb.db, Handled: pb.handled}\n reply := MigrateReply{}\n\n if !call(view.Backup, \"PBServer.Migrate\", &args, &reply) {\n return\n }\n\t}\n\n\tpb.view = view\n}", "func (self *averageCache) flush(flushLimit int) {\n\tlog.WithFields(log.Fields{\n\t\t\"cache\": self.name,\n\t}).Debug(\"Internal Flush\")\n\tvar valueFlushTargets []*whisper.TimeSeriesPoint = make([]*whisper.TimeSeriesPoint, 0)\n\tvar countFlushTargets []*whisper.TimeSeriesPoint = make([]*whisper.TimeSeriesPoint, 0)\n\tfor timeSlot, cacheSlot := range self.cache {\n\t\t// TODO: \n\t\t// Write all changes to subscriptions\n\t\tif cacheSlot.LastUpdated <= flushLimit {\n\t\t\tvalueFlushTargets = append(valueFlushTargets, &whisper.TimeSeriesPoint{timeSlot, cacheSlot.Value})\n\t\t\tcountFlushTargets = append(countFlushTargets, &whisper.TimeSeriesPoint{timeSlot, cacheSlot.Count})\n\t\t\tdelete(self.cache, timeSlot)\n\t\t}\n\t}\n\tlog.Debug(\"FlushAverages: \", valueFlushTargets)\n\tlog.Debug(\"FlushCounts: \", countFlushTargets)\n\n\t// TODO: Write flush targets to whisper\n\t// In another fiber perhaps to make this non-blocking?\n\tself.valueBackend.Write(valueFlushTargets)\n\tself.countBackend.Write(countFlushTargets)\n}", "func (r *Raft) tick() {\n\n\tswitch r.State {\n\tcase StateFollower:\n\t\tr.electionElapsed += 1\n\t\tif r.electionElapsed >= r.randomElectionTimeout {\n\t\t\tr.handleMsgUp()\n\t\t}\n\tcase StateCandidate:\n\t\tr.electionElapsed += 1\n\t\tif r.electionElapsed >= r.randomElectionTimeout {\n\t\t\tr.handleMsgUp()\n\t\t}\n\n\tcase StateLeader:\n\t\t// todo append retry is 1 logic clock\n\t\t//r.sendMsgToAll(r.sendAppendWrap)\n\t\tif r.heartbeatElapsed == 0 {\n\t\t\tr.sendHeartBeatToAll()\n\t\t}\n\t\tr.heartbeatElapsed = (r.heartbeatElapsed + 1) % r.heartbeatTimeout\n\t}\n\n\t// Your Code Here (2A).\n}" ]
[ "0.5581604", "0.5498568", "0.5405669", "0.5070121", "0.5051444", "0.50203633", "0.4999089", "0.49901783", "0.4933522", "0.49308974", "0.4929331", "0.4919969", "0.49038833", "0.48871338", "0.48802578", "0.48719504", "0.48650056", "0.48559475", "0.48462912", "0.48119715", "0.47915608", "0.47784895", "0.47754917", "0.4758478", "0.4755875", "0.4751962", "0.473532", "0.47081754", "0.47066188", "0.46930018", "0.46891317", "0.46838817", "0.46834046", "0.4683229", "0.46677703", "0.4664518", "0.46642134", "0.46596482", "0.46302247", "0.46259603", "0.46206003", "0.4599367", "0.45922512", "0.45778993", "0.4577848", "0.45674652", "0.4559658", "0.45375112", "0.4530607", "0.45305273", "0.45266476", "0.4521674", "0.45204866", "0.4516398", "0.4503549", "0.45029104", "0.44989234", "0.44975942", "0.44956765", "0.4485251", "0.4476425", "0.44701812", "0.4453696", "0.44506663", "0.44506663", "0.44472614", "0.44469032", "0.4438596", "0.4432753", "0.4432453", "0.44288948", "0.442797", "0.44211337", "0.44196168", "0.44054064", "0.44024536", "0.440161", "0.43955228", "0.43949357", "0.4386932", "0.43850288", "0.4382438", "0.43769345", "0.43743587", "0.4367248", "0.43665332", "0.43629646", "0.43628272", "0.43624556", "0.43612587", "0.43602753", "0.43583834", "0.43574643", "0.4346967", "0.4343296", "0.4341749", "0.43396312", "0.4338137", "0.43378222", "0.43377054" ]
0.70539033
0
TruncateHead remove all records after lastPulse
TruncateHead удаляет все записи после lastPulse
func (i *IndexDB) TruncateHead(ctx context.Context, from insolar.PulseNumber) error { i.lock.Lock() defer i.lock.Unlock() it := i.db.NewIterator(&indexKey{objID: *insolar.NewID(pulse.MinTimePulse, nil), pn: from}, false) defer it.Close() var hasKeys bool for it.Next() { hasKeys = true key := newIndexKey(it.Key()) err := i.db.Delete(&key) if err != nil { return errors.Wrapf(err, "can't delete key: %+v", key) } inslogger.FromContext(ctx).Debugf("Erased key. Pulse number: %s. ObjectID: %s", key.pn.String(), key.objID.String()) } if !hasKeys { inslogger.FromContext(ctx).Infof("No records. Nothing done. Pulse number: %s", from.String()) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RecordDB) TruncateHead(ctx context.Context, from insolar.PulseNumber) error {\n\n\tif err := r.truncateRecordsHead(ctx, from); err != nil {\n\t\treturn errors.Wrap(err, \"failed to truncate records head\")\n\t}\n\n\tif err := r.truncatePositionRecordHead(ctx, recordPositionKey{pn: from}, recordPositionKeyPrefix); err != nil {\n\t\treturn errors.Wrap(err, \"failed to truncate record positions head\")\n\t}\n\n\tif err := r.truncatePositionRecordHead(ctx, lastKnownRecordPositionKey{pn: from}, lastKnownRecordPositionKeyPrefix); err != nil {\n\t\treturn errors.Wrap(err, \"failed to truncate last known record positions head\")\n\t}\n\n\treturn nil\n}", "func (l *Log) Truncate(lowest uint64) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tvar segments []*segment\n\tfor _, s := range l.segments {\n\t\tif s.nextOffset <= lowest+1 {\n\t\t\tif err := s.Remove(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tsegments = append(segments, s)\n\t}\n\tl.segments = segments\n\treturn nil\n}", "func (l *Log) Truncate(lowest uint64) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tvar segments []*segment\n\tfor _, seg := range l.segments {\n\t\tif latestOffset := seg.nextOffset - 1; latestOffset <= lowest {\n\t\t\tif err := seg.Remove(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tsegments = append(segments, seg)\n\t}\n\n\tl.segments = segments\n\n\treturn nil\n}", "func (wal *WAL) TruncateBefore(o Offset) error {\n\tcutoff := sequenceToFilename(o.FileSequence())\n\t_, latestOffset, err := wal.Latest()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to determine latest offset: %v\", err)\n\t}\n\tlatestSequence := latestOffset.FileSequence()\n\treturn wal.forEachSegment(func(file os.FileInfo, first bool, last bool) (bool, error) {\n\t\tif last || file.Name() >= cutoff {\n\t\t\t// Files are sorted by name, if we've gotten past the cutoff or\n\t\t\t// encountered the last (active) file, don't bother continuing.\n\t\t\treturn false, nil\n\t\t}\n\t\tif filenameToSequence(file.Name()) == latestSequence {\n\t\t\t// Don't delete the file containing the latest valid entry\n\t\t\treturn true, nil\n\t\t}\n\t\trmErr := os.Remove(filepath.Join(wal.dir, file.Name()))\n\t\tif rmErr != nil {\n\t\t\treturn false, rmErr\n\t\t}\n\t\twal.log.Debugf(\"Removed WAL file %v\", filepath.Join(wal.dir, file.Name()))\n\t\treturn true, nil\n\t})\n}", "func (b *ChangeBuffer) truncateAfter(e list.Element) {\n\t// We must iterate and remove elements one by one to avoid memory leaks\n\tfirst := e.Next()\n\tfor first != nil {\n\t\tif first.Next() != nil {\n\t\t\tfirst = first.Next()\n\t\t\tb.Remove(first.Prev())\n\t\t} else {\n\t\t\tb.Remove(first)\n\t\t\tfirst = nil\n\t\t}\n\t}\n}", "func (t *BoundedTable) Truncate(ctx context.Context) error {\n\t// just reset everything.\n\tfor i := int64(0); i < t.capacity; i++ {\n\t\tatomic.StorePointer(&t.records[i], unsafe.Pointer(nil))\n\t}\n\tt.cursor = 0\n\treturn nil\n}", "func (rf *Raft) TruncateLog(lastAppliedIndex int) {\n\trf.mu.Lock()\n\tif lastAppliedIndex <= rf.lastApplied && lastAppliedIndex >= rf.Log.LastIncludedLength {\n\t\trf.Log.LastIncludedTerm = rf.Log.Entries[lastAppliedIndex-rf.Log.LastIncludedLength].Term\n\t\trf.Log.Entries = rf.Log.Entries[(lastAppliedIndex - rf.Log.LastIncludedLength + 1):]\n\t\trf.Log.LastIncludedLength = lastAppliedIndex + 1\n\t}\n\trf.mu.Unlock()\n}", "func (r *walReader) truncate(lastOffset int64) error {\n\tr.logger.Log(\"msg\", \"WAL corruption detected; truncating\",\n\t\t\"err\", r.err, \"file\", r.current().Name(), \"pos\", lastOffset)\n\n\t// Close and delete all files after the current one.\n\tfor _, f := range r.wal.files[r.cur+1:] {\n\t\tif err := f.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.Remove(f.Name()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tr.wal.files = r.wal.files[:r.cur+1]\n\n\t// Seek the current file to the last valid offset where we continue writing from.\n\t_, err := r.current().Seek(lastOffset, os.SEEK_SET)\n\treturn err\n}", "func (l *Ledger) Truncate(utxovmLastID []byte) error {\n\tl.xlog.Info(\"start truncate ledger\", \"blockid\", utils.F(utxovmLastID))\n\n\t// 获取账本锁\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\n\tbatchWrite := l.baseDB.NewBatch()\n\tnewMeta := proto.Clone(l.meta).(*pb.LedgerMeta)\n\tnewMeta.TipBlockid = utxovmLastID\n\n\t// 获取裁剪目标区块信息\n\tblock, err := l.fetchBlock(utxovmLastID)\n\tif err != nil {\n\t\tl.xlog.Warn(\"failed to find utxovm last block\", \"err\", err, \"blockid\", utils.F(utxovmLastID))\n\t\treturn err\n\t}\n\t// 查询分支信息\n\tbranchTips, err := l.GetBranchInfo(block.Blockid, block.Height)\n\tif err != nil {\n\t\tl.xlog.Warn(\"failed to find all branch tips\", \"err\", err)\n\t\treturn err\n\t}\n\n\t// 逐个分支裁剪到目标高度\n\tfor _, branchTip := range branchTips {\n\t\tdeletedBlockid := []byte(branchTip)\n\t\t// 裁剪到目标高度\n\t\terr = l.removeBlocks(deletedBlockid, block.Blockid, batchWrite)\n\t\tif err != nil {\n\t\t\tl.xlog.Warn(\"failed to remove garbage blocks\", \"from\", utils.F(l.meta.TipBlockid),\n\t\t\t\t\"to\", utils.F(block.Blockid))\n\t\t\treturn err\n\t\t}\n\t\t// 更新分支高度信息\n\t\terr = l.updateBranchInfo(block.Blockid, deletedBlockid, block.Height, batchWrite)\n\t\tif err != nil {\n\t\t\tl.xlog.Warn(\"truncate failed when calling updateBranchInfo\", \"err\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tnewMeta.TrunkHeight = block.Height\n\tmetaBuf, err := proto.Marshal(newMeta)\n\tif err != nil {\n\t\tl.xlog.Warn(\"failed to marshal pb meta\")\n\t\treturn err\n\t}\n\tbatchWrite.Put([]byte(pb.MetaTablePrefix), metaBuf)\n\terr = batchWrite.Write()\n\tif err != nil {\n\t\tl.xlog.Warn(\"batch write failed when truncate\", \"err\", err)\n\t\treturn err\n\t}\n\tl.meta = newMeta\n\n\tl.xlog.Info(\"truncate blockid succeed\")\n\treturn nil\n}", "func (t Table) Truncate(ctx context.Context) error {\n\tkeys, err := t.getKeys(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get table keys: %w\", err)\n\t}\n\n\titems, err := t.scan(ctx, keys)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"scan: %w\", err)\n\t}\n\n\tlog.Printf(\"[%s] contains %d items\\n\", t.name, len(items))\n\n\tif err := t.batchDelete(ctx, items); err != nil {\n\t\treturn fmt.Errorf(\"batch delete: %w\", err)\n\t}\n\n\tlog.Printf(\"[%s] complete to truncate table\\n\", t.name)\n\n\treturn nil\n}", "func (b *ChangeBuffer) truncateBefore(e list.Element) {\n\tlast := e.Prev()\n\tfor last != nil {\n\t\tif last.Prev() != nil {\n\t\t\tlast = last.Prev()\n\t\t\tb.Remove(last.Next())\n\t\t} else {\n\t\t\tb.Remove(last)\n\t\t\tlast = nil\n\t\t}\n\t}\n}", "func (snapshots EBSSnapshots) TrimHead(n int) EBSSnapshots {\n\tif n > len(snapshots) {\n\t\treturn EBSSnapshots{}\n\t}\n\treturn snapshots[n:]\n}", "func (seq Sequence) Truncate(width int, resolution time.Duration, asOf time.Time, until time.Time) (result Sequence) {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tresult = seq\n\toldUntil := result.Until()\n\tasOf = RoundTimeUntilDown(asOf, resolution, oldUntil)\n\tuntil = RoundTimeUntilDown(until, resolution, oldUntil)\n\n\tif !until.IsZero() {\n\t\tperiodsToRemove := int(oldUntil.Sub(until) / resolution)\n\t\tif periodsToRemove > 0 {\n\t\t\tbytesToRemove := periodsToRemove * width\n\t\t\tif bytesToRemove+Width64bits >= len(seq) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tresult = result[bytesToRemove:]\n\t\t\tresult.SetUntil(until)\n\t\t}\n\t}\n\n\tif !asOf.IsZero() {\n\t\tmaxPeriods := int(result.Until().Sub(asOf) / resolution)\n\t\tif maxPeriods <= 0 {\n\t\t\t// Entire sequence falls outside of truncation range\n\t\t\treturn nil\n\t\t}\n\t\tmaxLength := Width64bits + maxPeriods*width\n\t\tif maxLength >= len(result) {\n\t\t\treturn result\n\t\t}\n\t\treturn result[:maxLength]\n\t}\n\n\treturn result\n}", "func (b *pebbleBucket) DelBeforeTS(ts uint64) error {\n\tstart, end := b.name, keyUpperBound(b.name)\n\titer := b.db.NewIter(b.prefixIterOpts)\n\tfor iter.First(); iter.Valid(); iter.Next() {\n\t\t_, kts := decodeBatchKey(iter.Key(), b.name)\n\t\tif kts > ts {\n\t\t\tend = iter.Key()\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err := iter.Close(); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn errors.Trace(b.db.DeleteRange(start, end, b.writeOpts))\n}", "func (v *Data) Truncate(l int) {\n\tvar nil PicData\n\tdv := *v\n\tfor i := l; i < len(dv); i++ {\n\t\tdv[i] = nil\n\t}\n\n\t*v = dv[:l]\n}", "func (result *Result) Truncate(l int) *Result {\n\tif l == 0 {\n\t\treturn result\n\t}\n\n\tout := &Result{\n\t\tInsertID: result.InsertID,\n\t\tRowsAffected: result.RowsAffected,\n\t\tInfo: result.Info,\n\t\tSessionStateChanges: result.SessionStateChanges,\n\t}\n\tif result.Fields != nil {\n\t\tout.Fields = result.Fields[:l]\n\t}\n\tif result.Rows != nil {\n\t\tout.Rows = make([][]Value, 0, len(result.Rows))\n\t\tfor _, r := range result.Rows {\n\t\t\tout.Rows = append(out.Rows, r[:l])\n\t\t}\n\t}\n\treturn out\n}", "func Drain(s beam.Scope) {\n\tbeam.Init()\n\ts.Scope(\"truncate\")\n\tbeam.ParDo(s, &TruncateFn{}, beam.Impulse(s))\n}", "func (reader *embedFileReader) Truncate(int64) error {\n\treturn ErrNotAvail\n}", "func TestTiFlashTruncateTable(t *testing.T) {\n\ts, teardown := createTiFlashContext(t)\n\tdefer teardown()\n\ttk := testkit.NewTestKit(t, s.store)\n\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"drop table if exists ddltiflashp\")\n\ttk.MustExec(\"create table ddltiflashp(z int not null) partition by range (z) (partition p0 values less than (10), partition p1 values less than (20))\")\n\ttk.MustExec(\"alter table ddltiflashp set tiflash replica 1\")\n\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\t// Should get schema right now\n\ttk.MustExec(\"truncate table ddltiflashp\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\tCheckTableAvailableWithTableName(s.dom, t, 1, []string{}, \"test\", \"ddltiflashp\")\n\ttk.MustExec(\"drop table if exists ddltiflash2\")\n\ttk.MustExec(\"create table ddltiflash2(z int)\")\n\ttk.MustExec(\"alter table ddltiflash2 set tiflash replica 1\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailable)\n\t// Should get schema right now\n\n\ttk.MustExec(\"truncate table ddltiflash2\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailable)\n\tCheckTableAvailableWithTableName(s.dom, t, 1, []string{}, \"test\", \"ddltiflash2\")\n}", "func (s *Segment) Truncate(offset Offset) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tfor i, c := range s.chunks {\n\t\tif c.Offset().After(offset) {\n\t\t\t// Shrink the current chunk slice.\n\t\t\ts.chunks = s.chunks[i:]\n\n\t\t\t// Adjust the internal read pointer.\n\t\t\tif s.chunkIdx > 0 {\n\t\t\t\ts.chunkIdx -= i + 1\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (w *WAL) cut() error {\n\t// close old wal file; truncate to avoid wasting space if an early cut\n\toff, serr := w.tail().Seek(0, io.SeekCurrent)\n\tif serr != nil {\n\t\treturn serr\n\t}\n\n\tif err := w.tail().Truncate(off); err != nil {\n\t\treturn err\n\t}\n\n\tif err := w.sync(); err != nil {\n\t\treturn err\n\t}\n\n\tfpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1))\n\n\t// create a temp wal file with name sequence + 1, or truncate the existing one\n\tnewTail, err := w.fp.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update writer and save the previous crc\n\tw.locks = append(w.locks, newTail)\n\tprevCrc := w.encoder.crc.Sum32()\n\tw.encoder, err = newFileEncoder(w.tail().File, prevCrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = w.saveCrc(prevCrc); err != nil {\n\t\treturn err\n\t}\n\n\tif err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {\n\t\treturn err\n\t}\n\n\tif err = w.saveState(&w.state); err != nil {\n\t\treturn err\n\t}\n\n\t// atomically move temp wal file to wal file\n\tif err = w.sync(); err != nil {\n\t\treturn err\n\t}\n\n\toff, err = w.tail().Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = os.Rename(newTail.Name(), fpath); err != nil {\n\t\treturn err\n\t}\n\tstart := time.Now()\n\tif err = fileutil.Fsync(w.dirFile); err != nil {\n\t\treturn err\n\t}\n\twalFsyncSec.Observe(time.Since(start).Seconds())\n\n\t// reopen newTail with its new path so calls to Name() match the wal filename format\n\tnewTail.Close()\n\n\tif newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {\n\t\treturn err\n\t}\n\tif _, err = newTail.Seek(off, io.SeekStart); err != nil {\n\t\treturn err\n\t}\n\n\tw.locks[len(w.locks)-1] = newTail\n\n\tprevCrc = w.encoder.crc.Sum32()\n\tw.encoder, err = newFileEncoder(w.tail().File, prevCrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.Infof(fmt.Sprintf(\"created a new WAL segment path:%s\", fpath))\n\treturn nil\n}", "func (p Packet) Truncate() Packet {\n\tmLen := p.Len()\n\tif len(p) > mLen {\n\t\tp = p[:mLen]\n\t}\n\treturn p\n}", "func (p *TimePanel) CutHead(until time.Time) {\n\ti := sort.Search(len(p.dates), func(i int) bool {\n\t\treturn !p.dates[i].Before(until)\n\t})\n\tp.ICutHead(i)\n}", "func (w *fileWAL) truncate() error {\n\treturn w.f.Truncate(w.lastReadOffset)\n}", "func (b *baseKVStoreBatch) truncate(size int) {\n\tb.writeQueue = b.writeQueue[:size]\n}", "func (t *DbService) Truncate(request *TruncateRequest) (*TruncateResponse, error) {\n\trsp := &TruncateResponse{}\n\treturn rsp, t.client.Call(\"db\", \"Truncate\", request, rsp)\n}", "func (list_obj *SortedSeqnoListWithLock) truncateSeqnos(through_seqno uint64) {\n\tlist_obj.lock.Lock()\n\tdefer list_obj.lock.Unlock()\n\tseqno_list := list_obj.seqno_list\n\tindex, found := simple_utils.SearchUint64List(seqno_list, through_seqno)\n\tif found {\n\t\tlist_obj.seqno_list = seqno_list[index+1:]\n\t} else if index > 0 {\n\t\tlist_obj.seqno_list = seqno_list[index:]\n\t}\n}", "func DeleteAfter(t Time, L *list.List) {\n\tif L.Len() == 0 {\n\t\treturn\n\t}\n\tfront := L.Front()\n\tif front.Value.(Elem).GetTime() >= t {\n\t\tL = L.Init()\n\t\treturn\n\t}\nLoop:\n\tfor {\n\t\tel := L.Back()\n\t\tif el.Value.(Elem).GetTime() >= t {\n\t\t\tL.Remove(el)\n\t\t} else {\n\t\t\tbreak Loop\n\t\t}\n\t}\n}", "func (w *SegmentWAL) cut() error {\n\t// Sync current tail to disk and close.\n\tif tf := w.tail(); tf != nil {\n\t\tif err := w.sync(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\toff, err := tf.Seek(0, os.SEEK_CUR)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := tf.Truncate(off); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := tf.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tp, _, err := nextSequenceFile(w.dirFile.Name(), \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tf, err := os.Create(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = fileutil.Preallocate(f, w.segmentSize, true); err != nil {\n\t\treturn err\n\t}\n\tif err = w.dirFile.Sync(); err != nil {\n\t\treturn err\n\t}\n\n\t// Write header metadata for new file.\n\tmetab := make([]byte, 8)\n\tbinary.BigEndian.PutUint32(metab[:4], WALMagic)\n\tmetab[4] = WALFormatDefault\n\n\tif _, err := f.Write(metab); err != nil {\n\t\treturn err\n\t}\n\n\tw.files = append(w.files, f)\n\tw.cur = bufio.NewWriterSize(f, 4*1024*1024)\n\tw.curN = 8\n\n\treturn nil\n}", "func (t *Token) TruncateStart() *Token {\n\trtn := t.Prev\n\tt.Prev = nil\n\tif rtn != nil {\n\t\trtn.Next = nil\n\t}\n\treturn rtn\n}", "func (records Records) Cleaned() Records {\n\trecordsCount := len(records)\n\tif recordsCount == 0 {\n\t\treturn records\n\t}\n\n\tif recordsCount == 1 {\n\t\tr := records[0]\n\t\tif r.Duration == 0 {\n\t\t\tr.Duration = DefaultMeetDuration\n\t\t}\n\n\t\treturn records\n\t}\n\n\tsort.Sort(OrderByDate(records))\n\n\treturn fixDuration(recordsCount, records)\n}", "func (kv *fazzRedis) Truncate() error {\n\treturn kv.client.FlushAll().Err()\n}", "func (db *DB) Truncate() {\n\tfor _, table := range []string{\"archives\", \"transforms\"} {\n\t\t_, err := db.Exec(fmt.Sprintf(\"DELETE FROM %s\", table))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (wal *WAL) TruncateBeforeTime(ts time.Time) error {\n\treturn wal.TruncateBefore(NewOffset(tsToFileSequence(ts), 0))\n}", "func (p *CassandraClient) Truncate(cfname string) (err error) {\n\tif err = p.sendTruncate(cfname); err != nil {\n\t\treturn\n\t}\n\treturn p.recvTruncate()\n}", "func (kv *fazzRedis) Truncate(ctx context.Context) error {\n\treturn kv.client.FlushAll(ctx).Err()\n}", "func (ttruo *TradeTimeRangeUpdateOne) ClearRecords() *TradeTimeRangeUpdateOne {\n\tttruo.mutation.ClearRecords()\n\treturn ttruo\n}", "func (m *mergeWithTimestampsType) Flush() {\n\ttsLen := len(m.timestamps)\n\tif !m.lastRecordSet {\n\t\treturn\n\t}\n\tfor m.timestampIdx < tsLen {\n\t\tm.lastRecord.TimeStamp = m.timestamps[m.timestampIdx]\n\t\tif !m.wrapped.Append(&m.lastRecord) {\n\t\t\treturn\n\t\t}\n\t\tm.timestampIdx++\n\t}\n}", "func (b *ringBuf) truncateFrom(lo uint64) (removedBytes, removedEntries int32) {\n\tit, ok := iterateFrom(b, lo)\n\tfor ok {\n\t\tremovedBytes += int32(it.entry(b).Size())\n\t\tremovedEntries++\n\t\tit.clear(b)\n\t\tit, ok = it.next(b)\n\t}\n\tb.len -= int(removedEntries)\n\tif b.len < (len(b.buf) / shrinkThreshold) {\n\t\trealloc(b, 0, b.len)\n\t}\n\treturn\n}", "func (t *Track) Clean() {\n\tfor i := 0; i < len(t.samples); i++ {\n\t\tt.samples[i] = nil\n\t}\n\tt.samples = t.samples[:0]\n\tt.samples = nil\n}", "func (s *MemStorage) deleteBefore(channelID string, t int64) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tevents, ok := s.events[channelID]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\ti := positionGt(events, t)\n\tif i >= 0 {\n\t\tl := len(events[i:])\n\t\tc := defaultChannelLength\n\t\tif l > c {\n\t\t\tc = l\n\t\t}\n\t\ttruncated := make([]Event, l, c)\n\t\tcopy(truncated, events[i:])\n\t\ts.events[channelID] = truncated\n\t}\n\n\treturn nil\n}", "func (t Timestamp) Truncate(d Duration) Timestamp {\n\tif d <= 0 {\n\t\treturn t\n\t}\n\treturn t.Add(-Duration(int64(t) % int64(d)))\n}", "func (h *atomicHeadTailIndex) decHead() headTailIndex {\n\treturn headTailIndex(h.u.Add(-(1 << 32)))\n}", "func RemoveLastElemFromTop(c *gin.Context) { dequeueTop([]qMessage{}) }", "func (sb *SeekableBuffer) Truncate(size int64) (err error) {\n\tdefer func() {\n\t\tif state := recover(); state != nil {\n\t\t\terr = state.(error)\n\t\t}\n\t}()\n\n\tsizeInt := int(size)\n\tif sizeInt < len(sb.data)-1 {\n\t\tsb.data = sb.data[:sizeInt]\n\t} else {\n\t\tnew := make([]byte, sizeInt-len(sb.data))\n\t\tsb.data = append(sb.data, new...)\n\t}\n\n\treturn nil\n\n}", "func (ls *linestate) deleteToEnd() {\n\tls.buf = ls.buf[:ls.pos]\n\tls.refreshLine()\n}", "func (m *Mantle) truncatedMidGap() uint64 {\n\tmidGap := midGap(m.book(), rateStep)\n\treturn truncate(int64(midGap), int64(rateStep))\n}", "func (rf *Raft) cutoffLogBeforeIndex(lastLogIndex int, lastLogTerm int) {\n DISPrintf(\"Start to cut off server(%d) log. lastLogIndex=%d, lastLogfTerm=%d, before cut off its len(log)=%d\", rf.me, lastLogIndex, lastLogTerm, len(rf.log))\n if lastLogIndex >= len(rf.log) {\n rf.log = make([]Entry, 1, 100)\n rf.log[0].Term = lastLogTerm\n }else if rf.convertToGlobalViewIndex(lastLogIndex) <= rf.commitIndex {\n rf.log = rf.log[lastLogIndex:]\n DISPrintf(\"Cut off server(%d) log success and now its len(log)=%d\", rf.me, len(rf.log))\n }\n}", "func (d PacketData) TrimFront(count int) {\n\tif count > d.Size() {\n\t\tcount = d.Size()\n\t}\n\tbuf := d.pk.Data().ToBuffer()\n\tbuf.TrimFront(int64(count))\n\td.pk.buf.Truncate(int64(d.pk.dataOffset()))\n\td.pk.buf.Merge(&buf)\n}", "func Truncate() {\n\tfmt.Println(\"----------------> Truncate\")\n\n\tbuf := bytes.NewBufferString(\"hello\")\n\n\t//buf=hello\n\tfmt.Println(buf.String())\n\n\tbuf.Truncate(3)\n\t//buf=hel\n\tfmt.Println(buf.String())\n\n\tbuf.Truncate(2)\n\t//buf=he\n\tfmt.Println(buf.String())\n\n\tbuf.Truncate(0)\n\t//buf=\n\tfmt.Println(buf.String())\n}", "func (h *atomicHeadTailIndex) reset() {\n\th.u.Store(0)\n}", "func (sd *SelectDataset) Truncate() *TruncateDataset {\n\ttd := newTruncateDataset(sd.dialect.Dialect(), sd.queryFactory)\n\tif sd.clauses.HasSources() {\n\t\ttd = td.Table(sd.clauses.From())\n\t}\n\treturn td\n}", "func TestTiFlashTruncatePartition(t *testing.T) {\n\ts, teardown := createTiFlashContext(t)\n\tdefer teardown()\n\ttk := testkit.NewTestKit(t, s.store)\n\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"drop table if exists ddltiflash\")\n\ttk.MustExec(\"create table ddltiflash(i int not null, s varchar(255)) partition by range (i) (partition p0 values less than (10), partition p1 values less than (20))\")\n\ttk.MustExec(\"alter table ddltiflash set tiflash replica 1\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\ttk.MustExec(\"insert into ddltiflash values(1, 'abc'), (11, 'def')\")\n\ttk.MustExec(\"alter table ddltiflash truncate partition p1\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\tCheckTableAvailableWithTableName(s.dom, t, 1, []string{}, \"test\", \"ddltiflash\")\n}", "func (t *Token) TruncateEnd() *Token {\n\trtn := t.Next\n\tt.Next = nil\n\tif rtn != nil {\n\t\trtn.Prev = nil\n\t}\n\treturn rtn\n}", "func (res Responder) Truncate(n int) {\n\tres.b.Truncate(n)\n}", "func DeleteBefore(t Time, L *list.List) {\n\tif L.Len() == 0 {\n\t\treturn\n\t}\n\tback := L.Back()\n\tif back.Value.(Elem).GetTime() <= t {\n\t\tL = L.Init()\n\t\treturn\n\t}\nLoop:\n\tfor {\n\t\tel := L.Front()\n\t\tif el.Value.(Elem).GetTime() <= t {\n\t\t\tL.Remove(el)\n\t\t} else {\n\t\t\tbreak Loop\n\t\t}\n\t}\n}", "func (s *Srt) TrimTo(ms uint32) int {\n\tvar deleted int = 0\n\ts.ForEach(func(_ int, sub *Subtitle) bool {\n\t\tif sub.StartMs < ms {\n\t\t\tsub.MarkAsDeleted()\n\t\t\tdeleted++\n\t\t\ts.count--\n\t\t\treturn true\n\t\t}\n\t\tsub.StartMs -= ms\n\t\tsub.EndMs -= ms\n\t\treturn true\n\t})\n\treturn deleted\n}", "func (cp *ChangeLog) TruncateTo(maxLength int) int {\n\tif remove := len(cp.Entries) - maxLength; remove > 0 {\n\t\t// Set Since to the max of the sequences being removed:\n\t\tfor _, entry := range cp.Entries[0:remove] {\n\t\t\tif entry.Sequence > cp.Since {\n\t\t\t\tcp.Since = entry.Sequence\n\t\t\t}\n\t\t}\n\t\t// Copy entries into a new array to avoid leaving the entire old array in memory:\n\t\tnewEntries := make([]*LogEntry, maxLength)\n\t\tcopy(newEntries, cp.Entries[remove:])\n\t\tcp.Entries = newEntries\n\t\treturn remove\n\t}\n\treturn 0\n}", "func (sa *SuffixArray) Truncate(length uint64) error { return sa.ba.Truncate(length) }", "func (log *LogFile) updateHeadTail() error {\n\t// where are we in the log data file?\n\toffset, err := log.getWritePos()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\tif log.wrapNum == 0 {\n\t\t// if we haven't wrapped yet then gradually increase numSizeBytes\n\t\tlog.numSizeBytes = uint64(offset)\n\t\tstdlog.Printf(\"On 1st lap, increase numSizeBytes=%v\", log.numSizeBytes)\n\t}\n\n\t// point to offset in the data file where the next log entry is due to go\n\t// it is not written there yet but will be there when we next write it\n\tlog.headOffset = uint64(offset)\n\n\tstdlog.Printf(\"Update head %v and tail %v\\n\", log.headOffset, log.tailOffset)\n\tdata := metaData{HeadOffset: log.headOffset, TailOffset: log.tailOffset, MaxSizeBytes: log.maxSizeBytes, \n\t\tNumSizeBytes: log.numSizeBytes, WrapNum: log.wrapNum, NumEntries: log.NumEntries}\n\treturn log.writeMetaData(data)\n}", "func (c *Collection) removeBefore(t time.Time) error {\n\tif c == nil {\n\t\treturn errors.New(\"Collection.removeBefore: c == nil\")\n\t}\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tcLen := len(c.collection)\n\tif cLen == 0 {\n\t\treturn nil // we have a collection but no data\n\t}\n\t// remove old data here.\n\tfirst := 0\n\tdone := false\n\tfor !done {\n\t\tif c.collection[first].When().Before(t) {\n\t\t\tfirst++\n\t\t\tif first == cLen {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tfirst--\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// get the interval we need.\n\tif first == len(c.collection) {\n\t\tc.collection = nil // remove all entries\n\t} else if first != -1 {\n\t\tc.collection = c.collection[first:]\n\t}\n\treturn nil // no errors\n}", "func (r *Repairer) Truncate(part uint64, size int64) error {\n\tp := partitionFullPath(r.conf, r.topic, part)\n\treturn os.Truncate(p, size)\n}", "func deleteRecordFromSlice(slice []Record, id int) []Record {\n return append(slice[:id], slice[id+1:]...)\n}", "func (ingest *Ingestion) Clear(start int64, end int64) error {\n\tclear := ingest.DB.DeleteRange\n\n\terr := clear(start, end, \"history_effects\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operation_participants\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operations\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transaction_participants\", \"history_transaction_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transactions\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_ledgers\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = clear(start, end, \"history_trades\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *Writer) ZeroUntil(index int64)", "func (h *Queue) TrimTail(distance types.Distance) {\n\tif !h.trimSet || (h.trimValue > distance) {\n\t\th.trimSet = true\n\t\th.trimValue = distance\n\t}\n}", "func (t *Track) CleanForLive() {\n\tif len(t.chunksDuration) > t.chunksDepth {\n\t\tt.chunksDuration = t.chunksDuration[len(t.chunksDuration) - (t.chunksDepth + 1):]\n\t}\n\tif len(t.chunksSize) > t.chunksDepth {\n\t\tt.chunksSize = t.chunksSize[len(t.chunksSize) - (t.chunksDepth + 1):]\n\t}\n\tif len(t.chunksName) > t.chunksDepth {\n\t\tt.chunksName = t.chunksName[len(t.chunksName) - (t.chunksDepth + 1):]\n\t}\n}", "func (ttru *TradeTimeRangeUpdate) ClearRecords() *TradeTimeRangeUpdate {\n\tttru.mutation.ClearRecords()\n\treturn ttru\n}", "func (list_obj *DualSortedSeqnoListWithLock) truncateSeqnos(through_seqno uint64) {\n\tlist_obj.lock.Lock()\n\tdefer list_obj.lock.Unlock()\n\n\tlist_obj.seqno_list_1 = truncateGapSeqnoList(through_seqno, list_obj.seqno_list_1)\n\tlist_obj.seqno_list_2 = truncateGapSeqnoList(through_seqno, list_obj.seqno_list_2)\n}", "func (truo *TradeRecordUpdateOne) ClearTimeRange() *TradeRecordUpdateOne {\n\ttruo.mutation.ClearTimeRange()\n\treturn truo\n}", "func (s *streamKey) trimBefore(id string) int {\n\ts.mu.Lock()\n\tvar delete []string\n\tfor _, entry := range s.entries {\n\t\tif entry.ID < id {\n\t\t\tdelete = append(delete, entry.ID)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\ts.mu.Unlock()\n\ts.delete(delete)\n\treturn len(delete)\n}", "func Truncate(name string, size int64) error", "func (e *Execution) purge(threshold uint64) {\n\tfor blockID, record := range e.records {\n\t\tif record.Block.Header.Height < threshold {\n\t\t\tdelete(e.records, blockID)\n\t\t}\n\t}\n}", "func TestHandleLogTruncate(t *testing.T) {\n\tt.Skip(\"flaky\")\n\tta, lines, w, fs, dir := makeTestTailReal(t, \"trunc\")\n\tdefer os.RemoveAll(dir) // clean up\n\n\tlogfile := filepath.Join(dir, \"log\")\n\tf, err := fs.Create(logfile)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tresult := []*LogLine{}\n\tdone := make(chan struct{})\n\twg := sync.WaitGroup{}\n\tgo func() {\n\t\tfor line := range lines {\n\t\t\tresult = append(result, line)\n\t\t\twg.Done()\n\t\t}\n\t\tclose(done)\n\t}()\n\n\terr = ta.TailPath(logfile)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t_, err = f.WriteString(\"a\\nb\\nc\\n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twg.Add(3)\n\twg.Wait()\n\n\terr = f.Truncate(0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// This is potentially racy. Unlike in the case where we've got new\n\t// lines that we can verify were seen with the WaitGroup, here nothing\n\t// ensures that this update-due-to-truncate is seen by the Tailer before\n\t// we write new data to the file. In order to avoid the race we'll make\n\t// sure that the total data size written post-truncate is less than\n\t// pre-truncate, so that the post-truncate offset is always smaller\n\t// than the offset seen after wg.Add(3); wg.Wait() above.\n\n\t_, err = f.WriteString(\"d\\ne\\n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twg.Add(2)\n\n\t// ugh\n\twg.Wait()\n\tw.Close()\n\t<-done\n\n\texpected := []*LogLine{\n\t\t{logfile, \"a\"},\n\t\t{logfile, \"b\"},\n\t\t{logfile, \"c\"},\n\t\t{logfile, \"d\"},\n\t\t{logfile, \"e\"},\n\t}\n\tif diff := cmp.Diff(expected, result); diff != \"\" {\n\t\tt.Errorf(\"result didn't match:\\n%s\", diff)\n\t}\n}", "func (adapter *GORMAdapter) TruncateTable(entity interface{}) orm.Result {\n\treturn orm.Result{\n\t\tError: adapter.db.Delete(entity).Error,\n\t}\n}", "func (o *LargeObject) Truncate(size int64) (err error) {\n\t_, err = o.tx.Exec(o.ctx, \"select lo_truncate64($1, $2)\", o.fd, size)\n\treturn err\n}", "func StopLeading() {\n\tif intLeader == config.Id() {\n\t\tlastLeader = time.Now()\n\t}\n}", "func (repo *Repository) Truncate() error {\n\treturn repo.db.Delete(v1.Badge{}).Error\n}", "func (t *timeDataType) Truncate(d time.Duration) *timeDataType {\n\treturn t.Formatter(func(t time.Time) time.Time {\n\t\treturn t.Truncate(d)\n\t})\n}", "func TruncateEncodedChangeLog(r *bytes.Reader, maxLength, minLength int, w io.Writer) (removed int, newLength int) {\n\tsince := readSequence(r)\n\t// Find the starting position and sequence of each entry:\n\tentryPos := make([]int64, 0, 1000)\n\tentrySeq := make([]uint64, 0, 1000)\n\tfor {\n\t\tpos, err := r.Seek(0, 1)\n\t\tif err != nil {\n\t\t\tpanic(\"Seek??\")\n\t\t}\n\t\tflags, err := r.ReadByte()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak // eof\n\t\t\t}\n\t\t\tpanic(\"ReadByte failed\")\n\t\t}\n\t\tseq := readSequence(r)\n\t\tskipString(r)\n\t\tskipString(r)\n\t\tskipString(r)\n\t\tif flags > kMaxFlag {\n\t\t\tpanic(fmt.Sprintf(\"TruncateEncodedChangeLog: bad flags 0x%x, entry %d, offset %d\",\n\t\t\t\tflags, len(entryPos), pos))\n\t\t}\n\n\t\tentryPos = append(entryPos, pos)\n\t\tentrySeq = append(entrySeq, seq)\n\t}\n\n\t// How many entries to remove?\n\t// * Leave no more than maxLength entries\n\t// * Every sequence value removed should be less than every sequence remaining.\n\t// * The new 'since' value should be the maximum sequence removed.\n\toldLength := len(entryPos)\n\tremoved = oldLength - maxLength\n\tif removed <= 0 {\n\t\tremoved = 0\n\t} else {\n\t\tpivot, newSince := findPivot(entrySeq, removed-1)\n\t\tremoved = pivot + 1\n\t\tif oldLength-removed >= minLength {\n\t\t\tsince = newSince\n\t\t} else {\n\t\t\tremoved = 0\n\t\t\tbase.Warn(\"TruncateEncodedChangeLog: Couldn't find a safe place to truncate\")\n\t\t\t//TODO: Possibly find a pivot earlier than desired?\n\t\t}\n\t}\n\n\t// Write the updated Since and the remaining entries:\n\twriteSequence(since, w)\n\tif _, err := r.Seek(entryPos[removed], 0); err != nil {\n\t\tpanic(\"Seek back???\")\n\t}\n\tif _, err := io.Copy(w, r); err != nil {\n\t\tpanic(\"Copy???\")\n\t}\n\treturn removed, oldLength - removed\n}", "func (w *Wrapper) cleanBefore() {\n\tw.LastInsertID = 0\n\tw.LastResult = nil\n\tw.LastParams = []interface{}{}\n\tw.count = 0\n}", "func (s *Srt) Cut(start, end uint32) int {\n\tvar deleted int = 0\n\tduration := end - start\n\ts.ForEach(func(_ int, sub *Subtitle) bool {\n\t\tif sub.StartMs >= start && sub.StartMs < end {\n\t\t\tsub.MarkAsDeleted()\n\t\t\ts.count--\n\t\t\tdeleted++\n\t\t} else if sub.StartMs >= end {\n\t\t\tsub.StartMs -= duration\n\t\t\tsub.EndMs -= duration\n\t\t}\n\t\treturn true\n\t})\n\treturn deleted\n}", "func (l *FSList) TruncFilter() {\n\tfl := len(l.Filter)\n\tif fl <= 0 {\n\t\treturn\n\t}\n\tl.Filter = l.Filter[:fl-1]\n}", "func (l *LookupOscillator) BatchTruncateTick(freq float64, nframes int) []float64 {\n\tout := make([]float64, nframes)\n\tfor i := 0; i < nframes; i++ {\n\t\tindex := l.curphase\n\t\tif l.curfreq != freq {\n\t\t\tl.curfreq = freq\n\t\t\tl.incr = l.SizeOverSr * l.curfreq\n\t\t}\n\t\tcurphase := l.curphase\n\t\tcurphase += l.incr\n\t\tfor curphase > float64(Len(l.Table)) {\n\t\t\tcurphase -= float64(Len(l.Table))\n\t\t}\n\t\tfor curphase < 0.0 {\n\t\t\tcurphase += float64(Len(l.Table))\n\t\t}\n\t\tl.curphase = curphase\n\t\tout[i] = l.Table.data[int(index)]\n\t}\n\treturn out\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 (r *Reader) Unlimit() {\n\tr.newLimit <- nil\n}", "func santizeMetaData(h Heartbeat) Heartbeat {\n\th.CursorPosition = nil\n\th.Dependencies = nil\n\th.LineNumber = nil\n\th.Lines = nil\n\n\treturn h\n}", "func (s *streamKey) after(id string) []StreamEntry {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tpos := sort.Search(len(s.entries), func(i int) bool {\n\t\treturn streamCmp(id, s.entries[i].ID) < 0\n\t})\n\treturn s.entries[pos:]\n}", "func historyDelete(splited []string, length int) {\n if length == 2 {\n connect.DeleteGlobalMessages()\n return\n }\n connect.DeleteLocalMessages(splited[2:])\n}", "func (rso *RadosStripedObject) Truncate(size int64) (err error) {\n\n\tobj := C.CString(rso.ObjectName)\n\tdefer C.free(unsafe.Pointer(obj))\n\tc_size := C.uint64_t(size)\n\tret, err := C.rados_striper_trunc(rso.Ioctx, obj, c_size)\n\tif ret < 0 {\n\t\treturn err\n\t} else {\n\t\treturn nil\n\t}\n\treturn\n}", "func (mlog *MemoryLogStorage) TruncateMessages(index int64) error {\n\tlocalIndex := index - 1\n\tif localIndex < 0 {\n\t\treturn nil\n\t}\n\tif localIndex >= int64(len(mlog.offsets)) {\n\t\treturn nil\n\t}\n\tshrinkTo := mlog.offsets[localIndex]\n\tmlog.data = mlog.data[:shrinkTo]\n\tmlog.offsets = mlog.offsets[:localIndex]\n\treturn nil\n}", "func (recorder *TrxHistoryRecorder) Clean() {\n\trecorder.summaries.cache = list.New()\n}", "func (u *GameServerUpsertOne) ClearLastContactAt() *GameServerUpsertOne {\n\treturn u.Update(func(s *GameServerUpsert) {\n\t\ts.ClearLastContactAt()\n\t})\n}", "func (puo *PatientrecordUpdateOne) ClearMedicalrecordstaff() *PatientrecordUpdateOne {\n\tpuo.mutation.ClearMedicalrecordstaff()\n\treturn puo\n}", "func (huo *HistorytakingUpdateOne) ClearPatientrecord() *HistorytakingUpdateOne {\n\thuo.mutation.ClearPatientrecord()\n\treturn huo\n}", "func (v *Data) Clear() {\n\tv.Truncate(0)\n}", "func (t *OplogTailer) tail() error {\n\tvar iter *mgo.Iter\n\tlastTs := t.InitialTs\n\n\t// Stores the unique op IDs that have been reported for lastTs\n\t// (keeps us from re-reporting oplog entries when we restart the iterator)\n\t// Note that timestamps are only unique for a given mongod, so if there are\n\t// multiple replicaset members there may be multiple oplog entries for a given ts.\n\tvar hidsForLastTs []int64\n\n\tfor {\n\t\tif iter == nil {\n\t\t\t// If we recreate the iterator (e.g. if the cursor's been invalidated)\n\t\t\t// need to move up ts to avoid reporting entries that have already been processed.\n\t\t\tsel := append(t.baseQuery,\n\t\t\t\tbson.DocElem{\n\t\t\t\t\tName: \"ts\",\n\t\t\t\t\tValue: []bson.DocElem{\n\t\t\t\t\t\tbson.DocElem{\n\t\t\t\t\t\t\tName: \"$gte\",\n\t\t\t\t\t\t\tValue: lastTs,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tbson.DocElem{\n\t\t\t\t\tName: \"h\",\n\t\t\t\t\tValue: []bson.DocElem{\n\t\t\t\t\t\tbson.DocElem{\n\t\t\t\t\t\t\tName: \"$nin\",\n\t\t\t\t\t\t\tValue: hidsForLastTs,\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\t// Ref: https://github.com/go-mgo/mgo/issues/121\n\t\t\tquery := t.coll.Find(sel)\n\t\t\tquery = query.LogReplay()\n\t\t\titer = query.Tail(tailTimeout)\n\t\t}\n\n\t\tvar o OplogDoc\n\t\tif iter.Next(&o) {\n\t\t\tselect {\n\t\t\tcase <-t.DoneChan:\n\t\t\t\titer.Close()\n\t\t\t\treturn nil\n\t\t\tcase t.OutChan <- &o:\n\t\t\t}\n\n\t\t\tif o.Timestamp > lastTs {\n\t\t\t\tlastTs = o.Timestamp\n\t\t\t\thidsForLastTs = nil\n\t\t\t}\n\t\t\thidsForLastTs = append(hidsForLastTs, o.HistoryID)\n\t\t} else {\n\t\t\terr := iter.Err()\n\t\t\tif err != nil && err != mgo.ErrCursor {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif iter.Timeout() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\titer = nil\n\t\t}\n\t}\n}", "func TestTableTruncate(t *testing.T) {\n\tt.Run(\"Should succeed if table empty\", func(t *testing.T) {\n\t\ttb, cleanup := newTestTable(t)\n\t\tdefer cleanup()\n\n\t\terr := tb.Truncate()\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Should truncate the table\", func(t *testing.T) {\n\t\ttb, cleanup := newTestTable(t)\n\t\tdefer cleanup()\n\n\t\t// create two documents\n\t\tdoc1 := newDocument()\n\t\tdoc2 := newDocument()\n\n\t\t_, err := tb.Insert(doc1)\n\t\tassert.NoError(t, err)\n\t\t_, err = tb.Insert(doc2)\n\t\tassert.NoError(t, err)\n\n\t\terr = tb.Truncate()\n\t\tassert.NoError(t, err)\n\n\t\terr = tb.Iterate(func(_ types.Document) error {\n\t\t\treturn errors.New(\"should not iterate\")\n\t\t})\n\n\t\tassert.NoError(t, err)\n\t})\n}", "func DBTruncateTable(tableName string) error {\n\t_, err := r.Table(tableName).Delete().RunWrite(dbSession)\n\treturn err\n}", "func (tbl DbCompoundTable) Truncate(force bool) (err error) {\n\tfor _, query := range tbl.Dialect().TruncateDDL(tbl.Name().String(), force) {\n\t\t_, err = support.Exec(tbl, nil, query)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.75272435", "0.5956599", "0.58818066", "0.585593", "0.58506346", "0.5821484", "0.5794194", "0.57208204", "0.5657627", "0.5587941", "0.5498917", "0.5479526", "0.54287946", "0.5406762", "0.5404167", "0.53492576", "0.5343496", "0.5339121", "0.5239251", "0.5235306", "0.5232906", "0.52215016", "0.5213665", "0.5213078", "0.5200276", "0.5176488", "0.51560533", "0.51273155", "0.5122654", "0.50931406", "0.5082012", "0.50809705", "0.5079536", "0.50758994", "0.5061221", "0.50609624", "0.5041504", "0.5038606", "0.50150615", "0.5014168", "0.49962378", "0.49859872", "0.4984931", "0.4961818", "0.49604577", "0.49461606", "0.49413916", "0.4934312", "0.49289784", "0.49163857", "0.49135834", "0.4901754", "0.4900632", "0.48892853", "0.48860374", "0.48830396", "0.4878303", "0.48769155", "0.4876805", "0.48753673", "0.48642826", "0.48244143", "0.4820448", "0.48005807", "0.47937715", "0.47880962", "0.4787568", "0.477581", "0.4772108", "0.4770148", "0.4766963", "0.47525725", "0.47519445", "0.47325063", "0.47301304", "0.47223702", "0.47099125", "0.47055155", "0.47053748", "0.47004798", "0.46947062", "0.4694497", "0.46873197", "0.46718177", "0.466577", "0.46621916", "0.46593618", "0.46506092", "0.4644383", "0.46399528", "0.4638034", "0.46341556", "0.46341428", "0.4622324", "0.46111473", "0.46068898", "0.4606541", "0.46061173", "0.46051505", "0.45949656" ]
0.7663238
0
WaitReady waits for machinecontroller and its webhook to become ready
WaitReady ожидает, пока machinecontroller и его webhook станут готовыми
func WaitReady(s *state.State) error { if !s.Cluster.MachineController.Deploy { return nil } s.Logger.Infoln("Waiting for machine-controller to come up...") if err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil { return err } if err := waitForWebhook(s.Context, s.DynamicClient); err != nil { return err } if err := waitForMachineController(s.Context, s.DynamicClient); err != nil { return err } return waitForCRDs(s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func waitForWebhook(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerWebhookName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller webhook to became ready\")\n}", "func waitForMachineController(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller to became ready\")\n}", "func (c *BFTChain) WaitReady() error {\n\treturn nil\n}", "func (vm *VirtualMachine) WaitUntilReady(client SkytapClient) (*VirtualMachine, error) {\n\treturn vm.WaitUntilInState(client, []string{RunStateStop, RunStateStart, RunStatePause}, false)\n}", "func WaitForReady() {\n\tdefaultClient.WaitForReady()\n}", "func (c *Client) WaitUntilReady() {\n\tc.waitUntilReady()\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func WaitForReady() {\n\tucc.WaitForReady()\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func (a *Agent) WaitReady() {\n\ta.statusLock.RLock()\n\tdefer a.statusLock.RUnlock()\n\n\tfor {\n\t\tif a.status == 1 {\n\t\t\treturn\n\t\t}\n\t\ta.statusCond.Wait()\n\t}\n}", "func (p *Pebble) WaitReady(t *testing.T) {\n\tif p.pebbleCMD.Process == nil {\n\t\tt.Fatal(\"Pebble not started\")\n\t}\n\turl := p.DirectoryURL()\n\tRetry(t, 10, 10*time.Millisecond, func() error {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\t\tdefer cancel()\n\n\t\tt.Log(\"Checking pebble readiness\")\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := p.httpClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp.Body.Close()\n\t\treturn nil\n\t})\n}", "func WaitReady() {\n\tif deviceReady {\n\t\treturn\n\t}\n\tch := make(chan struct{}, 0)\n\tf := func() {\n\t\tdeviceReady = true\n\t\tclose(ch)\n\t}\n\tOnDeviceReady(f)\n\t<-ch\n\tUnDeviceReady(f)\n}", "func (s *S8Proxy) WaitUntilClientIsReady() {\n\ts.gtpClient.WaitUntilClientIsReady(0)\n}", "func (m *DomainMonitor) WaitReady() (err error) {\n\treturn m.sink.WaitReady()\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func (s *ssh) WaitReady(hostName string, timeout time.Duration) error {\n\tif timeout < utils.TimeoutCtxHost {\n\t\ttimeout = utils.TimeoutCtxHost\n\t}\n\thost := &host{session: s.session}\n\tcfg, err := host.SSHConfig(hostName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn conv.ToSystemSshConfig(cfg).WaitServerReady(timeout)\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func (l *LocalSDKServer) Ready(context.Context, *sdk.Empty) (*sdk.Empty, error) {\n\tlogrus.Info(\"Ready request has been received!\")\n\treturn &sdk.Empty{}, nil\n}", "func (client *gRPCVtctldClient) WaitForReady(ctx context.Context) error {\n\t// The gRPC implementation of WaitForReady uses the gRPC Connectivity API\n\t// See https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md\n\tfor {\n\t\tselect {\n\t\t// A READY connection to the vtctld could not be established\n\t\t// within the context timeout. The caller should close their\n\t\t// existing connection and establish a new one.\n\t\tcase <-ctx.Done():\n\t\t\treturn ErrConnectionTimeout\n\n\t\t// Wait to transition to READY state\n\t\tdefault:\n\t\t\tconnState := client.cc.GetState()\n\n\t\t\tswitch connState {\n\t\t\tcase connectivity.Ready:\n\t\t\t\treturn nil\n\n\t\t\t// Per https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md,\n\t\t\t// a client that enters the SHUTDOWN state never leaves this state, and all new RPCs should\n\t\t\t// fail immediately. Further polling is futile, in other words, and so we\n\t\t\t// return an error immediately to indicate that the caller can close the connection.\n\t\t\tcase connectivity.Shutdown:\n\t\t\t\treturn ErrConnectionShutdown\n\n\t\t\t// If the connection is IDLE, CONNECTING, or in a TRANSIENT_FAILURE mode,\n\t\t\t// then we wait to see if it will transition to a READY state.\n\t\t\tdefault:\n\t\t\t\tif !client.cc.WaitForStateChange(ctx, connState) {\n\t\t\t\t\t// If the client has failed to transition, fail so that the caller can close the connection.\n\t\t\t\t\treturn fmt.Errorf(\"failed to transition from state %s\", connState)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (chanSync *channelRelaySync) WaitOnSetup() {\n\tdefer chanSync.shared.setupComplete.Wait()\n}", "func (client *Client) WaitForBrokerReady(name string) error {\n\tnamespace := client.Namespace\n\tbrokerMeta := base.MetaEventing(name, namespace, \"Broker\")\n\tif err := base.WaitForResourceReady(client.Dynamic, brokerMeta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Wait(dev *model.Dev, okStatusList []config.UpState) error {\n\toktetoLog.Spinner(\"Activating your development container...\")\n\toktetoLog.StartSpinner()\n\tdefer oktetoLog.StopSpinner()\n\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\texit := make(chan error, 1)\n\n\tgo func() {\n\n\t\tticker := time.NewTicker(500 * time.Millisecond)\n\t\tfor {\n\t\t\tstatus, err := config.GetState(dev.Name, dev.Namespace)\n\t\t\tif err != nil {\n\t\t\t\texit <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif status == config.Failed {\n\t\t\t\texit <- fmt.Errorf(\"your development container has failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, okStatus := range okStatusList {\n\t\t\t\tif status == okStatus {\n\t\t\t\t\texit <- nil\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\toktetoLog.Infof(\"CTRL+C received, starting shutdown sequence\")\n\t\toktetoLog.StopSpinner()\n\t\treturn oktetoErrors.ErrIntSig\n\tcase err := <-exit:\n\t\tif err != nil {\n\t\t\toktetoLog.Infof(\"exit signal received due to error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (cli *CLI) SystemWaitReady() {\n\tintervalSec := time.Duration(3)\n\tutil.Panic(wait.PollImmediateInfinite(intervalSec*time.Second, func() (bool, error) {\n\t\tsys := &nbv1.NooBaa{}\n\t\terr := cli.Client.Get(cli.Ctx, client.ObjectKey{Namespace: cli.Namespace, Name: cli.SystemName}, sys)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif sys.Status.Phase == nbv1.SystemPhaseReady {\n\t\t\tcli.Log.Printf(\"✅ System Phase is \\\"%s\\\".\\n\", sys.Status.Phase)\n\t\t\treturn true, nil\n\t\t}\n\t\tif sys.Status.Phase == nbv1.SystemPhaseRejected {\n\t\t\treturn false, fmt.Errorf(\"❌ System Phase is \\\"%s\\\". describe noobaa for more information\", sys.Status.Phase)\n\t\t}\n\t\tcli.Log.Printf(\"⏳ System Phase is \\\"%s\\\". Waiting for it to be ready ...\\n\", sys.Status.Phase)\n\t\treturn false, nil\n\t}))\n}", "func (b *Bucket) WaitUntilReady(timeout time.Duration, opts *WaitUntilReadyOptions) error {\n\tif opts == nil {\n\t\topts = &WaitUntilReadyOptions{}\n\t}\n\n\tcli := b.sb.getCachedClient()\n\tif cli == nil {\n\t\treturn errors.New(\"bucket is not connected\")\n\t}\n\n\terr := cli.getBootstrapError()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprovider, err := cli.getWaitUntilReadyProvider()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdesiredState := opts.DesiredState\n\tif desiredState == 0 {\n\t\tdesiredState = ClusterStateOnline\n\t}\n\n\terr = provider.WaitUntilReady(\n\t\ttime.Now().Add(timeout),\n\t\tgocbcore.WaitUntilReadyOptions{\n\t\t\tDesiredState: gocbcore.ClusterState(desiredState),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (k *kubelet) waitForNodeReady() error {\n\tkc, _ := k.config.AdminConfig.ToYAMLString() //nolint:errcheck // This is checked in Validate().\n\n\tc, err := client.NewClient([]byte(kc))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating kubernetes client: %w\", err)\n\t}\n\n\treturn c.WaitForNodeReady(k.config.Name)\n}", "func waitWebhookConfigurationReady(f *framework.Framework, namespace string) error {\n\tcmClient := f.VclusterClient.CoreV1().ConfigMaps(namespace + \"-markers\")\n\treturn wait.PollUntilContextTimeout(f.Context, 100*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\tmarker := &corev1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: string(uuid.NewUUID()),\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tuniqueName: \"true\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t_, err := cmClient.Create(ctx, marker, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\t// The always-deny webhook does not provide a reason, so check for the error string we expect\n\t\t\tif strings.Contains(err.Error(), \"denied\") {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\t// best effort cleanup of markers that are no longer needed\n\t\t_ = cmClient.Delete(ctx, marker.GetName(), metav1.DeleteOptions{})\n\t\tf.Log.Infof(\"Waiting for webhook configuration to be ready...\")\n\t\treturn false, nil\n\t})\n}", "func (n *Netlify) WaitUntilDeployReady(ctx context.Context, d *models.Deploy) (*models.Deploy, error) {\n\treturn n.waitForState(ctx, d, \"prepared\", \"ready\")\n}", "func (g *Group) WaitTillReady() {\n\t<-g.readyCh\n}", "func (m *MachineScope) SetReady() {\n\tm.AzureMachine.Status.Ready = true\n}", "func (h *Handler) WaitReady(name string) error {\n\tif h.IsReady(name) {\n\t\treturn nil\n\t}\n\n\terrCh := make(chan error, 1)\n\tchkCh := make(chan struct{}, 1)\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGQUIT)\n\tctxCheck, cancelCheck := context.WithCancel(h.ctx)\n\tctxWatch, cancelWatch := context.WithCancel(h.ctx)\n\tdefer cancelCheck()\n\tdefer cancelWatch()\n\n\t// this goroutine used to check whether pod is ready and exists.\n\t// if pod already ready, return nil.\n\t// if pod does not exist, return error.\n\t// if pod exists but not ready, return nothing.\n\tgo func(context.Context) {\n\t\t<-chkCh\n\t\tfor i := 0; i < 6; i++ {\n\t\t\t// pod is already ready, return nil\n\t\t\tif h.IsReady(name) {\n\t\t\t\terrCh <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// pod no longer exists, return err\n\t\t\t_, err := h.Get(name)\n\t\t\tif k8serrors.IsNotFound(err) {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// pod exists but not ready, return northing.\n\t\t\tif err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Error(err)\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t}\n\t}(ctxCheck)\n\n\t// this goroutine used to watch pod.\n\tgo func(ctx context.Context) {\n\t\tfor {\n\t\t\ttimeout := int64(0)\n\t\t\tlistOptions := metav1.SingleObject(metav1.ObjectMeta{Name: name, Namespace: h.namespace})\n\t\t\tlistOptions.TimeoutSeconds = &timeout\n\t\t\twatcher, err := h.clientset.CoreV1().Pods(h.namespace).Watch(h.ctx, listOptions)\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tchkCh <- struct{}{}\n\t\t\tfor event := range watcher.ResultChan() {\n\t\t\t\tswitch event.Type {\n\t\t\t\tcase watch.Modified:\n\t\t\t\t\tif h.IsReady(name) {\n\t\t\t\t\t\twatcher.Stop()\n\t\t\t\t\t\terrCh <- nil\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\tcase watch.Deleted:\n\t\t\t\t\twatcher.Stop()\n\t\t\t\t\terrCh <- fmt.Errorf(\"pod/%s was deleted\", name)\n\t\t\t\t\treturn\n\t\t\t\tcase watch.Bookmark:\n\t\t\t\t\tlog.Debug(\"watch pod: bookmark\")\n\t\t\t\tcase watch.Error:\n\t\t\t\t\tlog.Debug(\"watch pod: error\")\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If event channel is closed, it means the kube-apiserver has closed the connection.\n\t\t\tlog.Debug(\"watch pod: reconnect to kubernetes\")\n\t\t\twatcher.Stop()\n\t\t}\n\t}(ctxWatch)\n\n\tselect {\n\tcase sig := <-sigCh:\n\t\treturn fmt.Errorf(\"cancelled by signal: %s\", sig.String())\n\tcase err := <-errCh:\n\t\treturn err\n\t}\n}", "func waitForMachineState(api *cloudapi.Client, id, state string, timeout time.Duration) error {\n\treturn waitFor(\n\t\tfunc() (bool, error) {\n\t\t\tcurrentState, err := readMachineState(api, id)\n\t\t\treturn currentState == state, err\n\t\t},\n\t\tmachineStateChangeCheckInterval,\n\t\tmachineStateChangeTimeout,\n\t)\n}", "func (i *TiFlashInstance) Ready(ctx context.Context, e ctxt.Executor, timeout uint64, tlsCfg *tls.Config) error {\n\t// FIXME: the timeout is applied twice in the whole `Ready()` process, in the worst\n\t// case it might wait double time as other components\n\tif err := PortStarted(ctx, e, i.GetServicePort(), timeout); err != nil {\n\t\treturn err\n\t}\n\n\tscheme := \"http\"\n\tif i.topo.BaseTopo().GlobalOptions.TLSEnabled {\n\t\tscheme = \"https\"\n\t}\n\taddr := fmt.Sprintf(\"%s://%s/tiflash/store-status\", scheme, utils.JoinHostPort(i.GetManageHost(), i.GetStatusPort()))\n\treq, err := http.NewRequest(\"GET\", addr, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq = req.WithContext(ctx)\n\n\tretryOpt := utils.RetryOption{\n\t\tDelay: time.Second,\n\t\tTimeout: time.Second * time.Duration(timeout),\n\t}\n\tvar queryErr error\n\tif err := utils.Retry(func() error {\n\t\tclient := utils.NewHTTPClient(statusQueryTimeout, tlsCfg)\n\t\tres, err := client.Client().Do(req)\n\t\tif err != nil {\n\t\t\tqueryErr = err\n\t\t\treturn err\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, err := io.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\tqueryErr = err\n\t\t\treturn err\n\t\t}\n\t\tif res.StatusCode == http.StatusNotFound || string(body) == \"Running\" {\n\t\t\treturn nil\n\t\t}\n\n\t\terr = fmt.Errorf(\"tiflash store status is '%s', not fully running yet\", string(body))\n\t\tqueryErr = err\n\t\treturn err\n\t}, retryOpt); err != nil {\n\t\treturn perrs.Annotatef(queryErr, \"timed out waiting for tiflash %s:%d to be ready after %ds\",\n\t\t\ti.Host, i.Port, timeout)\n\t}\n\treturn nil\n}", "func (client *Client) WaitForTriggerReady(name string) error {\n\tnamespace := client.Namespace\n\ttriggerMeta := base.MetaEventing(name, namespace, \"Trigger\")\n\tif err := base.WaitForResourceReady(client.Dynamic, triggerMeta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_m *BandwidthThrottlerSvc) Wait() {\n\t_m.Called()\n}", "func (s *SeleniumServer) Wait() {\n\terr := s.cmd.Wait()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\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 (a *Application) Wait() {\n\t<-a.terminated\n\tlog.Printf(\"[TEST] thats all folks\")\n}", "func (b *Bot) WaitUntilCompletion() {\n\tb.server.Wait()\n}", "func (svc *SSHService) WaitServerReady(hostParam interface{}, timeout time.Duration) error {\n\tvar err error\n\tsshSvc := NewSSHService(svc.provider)\n\tssh, err := sshSvc.GetConfig(hostParam)\n\tif err != nil {\n\t\treturn logicErrf(err, \"Failed to read SSH config\")\n\t}\n\twaitErr := ssh.WaitServerReady(timeout)\n\treturn infraErr(waitErr)\n}", "func (s *Serv) Wait() {\n\t<-s.done\n}", "func ensureVWHReady(){\n\tMustRunWithTimeout(certsReadyTime, \"kubectl create ns check-webhook\")\n\tMustRun(\"kubectl delete ns check-webhook\")\n}", "func (b *Botanist) WaitUntilRequiredExtensionsReady(ctx context.Context) error {\n\treturn retry.UntilTimeout(ctx, 5*time.Second, time.Minute, func(ctx context.Context) (done bool, err error) {\n\t\tif err := b.RequiredExtensionsReady(ctx); err != nil {\n\t\t\tb.Logger.Infof(\"Waiting until all the required extension controllers are ready (%+v)\", err)\n\t\t\treturn retry.MinorError(err)\n\t\t}\n\t\treturn retry.Ok()\n\t})\n}", "func (proxy *ProxyService) WaitReady(ctx context.Context) (bool, error) {\n\tselect {\n\tcase <-proxy.readyCh:\n\t\treturn proxy.IsReady(), nil\n\tcase <-ctx.Done():\n\t\treturn false, trace.Wrap(ctx.Err(), \"proxy service is not ready\")\n\t}\n}", "func (a *serverApp) Wait() {\n\t<-a.terminated\n}", "func (m *Machine) hasReadyCondition() bool {\n\n\tif m.vmiInstance == nil {\n\t\treturn false\n\t}\n\n\tfor _, cond := range m.vmiInstance.Status.Conditions {\n\t\tif cond.Type == kubevirtv1.VirtualMachineInstanceReady &&\n\t\t\tcond.Status == corev1.ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func WaitFabricReady(ctx context.Context, log logging.Logger, params WaitFabricReadyParams) error {\n\tif common.InterfaceIsNil(params.StateProvider) {\n\t\treturn errors.New(\"nil NetDevStateProvider\")\n\t}\n\n\tif len(params.FabricIfaces) == 0 {\n\t\treturn errors.New(\"no fabric interfaces requested\")\n\t}\n\n\tparams.FabricIfaces = common.DedupeStringSlice(params.FabricIfaces)\n\n\tch := make(chan error)\n\tgo loopFabricReady(log, params, ch)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-ch:\n\t\treturn err\n\t}\n}", "func (c *apiConsumers) Wait() {\n\tc.wait()\n}", "func Wait(options *WaitOptions, settings *env.Settings) error {\n\tkc, err := env.GetClient(settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//return status(kc, options, settings.Namespace)\n\treturn wait(kc, options, settings.Namespace)\n}", "func WaitOnReady(pvCount int, sleep, timeout time.Duration) bool {\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\tch := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tch <- AreAllReady(pvCount)\n\t\t\t\ttime.Sleep(sleep)\n\t\t\t}\n\t\t}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase ready := <-ch:\n\t\t\tif ready {\n\t\t\t\treturn ready\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tDescribePVs()\n\t\t\treturn false\n\t\t}\n\t}\n}", "func (p *Init) Wait() {\n\t<-p.waitBlock\n}", "func (app *ClientApplication) Ready() error {\n\tif ready, err := app.client().Ready(); err != nil {\n\t\treturn err\n\t} else if !ready {\n\t\treturn fmt.Errorf(\"worker not ready\")\n\t}\n\tlog.Infof(\"Worker is ready\")\n\treturn nil\n}", "func TestWaitUntilAllNodesReady(t *testing.T) {\n\tt.Parallel()\n\n\toptions := NewKubectlOptions(\"\", \"\", \"default\")\n\n\tWaitUntilAllNodesReady(t, options, 12, 5*time.Second)\n\n\tnodes := GetNodes(t, options)\n\tnodeNames := map[string]bool{}\n\tfor _, node := range nodes {\n\t\tnodeNames[node.Name] = true\n\t}\n\n\treadyNodes := GetReadyNodes(t, options)\n\treadyNodeNames := map[string]bool{}\n\tfor _, node := range readyNodes {\n\t\treadyNodeNames[node.Name] = true\n\t}\n\n\tassert.Equal(t, nodeNames, readyNodeNames)\n}", "func (s WeworkSender) Ready() bool {\n\tif s.InfoKey != \"\" && s.WarnKey != \"\" && s.ErrorKey != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func (e *endpoint) Wait() {\n\te.completed.Wait()\n}", "func (client *Client) WaitForChannelReady(name string) error {\n\tnamespace := client.Namespace\n\tchannelMeta := base.MetaEventing(name, namespace, \"Channel\")\n\tif err := base.WaitForResourceReady(client.Dynamic, channelMeta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func WaitReady(namespaceStore *nbv1.NamespaceStore) bool {\n\tlog := util.Logger()\n\tklient := util.KubeClient()\n\n\tinterval := time.Duration(3)\n\n\terr := wait.PollUntilContextCancel(ctx, interval*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\terr := klient.Get(util.Context(), util.ObjectKey(namespaceStore), namespaceStore)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"⏳ Failed to get NamespaceStore: %s\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tCheckPhase(namespaceStore)\n\t\tif namespaceStore.Status.Phase == nbv1.NamespaceStorePhaseRejected {\n\t\t\treturn false, fmt.Errorf(\"NamespaceStorePhaseRejected\")\n\t\t}\n\t\tif namespaceStore.Status.Phase != nbv1.NamespaceStorePhaseReady {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn (err == nil)\n}", "func (mod *Module)WaitTillStartupDone(){\n\tfor mod.hasRunStartup == false{//wait for startup to stop running\n\t\ttime.Sleep(time.Millisecond*10)\n\t}\n}", "func (b *Botanist) WaitUntilKubeAPIServerReady(ctx context.Context) error {\n\treturn retry.UntilTimeout(ctx, 5*time.Second, 300*time.Second, func(ctx context.Context) (done bool, err error) {\n\n\t\tdeploy := &appsv1.Deployment{}\n\t\tif err := b.K8sSeedClient.DirectClient().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeAPIServer), deploy); err != nil {\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\t\tif deploy.Generation != deploy.Status.ObservedGeneration {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver not observed at latest generation (%d/%d)\",\n\t\t\t\tdeploy.Status.ObservedGeneration, deploy.Generation))\n\t\t}\n\n\t\treplicas := int32(0)\n\t\tif deploy.Spec.Replicas != nil {\n\t\t\treplicas = *deploy.Spec.Replicas\n\t\t}\n\t\tif replicas != deploy.Status.UpdatedReplicas {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver does not have enough updated replicas (%d/%d)\",\n\t\t\t\tdeploy.Status.UpdatedReplicas, replicas))\n\t\t}\n\t\tif replicas != deploy.Status.Replicas {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver deployment has outdated replicas\"))\n\t\t}\n\t\tif replicas != deploy.Status.AvailableReplicas {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver does not have enough available replicas (%d/%d\",\n\t\t\t\tdeploy.Status.AvailableReplicas, replicas))\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func notifyReady() {\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func (relaySync *relaySync) WaitForInit(ctx context.Context) error {\n\tselect {\n\tcase <-relaySync.firstSetupWait:\n\tcase <-ctx.Done():\n\t\treturn streadway.ErrClosed\n\t}\n\n\treturn nil\n}", "func (m *StateSwitcherMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func waitForClusterReady(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Ready\n\t\t},\n\t)\n}", "func (client *Client) WaitHostReady(hostID string, timeout time.Duration) (*model.Host, error) {\n\treturn client.osclt.WaitHostReady(hostID, timeout)\n}", "func (a *App) Ready() {\n\ta.ready.Wait()\n}", "func (a *App) Ready() {\n\ta.ready.Wait()\n}", "func (_m *Broadcaster) DependentReady() {\n\t_m.Called()\n}", "func IsReady(name string, timing ...time.Duration) feature.StepFn {\n\treturn k8s.IsReady(GVR(), name, timing...)\n}", "func waitForAPI(ctx context.Context, client *gophercloud.ServiceClient) {\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\t// NOTE: Some versions of Ironic inspector returns 404 for /v1/ but 200 for /v1,\n\t// which seems to be the default behavior for Flask. Remove the trailing slash\n\t// from the client endpoint.\n\tendpoint := strings.TrimSuffix(client.Endpoint, \"/\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for API to become available...\")\n\n\t\t\tr, err := httpClient.Get(endpoint)\n\t\t\tif err == nil {\n\t\t\t\tstatusCode := r.StatusCode\n\t\t\t\tr.Body.Close()\n\t\t\t\tif statusCode == http.StatusOK {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (f *FakeCmdRunner) Wait() error {\n\treturn f.Err\n}", "func (s *sshClientExternal) Wait() error {\n\tif s.session == nil {\n\t\treturn nil\n\t}\n\treturn s.session.Wait()\n}", "func (a *Agent) Wait() error {\n\ta.init()\n\treturn <-a.waitCh\n}", "func ready(s *sdk.SDK) {\n\terr := s.Ready()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not send ready message\")\n\t}\n}", "func Wait() {\n\tdefaultManager.Wait()\n}", "func (node *Node) Wait() error {\n\treturn node.httpAPIServer.Wait()\n}", "func (b *buildandrun) Wait() {\n\t<-b.done\n}", "func (p *EventReplay) Wait() {}", "func (e *engine) Wait(context.Context, *Spec, *Step) (*State, error) {\n\treturn nil, nil // no-op for bash implementation\n}", "func (oc *contractTransmitter) Ready() error { return nil }", "func (s *Service) Wait() {\n\ts.waiter.Wait()\n}", "func (s *Service) Wait() {\n\ts.waiter.Wait()\n}", "func (s *Service) Wait() {\n\ts.waiter.Wait()\n}", "func (s *Store) WaitForInit() {\n\ts.initComplete.Wait()\n}", "func (elm *etcdLeaseManager) Wait() {\n\telm.wg.Wait()\n}", "func (c *controller) ready(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(\"ready check\")\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (s *Service) Wait(timeout time.Duration) (int, error) {\n\turl := s.BaseURL\n\tswitch s.Name {\n\tcase DeployService:\n\t\turl += \"/status.html\" // because /ApplicationStatus is not publicly reachable in Vespa Cloud\n\tcase QueryService, DocumentService:\n\t\turl += \"/ApplicationStatus\"\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"invalid service: %s\", s.Name)\n\t}\n\treturn waitForOK(s, url, timeout)\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n}", "func WaitAPIServiceReady(c *aggregator.Clientset, name string, timeout time.Duration) error {\n\tif err := wait.PollImmediate(time.Second, timeout, func() (done bool, err error) {\n\t\tapiService, e := c.ApiregistrationV1().APIServices().Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif e != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif apiregistrationv1helper.IsAPIServiceConditionTrue(apiService, apiregistrationv1.Available) {\n\t\t\treturn true, nil\n\t\t}\n\n\t\tklog.Infof(\"Waiting for APIService(%s) condition(%s), will try\", name, apiregistrationv1.Available)\n\t\treturn false, nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *HTTPProbe) Ready() {\n\tp.ready.Swap(1)\n}", "func (c *NetClient) Wait() {\n\t<-c.haltedCh\n}", "func WaitForResourceReady(dynamicClient dynamic.Interface, obj *MetaResource) error {\n\tmetricName := fmt.Sprintf(\"WaitForResourceReady/%s\", obj.Name)\n\t_, span := trace.StartSpan(context.Background(), metricName)\n\tdefer span.End()\n\n\treturn wait.PollImmediate(interval, timeout, func() (bool, error) {\n\t\treturn isResourceReady(dynamicClient, obj)\n\t})\n}", "func (h *KubernetesHelper) WaitUntilDeployReady(deploys map[string]DeploySpec) {\n\tctx := context.Background()\n\tfor deploy, spec := range deploys {\n\t\tif err := h.CheckPods(ctx, spec.Namespace, deploy, 1); err != nil {\n\t\t\tvar out string\n\t\t\t//nolint:errorlint\n\t\t\tif rce, ok := err.(*RestartCountError); ok {\n\t\t\t\tout = fmt.Sprintf(\"Error running test: failed to wait for deploy/%s to become 'ready', too many restarts (%v)\\n\", deploy, rce)\n\t\t\t} else {\n\t\t\t\tout = fmt.Sprintf(\"Error running test: failed to wait for deploy/%s to become 'ready', timed out waiting for condition\\n\", deploy)\n\t\t\t}\n\t\t\tos.Stderr.Write([]byte(out))\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func (n *Netlify) WaitUntilDeployLive(ctx context.Context, d *models.Deploy) (*models.Deploy, error) {\n\treturn n.waitForState(ctx, d, \"ready\")\n}", "func WaitForCondition(mcpName string, conditionType machineconfigv1.MachineConfigPoolConditionType, conditionStatus corev1.ConditionStatus) {\n\n\tvar cnfNodes []corev1.Node\n\trunningOnSingleNode, err := cluster.IsSingleNode()\n\tExpectWithOffset(1, err).ToNot(HaveOccurred())\n\t// checking in eventually as in case of single node cluster the only node may\n\t// be rebooting\n\tEventuallyWithOffset(1, func() error {\n\t\tmcp, err := GetByName(mcpName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting MCP by name\")\n\t\t}\n\n\t\tnodeLabels := mcp.Spec.NodeSelector.MatchLabels\n\t\tkey, _ := components.GetFirstKeyAndValue(nodeLabels)\n\t\treq, err := labels.NewRequirement(key, selection.Exists, []string{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed creating node selector\")\n\t\t}\n\n\t\tselector := labels.NewSelector()\n\t\tselector = selector.Add(*req)\n\t\tcnfNodes, err = nodes.GetBySelector(selector)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting nodes by selector\")\n\t\t}\n\n\t\ttestlog.Infof(\"MCP %q is targeting %v node(s)\", mcp.Name, len(cnfNodes))\n\t\treturn nil\n\t}, cluster.ComputeTestTimeout(10*time.Minute, runningOnSingleNode), 5*time.Second).ShouldNot(HaveOccurred(), \"Failed to find CNF nodes by MCP %q\", mcpName)\n\n\t// timeout should be based on the number of worker-cnf nodes\n\ttimeout := time.Duration(len(cnfNodes)*mcpUpdateTimeoutPerNode) * time.Minute\n\tif len(cnfNodes) == 0 {\n\t\ttimeout = 2 * time.Minute\n\t}\n\n\tEventuallyWithOffset(1, func() corev1.ConditionStatus {\n\t\treturn GetConditionStatus(mcpName, conditionType)\n\t}, cluster.ComputeTestTimeout(timeout, runningOnSingleNode), 30*time.Second).Should(Equal(conditionStatus), \"Failed to find condition status by MCP %q\", mcpName)\n}", "func (b *Botanist) WaitUntilEtcdsReady(ctx context.Context) error {\n\treturn etcd.WaitUntilEtcdsReady(\n\t\tctx,\n\t\tb.K8sSeedClient.DirectClient(),\n\t\tb.Logger,\n\t\tb.Shoot.SeedNamespace,\n\t\t2,\n\t\t5*time.Second,\n\t\t3*time.Minute,\n\t\t5*time.Minute,\n\t)\n}", "func (customer *Customer) CustomerIsReadyAndEntersWaitState(check bool) (err error) {\n\n\tvar currentTrigger ssm.Trigger\n\n\tcurrentTrigger = TriggerCustomerWaitsForCommands\n\n\tswitch check {\n\n\tcase true:\n\t\t// Do a check if state machine is in correct state for triggering event\n\t\tif customer.CustomerStateMachine.CanFire(currentTrigger.Key) == true {\n\t\t\terr = nil\n\n\t\t} else {\n\n\t\t\terr = customer.CustomerStateMachine.Fire(currentTrigger.Key, nil)\n\t\t}\n\n\tcase false:\n\t\t// Execute Trigger\n\t\terr = customer.CustomerStateMachine.Fire(currentTrigger.Key, nil)\n\t\tif err != nil {\n\t\t\tlogTriggerStateError(4, customer.CustomerStateMachine.State(), currentTrigger, err)\n\n\t\t}\n\t}\n\n\treturn err\n\n}", "func (c *controller) waitDeploymentReady(\n\tctx context.Context,\n\tdeploymentName string,\n\tnamespace string,\n) error {\n\t// Init ticker to check status every second\n\tticker := time.NewTicker(time.Second)\n\tdefer ticker.Stop()\n\n\t// Init knative ServicesGetter\n\tdeployments := c.k8sAppsClient.Deployments(namespace)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"timeout waiting for deployment %s to be ready\", deploymentName)\n\t\tcase <-ticker.C:\n\t\t\tdeployment, err := deployments.Get(deploymentName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to get deployment status for %s: %v\", deploymentName, err)\n\t\t\t}\n\n\t\t\tif deploymentReady(deployment) {\n\t\t\t\t// Service is completely ready\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *Response) wait() {\n\tr.StatusCode = HTTPStatusOK\n}" ]
[ "0.81729543", "0.73304754", "0.6926979", "0.69264543", "0.6682231", "0.6572147", "0.6555187", "0.6544689", "0.64363945", "0.62041384", "0.61236566", "0.60687506", "0.60536796", "0.60392857", "0.5971176", "0.59554976", "0.58414894", "0.58387625", "0.5814672", "0.5803259", "0.5783128", "0.577015", "0.57497394", "0.57397735", "0.57397246", "0.5721885", "0.5696095", "0.56816375", "0.5658691", "0.5648395", "0.5647614", "0.56443214", "0.5635702", "0.5634624", "0.5622948", "0.5599984", "0.5588777", "0.5585816", "0.5568214", "0.55585915", "0.55512005", "0.55510014", "0.5536125", "0.552952", "0.5520784", "0.5511295", "0.55084884", "0.5501455", "0.5499604", "0.5495508", "0.5473597", "0.54714936", "0.5465977", "0.5462402", "0.54593503", "0.54591805", "0.5453497", "0.5431939", "0.54318064", "0.5431432", "0.54226506", "0.5419544", "0.5408438", "0.5400009", "0.538846", "0.5385435", "0.53802556", "0.53802556", "0.53777194", "0.5368712", "0.53631085", "0.5352946", "0.5347596", "0.534614", "0.53440166", "0.5332794", "0.53289384", "0.5327947", "0.53262335", "0.5323447", "0.53205186", "0.53196967", "0.53196967", "0.53196967", "0.5315257", "0.5313336", "0.53087336", "0.5300953", "0.53009075", "0.5300501", "0.52923", "0.52921873", "0.5290592", "0.52893496", "0.5285912", "0.5282355", "0.5278832", "0.5270685", "0.52649003", "0.5262643" ]
0.7730005
1
waitForCRDs waits for machinecontroller CRDs to be created and become established
waitForCRDs ожидает создания и установки machinecontroller CRDs
func waitForCRDs(s *state.State) error { condFn := clientutil.CRDsReadyCondition(s.Context, s.DynamicClient, CRDNames()) err := wait.PollUntilContextTimeout(s.Context, 5*time.Second, 3*time.Minute, false, condFn.WithContext()) return fail.KubeClient(err, "waiting for machine-controller CRDs to became ready") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MeshReconciler) waitForCRD(name string, client runtimeclient.Client) error {\n\tm.logger.WithField(\"name\", name).Debug(\"waiting for CRD\")\n\n\tbackoffConfig := backoff.ConstantBackoffConfig{\n\t\tDelay: time.Duration(backoffDelaySeconds) * time.Second,\n\t\tMaxRetries: backoffMaxretries,\n\t}\n\tbackoffPolicy := backoff.NewConstantBackoffPolicy(backoffConfig)\n\n\tvar crd apiextensionsv1beta1.CustomResourceDefinition\n\terr := backoff.Retry(func() error {\n\t\terr := client.Get(context.Background(), types.NamespacedName{\n\t\t\tName: name,\n\t\t}, &crd)\n\t\tif err != nil {\n\t\t\treturn errors.WrapIf(err, \"could not get CRD\")\n\t\t}\n\n\t\tfor _, condition := range crd.Status.Conditions {\n\t\t\tif condition.Type == apiextensionsv1beta1.Established {\n\t\t\t\tif condition.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn errors.New(\"CRD is not established yet\")\n\t}, backoffPolicy)\n\n\treturn err\n}", "func waitForCRDEstablishment(clientset apiextensionsclient.Interface) error {\n\treturn wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {\n\t\tsparkAppCrd, err := getCRD(clientset)\n\t\tfor _, cond := range sparkAppCrd.Status.Conditions {\n\t\t\tswitch cond.Type {\n\t\t\tcase apiextensionsv1beta1.Established:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\tcase apiextensionsv1beta1.NamesAccepted:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionFalse {\n\t\t\t\t\tfmt.Printf(\"Name conflict: %v\\n\", cond.Reason)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false, err\n\t})\n}", "func waitForCRDCreated(clientset *fake.Clientset, CRDName string) error {\n\treturn wait.Poll(50*time.Millisecond, 5*time.Second, func() (bool, error) {\n\t\t_, err := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(CRDName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, err\n\t})\n}", "func (rcc *rotateCertsCmd) waitForControlPlaneReadiness() error {\n\tlog.Info(\"Checking health of control plane components\")\n\tpods := make([]string, 0)\n\tfor _, n := range rcc.cs.Properties.GetMasterVMNameList() {\n\t\tfor _, c := range []string{kubeAddonManager, kubeAPIServer, kubeControllerManager, kubeScheduler} {\n\t\t\tpods = append(pods, fmt.Sprintf(\"%s-%s\", c, n))\n\t\t}\n\t}\n\tif err := ops.WaitForReady(rcc.kubeClient, metav1.NamespaceSystem, pods, rotateCertsDefaultInterval, rotateCertsDefaultTimeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for control plane containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func waitForMachineController(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller to became ready\")\n}", "func waitForKnativeCrdsRegistered(timeout, interval time.Duration) error {\n\telapsed := time.Duration(0)\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(interval):\n\t\t\tif err := kubectl(nil, \"get\", \"images.caching.internal.knative.dev\"); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\telapsed += interval\n\t\t\tif elapsed > timeout {\n\t\t\t\treturn errors.Errorf(\"failed to confirm knative crd registration after %v\", timeout)\n\t\t\t}\n\t\t}\n\t}\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func waitUntilRDSClusterCreated(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\n\tmaxWaitAttempts := 120\n\n\tinput := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(rdsClusterName),\n\t}\n\n\tfmt.Printf(\"Wait until RDS cluster [%v] is fully created ...\\n\", rdsClusterName)\n\n\tstart := time.Now()\n\n\t// Check until created\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start)\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Cluster creation elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBClusters(input)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Wait RDS cluster creation err %v\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Cluster status: [%s]\\n\", *resp.DBClusters[0].Status)\n\t\tif *resp.DBClusters[0].Status == \"available\" {\n\t\t\tfmt.Printf(\"RDS cluster [%v] created successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\treturn fmt.Errorf(\"Aurora Cluster [%v] is not ready, exceed max wait attemps\\n\", rdsClusterName)\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func (r *CRDRegistry) RegisterCRDs() error {\n\tfor _, crd := range crds {\n\t\t// create the CustomResourceDefinition in the api\n\t\tif err := r.createCRD(crd); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// wait for the CustomResourceDefinition to be established\n\t\tif err := r.awaitCRD(crd, watchTimeout); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (sc *syncContext) ensureCRDReady(name string) {\n\t_ = wait.PollImmediate(time.Duration(100)*time.Millisecond, crdReadinessTimeout, func() (bool, error) {\n\t\tcrd, err := sc.extensionsclientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, condition := range crd.Status.Conditions {\n\t\t\tif condition.Type == v1beta1.Established {\n\t\t\t\treturn condition.Status == v1beta1.ConditionTrue, nil\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func waitForDaemonSets(c kubernetes.Interface, ns string, allowedNotReadyNodes int32, timeout time.Duration) error {\n\tif allowedNotReadyNodes == -1 {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\tframework.Logf(\"Waiting up to %v for all daemonsets in namespace '%s' to start\",\n\t\ttimeout, ns)\n\n\treturn wait.PollImmediate(framework.Poll, timeout, func() (bool, error) {\n\t\tdsList, err := c.AppsV1().DaemonSets(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"Error getting daemonsets in namespace: '%s': %v\", ns, err)\n\t\t\treturn false, err\n\t\t}\n\t\tvar notReadyDaemonSets []string\n\t\tfor _, ds := range dsList.Items {\n\t\t\tframework.Logf(\"%d / %d pods ready in namespace '%s' in daemonset '%s' (%d seconds elapsed)\", ds.Status.NumberReady, ds.Status.DesiredNumberScheduled, ns, ds.ObjectMeta.Name, int(time.Since(start).Seconds()))\n\t\t\tif ds.Status.DesiredNumberScheduled-ds.Status.NumberReady > allowedNotReadyNodes {\n\t\t\t\tnotReadyDaemonSets = append(notReadyDaemonSets, ds.ObjectMeta.Name)\n\t\t\t}\n\t\t}\n\n\t\tif len(notReadyDaemonSets) > 0 {\n\t\t\tframework.Logf(\"there are not ready daemonsets: %v\", notReadyDaemonSets)\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func WaitForCassDcReady(key types.NamespacedName, retryInterval, timeout time.Duration) error {\n\tstart := time.Now()\n\treturn wait.Poll(retryInterval, timeout, func() (bool, error) {\n\t\tcassdc, err := GetCassDc(key)\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, err\n\t\t}\n\t\tlogCassDcStatus(cassdc, start)\n\t\treturn cassdc.Status.CassandraOperatorProgress == cassdcapi.ProgressReady, nil\n\t})\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal, min, max int32) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\td, err := cs.AppsV1Interface.Deployments(\"openshift-machine-config-operator\").Get(context.TODO(), \"etcd-quorum-guard\", metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// By this point the deployment should exist.\n\t\t\tfmt.Printf(\" error waiting for etcd-quorum-guard deployment to exist: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tif d.Status.Replicas < 1 {\n\t\t\tfmt.Println(\"operator deployment has no replicas\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.Replicas == expectedTotal &&\n\t\t\td.Status.AvailableReplicas >= min &&\n\t\t\td.Status.AvailableReplicas <= max {\n\t\t\tfmt.Printf(\" Deployment is ready! %d %d\\n\", d.Status.Replicas, d.Status.AvailableReplicas)\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\tfor pod, info := range pods {\n\t\tif info.status == \"Running\" {\n\t\t\tnode := info.node\n\t\t\tif node == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Pod %s not associated with a node\", pod)\n\t\t\t}\n\t\t\tif _, ok := nodes[node]; !ok {\n\t\t\t\treturn fmt.Errorf(\"pod %s running on %s, not a master\", pod, node)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func WaitDestroy(s *state.State) error {\n\ts.Logger.Info(\"Waiting for all machines to get deleted...\")\n\n\treturn wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) {\n\t\tlist := &clusterv1alpha1.MachineList{}\n\t\tif err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\t\treturn false, fail.KubeClient(err, \"getting %T\", list)\n\t\t}\n\t\tif len(list.Items) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func (s *Installer) WaitForArgoCD() error {\n\tif s.Verbose {\n\t\tdefer NewWaitingMessage(\"Argo CD\", s.StatusUpdateInterval).Stop()\n\t}\n\twaitForDeployments := []string{\n\t\t\"argocd-application-controller\",\n\t\t\"argocd-dex-server\",\n\t\t\"argocd-redis\",\n\t\t\"argocd-repo-server\",\n\t\t\"argocd-server\",\n\t}\n\tdones := make([]chan error, len(waitForDeployments), len(waitForDeployments))\n\tfor i, deploymentName := range waitForDeployments {\n\t\tdone := make(chan error, 1)\n\t\tdones[i] = done\n\t\tgo func(deploymentName string, done chan<- error) {\n\t\t\tdefer close(done)\n\t\t\tdone <- WaitForDeployment(\n\t\t\t\ts.client,\n\t\t\t\tdeploymentName,\n\t\t\t\t\"argocd\",\n\t\t\t\t5*time.Second,\n\t\t\t\t30*time.Second)\n\t\t}(deploymentName, done)\n\t}\n\tvar multi error\n\tfor _, done := range dones {\n\t\tif err := <-done; err != nil {\n\t\t\tmulti = multierror.Append(multi, err)\n\t\t}\n\t}\n\treturn multi\n}", "func WaitForResources(objects object.K8sObjects, opts *kubectlcmd.Options) error {\n\tif opts.DryRun {\n\t\tlogAndPrint(\"Not waiting for resources ready in dry run mode.\")\n\t\treturn nil\n\t}\n\n\tcs, err := kubernetes.NewForConfig(k8sRESTConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"k8s client error: %s\", err)\n\t}\n\n\terrPoll := wait.Poll(2*time.Second, opts.WaitTimeout, func() (bool, error) {\n\t\tpods := []v1.Pod{}\n\t\tservices := []v1.Service{}\n\t\tdeployments := []deployment{}\n\t\tnamespaces := []v1.Namespace{}\n\n\t\tfor _, o := range objects {\n\t\t\tkind := o.GroupVersionKind().Kind\n\t\t\tswitch kind {\n\t\t\tcase \"Namespace\":\n\t\t\t\tnamespace, err := cs.CoreV1().Namespaces().Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnamespaces = append(namespaces, *namespace)\n\t\t\tcase \"Pod\":\n\t\t\t\tpod, err := cs.CoreV1().Pods(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, *pod)\n\t\t\tcase \"ReplicationController\":\n\t\t\t\trc, err := cs.CoreV1().ReplicationControllers(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, rc.Namespace, rc.Spec.Selector)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"Deployment\":\n\t\t\t\tcurrentDeployment, err := cs.AppsV1().Deployments(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\t_, _, newReplicaSet, err := kubectlutil.GetAllReplicaSets(currentDeployment, cs.AppsV1())\n\t\t\t\tif err != nil || newReplicaSet == nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnewDeployment := deployment{\n\t\t\t\t\tnewReplicaSet,\n\t\t\t\t\tcurrentDeployment,\n\t\t\t\t}\n\t\t\t\tdeployments = append(deployments, newDeployment)\n\t\t\tcase \"DaemonSet\":\n\t\t\t\tds, err := cs.AppsV1().DaemonSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, ds.Namespace, ds.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"StatefulSet\":\n\t\t\t\tsts, err := cs.AppsV1().StatefulSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, sts.Namespace, sts.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"ReplicaSet\":\n\t\t\t\trs, err := cs.AppsV1().ReplicaSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, rs.Namespace, rs.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"Service\":\n\t\t\t\tsvc, err := cs.CoreV1().Services(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tservices = append(services, *svc)\n\t\t\t}\n\t\t}\n\t\tisReady := namespacesReady(namespaces) && podsReady(pods) && deploymentsReady(deployments) && servicesReady(services)\n\t\tif !isReady {\n\t\t\tlogAndPrint(\"Waiting for resources ready with timeout of %v\", opts.WaitTimeout)\n\t\t}\n\t\treturn isReady, nil\n\t})\n\n\tif errPoll != nil {\n\t\tlogAndPrint(\"Failed to wait for resources ready: %v\", errPoll)\n\t\treturn fmt.Errorf(\"failed to wait for resources ready: %s\", errPoll)\n\t}\n\treturn nil\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func waitForClusterReady(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Ready\n\t\t},\n\t)\n}", "func waitForReadyNodes(desiredCount int, timeout time.Duration, requiredConsecutiveSuccesses int) error {\n\tstop := time.Now().Add(timeout)\n\n\tconsecutiveSuccesses := 0\n\tfor {\n\t\tif time.Now().After(stop) {\n\t\t\tbreak\n\t\t}\n\n\t\tnodes, err := kubectlGetNodes(\"\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"kubectl get nodes failed, sleeping: %v\", err)\n\t\t\tconsecutiveSuccesses = 0\n\t\t\ttime.Sleep(30 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t\treadyNodes := countReadyNodes(nodes)\n\t\tif readyNodes >= desiredCount {\n\t\t\tconsecutiveSuccesses++\n\t\t\tif consecutiveSuccesses >= requiredConsecutiveSuccesses {\n\t\t\t\tlog.Printf(\"%d ready nodes found, %d sequential successes - cluster is ready\",\n\t\t\t\t\treadyNodes,\n\t\t\t\t\tconsecutiveSuccesses)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tlog.Printf(\"%d ready nodes found, waiting for %d sequential successes (success count = %d)\",\n\t\t\t\treadyNodes,\n\t\t\t\trequiredConsecutiveSuccesses,\n\t\t\t\tconsecutiveSuccesses)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t} else {\n\t\t\tconsecutiveSuccesses = 0\n\t\t\tlog.Printf(\"%d (ready nodes) < %d (requested instances), sleeping\", readyNodes, desiredCount)\n\t\t\ttime.Sleep(30 * time.Second)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"waiting for ready nodes timed out\")\n}", "func waitForReplicasInit(\n\tctx context.Context,\n\tdialer *nodedialer.Dialer,\n\trangeID roachpb.RangeID,\n\treplicas []roachpb.ReplicaDescriptor,\n) error {\n\treturn contextutil.RunWithTimeout(ctx, \"wait for replicas init\", 5*time.Second, func(ctx context.Context) error {\n\t\tg := ctxgroup.WithContext(ctx)\n\t\tfor _, repl := range replicas {\n\t\t\trepl := repl // copy for goroutine\n\t\t\tg.GoCtx(func(ctx context.Context) error {\n\t\t\t\tconn, err := dialer.Dial(ctx, repl.NodeID, rpc.DefaultClass)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"could not dial n%d\", repl.NodeID)\n\t\t\t\t}\n\t\t\t\t_, err = NewPerReplicaClient(conn).WaitForReplicaInit(ctx, &WaitForReplicaInitRequest{\n\t\t\t\t\tStoreRequestHeader: StoreRequestHeader{NodeID: repl.NodeID, StoreID: repl.StoreID},\n\t\t\t\t\tRangeID: rangeID,\n\t\t\t\t})\n\t\t\t\treturn err\n\t\t\t})\n\t\t}\n\t\treturn g.Wait()\n\t})\n}", "func getCRDs(csv *v1alpha1.ClusterServiceVersion) (crds []client.Object) {\n\tfor _, resource := range csv.Status.RequirementStatus {\n\t\tif resource.Kind == crdKind {\n\t\t\tobj := &unstructured.Unstructured{}\n\t\t\tobj.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\t\tGroup: resource.Group,\n\t\t\t\tVersion: resource.Version,\n\t\t\t\tKind: resource.Kind,\n\t\t\t})\n\t\t\tobj.SetName(resource.Name)\n\t\t\tcrds = append(crds, obj)\n\t\t}\n\t}\n\treturn\n}", "func WaitForResources(objects object.K8sObjects, restConfig *rest.Config, cs kubernetes.Interface,\n\twaitTimeout time.Duration, dryRun bool, l *progress.ManifestLog) error {\n\tif dryRun {\n\t\treturn nil\n\t}\n\n\tif err := waitForCRDs(objects, restConfig); err != nil {\n\t\treturn err\n\t}\n\n\tvar notReady []string\n\n\t// Check if we are ready immediately, to avoid the 2s delay below when we are already redy\n\tif ready, _, err := waitForResources(objects, cs, l); err == nil && ready {\n\t\treturn nil\n\t}\n\n\terrPoll := wait.Poll(2*time.Second, waitTimeout, func() (bool, error) {\n\t\tisReady, notReadyObjects, err := waitForResources(objects, cs, l)\n\t\tnotReady = notReadyObjects\n\t\treturn isReady, err\n\t})\n\n\tif errPoll != nil {\n\t\tmsg := fmt.Sprintf(\"resources not ready after %v: %v\\n%s\", waitTimeout, errPoll, strings.Join(notReady, \"\\n\"))\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func WaitReady(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\ts.Logger.Infoln(\"Waiting for machine-controller to come up...\")\n\n\tif err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForWebhook(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForMachineController(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\treturn waitForCRDs(s)\n}", "func waitForClusterProvisioned(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Provisioned\n\t\t},\n\t)\n}", "func SetupCRDs(crdPath, pattern string) env.Func {\n\treturn func(ctx context.Context, c *envconf.Config) (context.Context, error) {\n\t\tr, err := resources.New(c.Client().RESTConfig())\n\t\tif err != nil {\n\t\t\treturn ctx, err\n\t\t}\n\t\treturn ctx, decoder.ApplyWithManifestDir(ctx, r, crdPath, pattern, []resources.CreateOption{})\n\t}\n}", "func waitForCnsVSphereVolumeMigrationCrd(ctx context.Context, vpath string) (*v1alpha1.CnsVSphereVolumeMigration, error) {\n\tvar (\n\t\tfound bool\n\t\tcrd *v1alpha1.CnsVSphereVolumeMigration\n\t)\n\twaitErr := wait.PollImmediate(poll, pollTimeout, func() (bool, error) {\n\t\tfound, crd = getCnsVSphereVolumeMigrationCrd(ctx, vpath)\n\t\treturn found, nil\n\t})\n\treturn crd, waitErr\n}", "func processCRDs(ctx context.Context, processor crdProcessor, defs []crd.Definition) error {\n\tclient, err := crdClientFn()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, def := range defs {\n\t\tcustomResourceDefinition, err := loadCRD(def.Contents)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := processor(ctx, client, customResourceDefinition); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func waitUntilRDSClusterDeleted(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\n\tinput := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(rdsClusterName),\n\t}\n\n\t// Check if Cluster exists\n\t_, err := rdsClientSess.DescribeDBClusters(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t} else {\n\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: DEBUG - fmt.Println(result)\n\tfmt.Printf(\"Wait until RDS cluster [%v] is fully deleted...\\n\", rdsClusterName)\n\n\tstart := time.Now()\n\n\tmaxWaitAttempts := 120\n\n\t// Check until deleted\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start).Seconds()\n\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Cluster deletion elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBClusters(input)\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\t\tfmt.Println(\"RDS Cluster deleted successfully\")\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"Cluster status: [%s]\\n\", *resp.DBClusters[0].Status)\n\t\tif *resp.DBClusters[0].Status == \"terminated\" {\n\t\t\tfmt.Printf(\"RDS cluster [%v] deleted successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\n\t// Timeout Err\n\treturn fmt.Errorf(\"RDS Cluster [%v] could not be deleted, exceed max wait attemps\\n\", rdsClusterName)\n}", "func WaitDaemonsetReady(namespace, name string, timeout time.Duration) error {\n\n\tnodes, err := daemonsetClient.K8sClient.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get node list, err:%s\", err)\n\t}\n\n\tnodesCount := int32(len(nodes.Items))\n\tisReady := false\n\tfor start := time.Now(); !isReady && time.Since(start) < timeout; {\n\t\tdaemonSet, err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Get(context.Background(), name, metav1.GetOptions{})\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get daemonset, err: %s\", err)\n\t\t}\n\n\t\tif daemonSet.Status.DesiredNumberScheduled != nodesCount {\n\t\t\treturn fmt.Errorf(\"daemonset DesiredNumberScheduled not equal to number of nodes:%d, please instantiate debug pods on all nodes\", nodesCount)\n\t\t}\n\n\t\tlogrus.Infof(\"Waiting for (%d) debug pods to be ready: %+v\", nodesCount, daemonSet.Status)\n\t\tif isDaemonSetReady(&daemonSet.Status) {\n\t\t\tisReady = true\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(waitingTime)\n\t}\n\n\tif !isReady {\n\t\treturn errors.New(\"daemonset debug pods not ready\")\n\t}\n\n\tlogrus.Infof(\"All the debug pods are ready.\")\n\treturn nil\n}", "func (client *Client) WaitForAllTestResourcesReady() error {\n\tif err := client.WaitForChannelsReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForSubscriptionsReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForBrokersReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForTriggersReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForCronJobSourcesReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForContainerSourcesReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := pkgTest.WaitForAllPodsRunning(client.Kube, client.Namespace); err != nil {\n\t\treturn err\n\t}\n\t// FIXME(Fredy-Z): This hacky sleep is added to try mitigating the test flakiness.\n\t// Will delete it after we find the root cause and fix.\n\ttime.Sleep(10 * time.Second)\n\treturn nil\n}", "func waitAndCleanup() {\n\ttime.Sleep(1 * time.Second)\n\n\t// Disconnect from switches.\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tvrtrAgents[i].Delete()\n\t\tvxlanAgents[i].Delete()\n\t\tvlanAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tvlrtrAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\thostBridges[i].Delete()\n\t}\n\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vxlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[NUM_AGENT+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(2*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tbrName := \"vlrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(3*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\tbrName := \"hostBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[HB_AGENT_INDEX].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n}", "func (rcc *rotateCertsCmd) waitForKubeSystemReadiness() error {\n\tlog.Info(\"Checking health of all kube-system pods\")\n\ttimeout := time.Duration(len(rcc.nodes)) * time.Duration(float64(time.Minute)*1.25)\n\tif rotateCertsDefaultTimeout > timeout {\n\t\ttimeout = rotateCertsDefaultTimeout\n\t}\n\tif err := ops.WaitForAllInNamespaceReady(rcc.kubeClient, metav1.NamespaceSystem, rotateCertsDefaultInterval, timeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for kube-system containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func waitForGlusterContainer() error {\n\n\t//Check if docker gluster container is up and running\n\tfor {\n\t\tglusterServerContainerVal, err := helpers.GetSystemDockerNode(\"gluster-server\")\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error in checking docker gluster container for status \", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tif len(glusterServerContainerVal) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\trwolog.Debug(\"Sleeping for 10 seconds to get gluster docker container up\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func waitForCertificateReady(configMap *corev1.ConfigMap) bool {\n\tlog := util.Logger()\n\tklient := util.KubeClient()\n\n\tinterval := time.Duration(3)\n\ttimeout := time.Duration(15)\n\n\terr := wait.PollUntilContextTimeout(ctx, interval*time.Second, timeout*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\tif err := klient.Get(util.Context(), util.ObjectKey(configMap), configMap); err != nil {\n\t\t\tlog.Printf(\"⏳ Failed to get service ca certificate: %s\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif configMap.Data[\"service-ca.crt\"] == \"\" {\n\t\t\treturn false, fmt.Errorf(\"service ca certificate not created\")\n\t\t}\n\n\t\treturn true, nil\n\t})\n\treturn (err == nil)\n}", "func waitForConnection(ctx context.Context, c client.Interface) {\n\tlog.Info(\"Checking datastore connection\")\n\tfor {\n\t\t// Query some arbitrary configuration to see if the connection\n\t\t// is working. Getting a specific Node is a good option, even\n\t\t// if the Node does not exist.\n\t\t_, err := c.Nodes().Get(ctx, \"foo\", options.GetOptions{})\n\n\t\t// We only care about a couple of error cases, all others would\n\t\t// suggest the datastore is accessible.\n\t\tif err != nil {\n\t\t\tswitch err.(type) {\n\t\t\tcase cerrors.ErrorConnectionUnauthorized:\n\t\t\t\tlog.WithError(err).Warn(\"Connection to the datastore is unauthorized\")\n\t\t\t\tutils.Terminate()\n\t\t\tcase cerrors.ErrorDatastoreError:\n\t\t\t\tlog.WithError(err).Info(\"Hit error connecting to datastore - retry\")\n\t\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// We've connected to the datastore - break out of the loop.\n\t\tbreak\n\t}\n\tlog.Info(\"Datastore connection verified\")\n}", "func (c *containerAdapter) waitClusterVolumes(ctx context.Context) error {\n\tfor _, attached := range c.container.task.Volumes {\n\t\t// for every attachment, try until we succeed or until the context\n\t\t// is canceled.\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tdefault:\n\t\t\t\t// continue through the code.\n\t\t\t}\n\t\t\tpath, err := c.dependencies.Volumes().Get(attached.ID)\n\t\t\tif err == nil && path != \"\" {\n\t\t\t\t// break out of the inner-most loop\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tswarmlog.G(ctx).Debug(\"volumes ready\")\n\treturn nil\n}", "func waitForSystemdActiveState(units []string, maxAttempts int) (errch chan error) {\n\terrchan := make(chan error)\n\tvar wg sync.WaitGroup\n\tfor _, name := range units {\n\t\twg.Add(1)\n\t\tgo checkSystemdActiveState(name, maxAttempts, &wg, errchan)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errchan)\n\t}()\n\n\treturn errchan\n}", "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func (c *Client) WaitForResources(timeout time.Duration, resources []*manifest.MappingResult) error {\n\treturn wait.Poll(5*time.Second, timeout, func() (bool, error) {\n\t\tstatefulSets := []appsv1.StatefulSet{}\n\t\tdeployments := []deployment{}\n\t\tfor _, r := range resources {\n\t\t\tswitch r.Metadata.Kind {\n\t\t\tcase \"ConfigMap\":\n\t\t\tcase \"Service\":\n\t\t\tcase \"ReplicationController\":\n\t\t\tcase \"Pod\":\n\t\t\tcase \"Deployment\":\n\t\t\t\tcurrentDeployment, err := c.clientset.AppsV1().Deployments(r.Metadata.ObjectMeta.Namespace).Get(context.TODO(), r.Metadata.ObjectMeta.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\t// Find RS associated with deployment\n\t\t\t\tnewReplicaSet, err := c.getNewReplicaSet(currentDeployment)\n\t\t\t\tif err != nil || newReplicaSet == nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnewDeployment := deployment{\n\t\t\t\t\tnewReplicaSet,\n\t\t\t\t\tcurrentDeployment,\n\t\t\t\t}\n\t\t\t\tdeployments = append(deployments, newDeployment)\n\t\t\tcase \"StatefulSet\":\n\t\t\t\tsf, err := c.clientset.AppsV1().StatefulSets(r.Metadata.ObjectMeta.Namespace).Get(context.TODO(), r.Metadata.ObjectMeta.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tstatefulSets = append(statefulSets, *sf)\n\t\t\t}\n\t\t}\n\t\tisReady := c.statefulSetsReady(statefulSets) && c.deploymentsReady(deployments)\n\t\treturn isReady, nil\n\t})\n}", "func waitResults(clients []*SSHClient.SSHClient, results chan bool, c *cli.Context) {\n\ttimeout := time.After(time.Duration(c.Int(\"timeout\")) * time.Second)\n\n\tfor i := 0; i < len(clients); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\tres = !res\n\t\tcase <-timeout:\n\t\t\tfmt.Println(\"Timed out! Commands might be still running on the hosts\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func collectCRDResources(discovery discovery.DiscoveryInterface) ([]*metav1.APIResourceList, error) {\n\tresources, err := discovery.ServerResources()\n\tcrdResources := []*metav1.APIResourceList{}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, res := range resources {\n\t\tgv, err := schema.ParseGroupVersion(res.GroupVersion)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif gv.Group != \"apiextensions.k8s.io\" {\n\t\t\tcontinue\n\t\t}\n\t\temptyAPIResourceList := metav1.APIResourceList{\n\t\t\tGroupVersion: res.GroupVersion,\n\t\t}\n\t\temptyAPIResourceList.APIResources = findCRDGVRs(res.APIResources)\n\t\tcrdResources = append(crdResources, &emptyAPIResourceList)\n\t}\n\n\treturn crdResources, nil\n}", "func WaitForBKClusterToTerminate(t *testing.T, k8client client.Client, b *bkapi.BookkeeperCluster) error {\n\tlog.Printf(\"waiting for Bookkeeper cluster to terminate: %s\", b.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(b.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"bookkeeper_cluster\": b.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"bookkeeper cluster terminated: %s\", b.Name)\n\treturn nil\n}", "func (k *kubelet) waitForNodeReady() error {\n\tkc, _ := k.config.AdminConfig.ToYAMLString() //nolint:errcheck // This is checked in Validate().\n\n\tc, err := client.NewClient([]byte(kc))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating kubernetes client: %w\", err)\n\t}\n\n\treturn c.WaitForNodeReady(k.config.Name)\n}", "func (m *MeshReconciler) waitForIstioCRToBeDeleted(client client.Client) error {\n\tm.logger.Debug(\"waiting for Istio CR to be deleted\")\n\n\tbackoffConfig := backoff.ConstantBackoffConfig{\n\t\tDelay: time.Duration(backoffDelaySeconds) * time.Second,\n\t\tMaxRetries: backoffMaxretries,\n\t}\n\tbackoffPolicy := backoff.NewConstantBackoffPolicy(backoffConfig)\n\n\terr := backoff.Retry(func() error {\n\t\tvar istio v1beta1.Istio\n\t\terr := client.Get(context.Background(), types.NamespacedName{\n\t\t\tName: m.Configuration.name,\n\t\t\tNamespace: istioOperatorNamespace,\n\t\t}, &istio)\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.New(\"Istio CR still exists\")\n\t}, backoffPolicy)\n\n\treturn errors.WithStack(err)\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func WaitForCleanup() error {\n\tctx := context.Background()\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar (\n\t\tinterval = time.NewTicker(1 * time.Second)\n\t\ttimeout = time.NewTimer(1 * time.Minute)\n\t)\n\n\tfor range interval.C {\n\t\tselect {\n\t\tcase <-timeout.C:\n\t\t\treturn errors.New(\"timed out waiting for all easycontainers containers to get removed\")\n\t\tdefault:\n\t\t\t// only grab the containers created by easycontainers\n\t\t\targs := filters.NewArgs()\n\t\t\targs.Add(\"name\", \"/\"+prefix)\n\n\t\t\tcontainers, err := cli.ContainerList(ctx, types.ContainerListOptions{\n\t\t\t\tFilters: args,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(containers) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func (e *DockerRegistryServiceController) waitForDockerURLs(ready chan<- struct{}, stopCh <-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Wait for the stores to fill\n\tif !cache.WaitForCacheSync(stopCh, e.servicesSynced, e.secretsSynced) {\n\t\treturn\n\t}\n\n\t// after syncing, determine the current state and assume that we're up to date for it if you don't do this,\n\t// you'll get an initial storm as you mess with all the dockercfg secrets every time you startup\n\turls := e.getDockerRegistryLocations()\n\te.setRegistryURLs(urls...)\n\te.dockercfgController.SetDockerURLs(urls...)\n\tclose(e.dockerURLsInitialized)\n\tclose(ready)\n\n\treturn\n}", "func waitForHelmRunning(ctx context.Context, configPath string) error {\n\tfor {\n\t\tcmd := exec.Command(\"helm\", \"ls\", \"--kubeconfig\", configPath)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stderr = &out\n\t\tcmd.Run()\n\t\tif out.String() == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.Wrap(ctx.Err(), \"timed out waiting for helm to become ready\")\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t}\n}", "func ClusterCRD(t *testing.T) {\n\tctx := test.NewTestCtx(t)\n\tdefer ctx.Cleanup()\n\n\terr := helpers.DeployOperator(t, ctx)\n\thelpers.AssertNoError(t, err)\n\n\tt.Run(\"auto-installs-pipelines\", testsuites.ValidateAutoInstall)\n\tt.Run(\"deployment-recreation\", testsuites.ValidateDeploymentRecreate)\n\tt.Run(\"delete-pipelines\", testsuites.ValidateDeletion)\n}", "func (mgr *WatcherManager) runCrdWatcher(obj *apiextensionsV1beta1.CustomResourceDefinition) {\n\tgroupVersion := obj.Spec.Group + \"/\" + obj.Spec.Version\n\tcrdName := obj.Name\n\n\tcrdClient, ok := resources.CrdClientList[groupVersion]\n\n\tif !ok {\n\t\tcrdClient, ok = resources.CrdClientList[crdName]\n\t}\n\n\tif ok {\n\t\tvar runtimeObject k8sruntime.Object\n\t\tvar namespaced bool\n\t\tif obj.Spec.Scope == \"Cluster\" {\n\t\t\tnamespaced = false\n\t\t} else if obj.Spec.Scope == \"Namespaced\" {\n\t\t\tnamespaced = true\n\t\t}\n\n\t\t// init and run writer handler\n\t\taction := action.NewStorageAction(mgr.clusterID, obj.Spec.Names.Kind, mgr.storageService)\n\t\tmgr.writer.Handlers[obj.Spec.Names.Kind] = output.NewHandler(mgr.clusterID, obj.Spec.Names.Kind, action)\n\t\tstopChan := make(chan struct{})\n\t\tmgr.writer.Handlers[obj.Spec.Names.Kind].Run(stopChan)\n\n\t\t// init and run watcher\n\t\twatcher := NewWatcher(&crdClient, mgr.watchResource.Namespace, obj.Spec.Names.Kind, obj.Spec.Names.Plural, runtimeObject, mgr.writer, mgr.watchers, namespaced) // nolint\n\t\twatcher.stopChan = stopChan\n\t\tmgr.crdWatchers[obj.Spec.Names.Kind] = watcher\n\t\tglog.Infof(\"watcher manager, start list-watcher[%+v]\", obj.Spec.Names.Kind)\n\t\tgo watcher.Run(watcher.stopChan)\n\t}\n}", "func waitForConsistency() {\n\ttime.Sleep(500 * time.Millisecond)\n}", "func EnsureCRDCreated(cfg *rest.Config) (created bool, err error) {\n\tcrdVar, err := createCRDObject(helmRequestCRDYaml)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn crd.EnsureCRDCreated(cfg, crdVar)\n\t// return util.EnsureCRDCreated(cfg, CRD)\n}", "func (k Kubectl) WaitPodsReady(timeout time.Duration) error {\n\treturn utils.CheckUntil(5*time.Second, timeout, func() (bool, error) {\n\t\tcmd := kindCommand(\"kubectl get -n authelia pods --no-headers\")\n\t\tcmd.Stdout = nil\n\t\tcmd.Stderr = nil\n\t\toutput, _ := cmd.Output()\n\n\t\tlines := strings.Split(string(output), \"\\n\")\n\n\t\tnonEmptyLines := make([]string, 0)\n\t\tfor _, line := range lines {\n\t\t\tif line != \"\" {\n\t\t\t\tnonEmptyLines = append(nonEmptyLines, line)\n\t\t\t}\n\t\t}\n\n\t\tfor _, line := range nonEmptyLines {\n\t\t\tif !strings.Contains(line, \"1/1\") {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n}", "func DeployCR(bs *bootstrap.Bootstrap) {\n\tfor _, kind := range Kinds {\n\t\tif err := waitResourceReady(bs, apiGroupVersion, kind); err != nil {\n\t\t\tklog.Errorf(\"Failed to wait for resource ready with kind %s, apiGroupVersion: %s\", kind, apiGroupVersion)\n\t\t}\n\t}\n\n\tfor _, cr := range DeployCRs {\n\t\tfor {\n\t\t\tdone := deployResource(bs, cr)\n\t\t\tif done {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\n\t}\n}", "func waitKcpConn() *smux.Session {\n\tfor {\n\t\tif session, err := createKcpConn(); err == nil {\n\t\t\treturn session\n\t\t} else {\n\t\t\tlog.Println(\"re-connecting:\", err)\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}\n}", "func (m *Machine) WaitForPVCsDelete(namespace string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.PVCsDeleted(namespace)\n\t})\n}", "func (b *Botanist) WaitUntilContainerRuntimeResourcesReady(ctx context.Context) error {\n\tfns := []flow.TaskFn{}\n\n\tfor _, worker := range b.Shoot.Info.Spec.Provider.Workers {\n\t\tif worker.CRI != nil {\n\t\t\tfor _, containerRuntime := range worker.CRI.ContainerRuntimes {\n\t\t\t\tvar (\n\t\t\t\t\tname = getContainerRuntimeKey(containerRuntime.Type, worker.Name)\n\t\t\t\t\tnamespace = b.Shoot.SeedNamespace\n\t\t\t\t)\n\t\t\t\tfns = append(fns, func(ctx context.Context) error {\n\t\t\t\t\tif err := retry.UntilTimeout(ctx, DefaultInterval, shoot.ExtensionDefaultTimeout, func(ctx context.Context) (bool, error) {\n\t\t\t\t\t\treq := &extensionsv1alpha1.ContainerRuntime{}\n\t\t\t\t\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(namespace, name), req); err != nil {\n\t\t\t\t\t\t\treturn retry.SevereError(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif err := health.CheckExtensionObject(req); err != nil {\n\t\t\t\t\t\t\tb.Logger.WithError(err).Errorf(\"Container runtime %s/%s did not get ready yet\", namespace, name)\n\t\t\t\t\t\t\treturn retry.MinorError(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn retry.Ok()\n\t\t\t\t\t}); err != nil {\n\t\t\t\t\t\treturn gardencorev1beta1helper.DetermineError(err, fmt.Sprintf(\"failed waiting for container runtime %s to be ready: %v\", name, err))\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn flow.ParallelExitOnError(fns...)(ctx)\n}", "func (c *CRDRemover) removeCRDs(req *common.HcoRequest) {\n\tremoved := make([]schema.GroupKind, 0, len(c.crdsToRemove))\n\tunremoved := make([]schema.GroupKind, 0, len(c.crdsToRemove))\n\n\t// The deletion is performed concurrently for all CRDs.\n\tvar mutex sync.Mutex\n\tvar wg sync.WaitGroup\n\twg.Add(len(c.crdsToRemove))\n\n\tfor _, crdToBeRemoved := range c.crdsToRemove {\n\t\tgo func(crd schema.GroupKind) {\n\t\t\tisRemoved := c.removeCRD(req, crd)\n\n\t\t\tmutex.Lock()\n\t\t\tdefer mutex.Unlock()\n\n\t\t\tif isRemoved {\n\t\t\t\tremoved = append(removed, crd)\n\t\t\t} else {\n\t\t\t\tunremoved = append(unremoved, crd)\n\t\t\t}\n\n\t\t\twg.Done()\n\t\t}(crdToBeRemoved)\n\t}\n\n\twg.Wait()\n\n\t// For CRDs that failed to remove, we'll retry in the next reconciliation loop.\n\tc.crdsToRemove = unremoved\n\n\t// For CRDs that were successfully removed, we can proceed to remove\n\t// their corresponding entries from HCO.Status.RelatedObjects.\n\tc.relatedObjectsToRemove = append(c.relatedObjectsToRemove, removed...)\n}", "func (adminOrg *AdminOrg) CreateVdcWait(vdcDefinition *types.VdcConfiguration) error {\n\ttask, err := adminOrg.CreateVdc(vdcDefinition)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = task.WaitTaskCompletion()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't finish creating VDC %s\", err)\n\t}\n\treturn nil\n}", "func (b *Botanist) WaitUntilContainerRuntimeResourcesDeleted(ctx context.Context) error {\n\tvar (\n\t\tlastError *gardencorev1beta1.LastError\n\t\tcontainerRuntimes = &extensionsv1alpha1.ContainerRuntimeList{}\n\t)\n\n\tif err := b.K8sSeedClient.Client().List(ctx, containerRuntimes, client.InNamespace(b.Shoot.SeedNamespace)); err != nil {\n\t\treturn err\n\t}\n\n\tfns := make([]flow.TaskFn, 0, len(containerRuntimes.Items))\n\tfor _, containerRuntime := range containerRuntimes.Items {\n\t\tif containerRuntime.GetDeletionTimestamp() == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar (\n\t\t\tname = containerRuntime.Name\n\t\t\tnamespace = containerRuntime.Namespace\n\t\t)\n\n\t\tfns = append(fns, func(ctx context.Context) error {\n\t\t\tif err := retry.UntilTimeout(ctx, DefaultInterval, shoot.ExtensionDefaultTimeout, func(ctx context.Context) (bool, error) {\n\t\t\t\tretrievedContainerRuntime := extensionsv1alpha1.ContainerRuntime{}\n\t\t\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(namespace, name), &retrievedContainerRuntime); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\treturn retry.Ok()\n\t\t\t\t\t}\n\t\t\t\t\treturn retry.SevereError(err)\n\t\t\t\t}\n\n\t\t\t\tif lastErr := retrievedContainerRuntime.Status.LastError; lastErr != nil {\n\t\t\t\t\tb.Logger.Errorf(\"Container runtime %s did not get deleted yet, lastError is: %s\", name, lastErr.Description)\n\t\t\t\t\tlastError = lastErr\n\t\t\t\t}\n\n\t\t\t\treturn retry.MinorError(gardencorev1beta1helper.WrapWithLastError(fmt.Errorf(\"container runtime %s is still present\", name), lastError))\n\t\t\t}); err != nil {\n\t\t\t\tmessage := \"Failed waiting for container runtime delete\"\n\t\t\t\tif lastError != nil {\n\t\t\t\t\treturn gardencorev1beta1helper.DetermineError(errors.New(lastError.Description), fmt.Sprintf(\"%s: %s\", message, lastError.Description))\n\t\t\t\t}\n\t\t\t\treturn gardencorev1beta1helper.DetermineError(err, fmt.Sprintf(\"%s: %s\", message, err.Error()))\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn flow.Parallel(fns...)(ctx)\n}", "func (c *KafkaCluster) waitForRsteps(steps int) (int, error) {\n\tcancel := make(chan struct{})\n\tresult := make(chan int)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-cancel:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tcval := atomic.LoadInt32(c.rsteps)\n\t\t\t\tif cval >= int32(steps) {\n\t\t\t\t\tresult <- int(cval)\n\t\t\t\t}\n\t\t\t\ttime.Sleep(5 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase res := <-result:\n\t\treturn res, nil\n\tcase <-time.After(3 * time.Second):\n\t\tclose(cancel)\n\t\treturn 0, errors.New(\"Timed out waiting for steps\")\n\t}\n}", "func (tc *testContext) waitForServicesConfigMapDeletion(cmName string) error {\n\terr := wait.PollImmediate(retry.Interval, retry.ResourceChangeTimeout, func() (bool, error) {\n\t\t_, err := tc.client.K8s.CoreV1().ConfigMaps(wmcoNamespace).Get(context.TODO(), cmName, meta.GetOptions{})\n\t\tif err == nil {\n\t\t\t// Retry if the resource is found\n\t\t\treturn false, nil\n\t\t}\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"error retrieving ConfigMap: %s: %w\", cmName, err)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error waiting for ConfigMap deletion %s/%s: %w\", wmcoNamespace, cmName, err)\n\t}\n\treturn nil\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func (d *deploymentTester) waitForReadyReplicas() error {\n\tif err := wait.PollImmediate(pollInterval, pollTimeout, func() (bool, error) {\n\t\tdeployment, err := d.c.AppsV1().Deployments(d.deployment.Namespace).Get(context.TODO(), d.deployment.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to get deployment %q: %v\", d.deployment.Name, err)\n\t\t}\n\t\treturn deployment.Status.ReadyReplicas == *deployment.Spec.Replicas, nil\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to wait for .readyReplicas to equal .replicas: %v\", err)\n\t}\n\treturn nil\n}", "func WaitForZKClusterToTerminate(t *testing.T, k8client client.Client, z *zkapi.ZookeeperCluster) error {\n\tlog.Printf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(z.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitForWebhook(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerWebhookName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller webhook to became ready\")\n}", "func waitForClusterReachable(kubeconfig string) error {\n\tcfg, err := loadKubeconfigContents(kubeconfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Timeout = 15 * time.Second\n\tclient, err := clientset.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn wait.PollImmediate(15*time.Second, 20*time.Minute, func() (bool, error) {\n\t\t_, err := client.Core().Namespaces().Get(\"openshift-apiserver\", metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tlog.Printf(\"cluster is not yet reachable %s: %v\", cfg.Host, err)\n\t\treturn false, nil\n\t})\n}", "func waitSerial() {\n\tfor !machine.Serial.DTR() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}", "func (it *integTestSuite) TestNpmWorkloadCreateDelete(c *C) {\n\t// if not present create the default tenant\n\tc.Skip(\"Skipped till we figure out pushing the correct insertion profile in this test suite. THis is already tested in venice integ\")\n\tit.CreateTenant(\"default\")\n\t// create a wait channel\n\twaitCh := make(chan error, it.numAgents*2)\n\n\t// create a workload on each host\n\tfor i := range it.agents {\n\t\tmacAddr := fmt.Sprintf(\"0002.0000.%02x00\", i)\n\t\terr := it.CreateWorkload(\"default\", \"default\", fmt.Sprintf(\"testWorkload-%d\", i), fmt.Sprintf(\"testHost-%d\", i), macAddr, uint32(100+i), 1)\n\t\tAssertOk(c, err, \"Error creating workload\")\n\t}\n\n\t// verify the network got created for external vlan\n\tAssertEventually(c, func() (bool, interface{}) {\n\t\t_, nerr := it.npmCtrler.StateMgr.FindNetwork(\"default\", \"Network-Vlan-1\")\n\t\treturn (nerr == nil), nil\n\t}, \"Network not found in statemgr\")\n\n\t// wait for all endpoints to be propagated to other agents\n\tfor _, ag := range it.agents {\n\t\tgo func(ag *Dpagent) {\n\t\t\tfound := CheckEventually(func() (bool, interface{}) {\n\t\t\t\tepMeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t}\n\t\t\t\tendpoints, _ := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.List, epMeta)\n\t\t\t\treturn len(endpoints) == it.numAgents, nil\n\t\t\t}, \"10ms\", it.pollTimeout())\n\t\t\tif !found {\n\t\t\t\tepMeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t}\n\t\t\t\tendpoints, _ := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.List, epMeta)\n\t\t\t\tlog.Infof(\"Endpoint count expected [%v] found [%v]\", it.numAgents, len(endpoints))\n\t\t\t\twaitCh <- fmt.Errorf(\"Endpoint count incorrect in datapath\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfoundLocal := false\n\t\t\tfor idx := range it.agents {\n\t\t\t\tmacAddr := fmt.Sprintf(\"0002.0000.%02x00\", idx)\n\t\t\t\tname, _ := strconv.ParseMacAddr(macAddr)\n\t\t\t\tepname := fmt.Sprintf(\"testWorkload-%d-%s\", idx, name)\n\t\t\t\tepmeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t\tObjectMeta: api.ObjectMeta{\n\t\t\t\t\t\tTenant: \"default\",\n\t\t\t\t\t\tNamespace: \"default\",\n\t\t\t\t\t\tName: epname,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tsep, perr := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.Get, epmeta)\n\t\t\t\tif perr != nil {\n\t\t\t\t\twaitCh <- fmt.Errorf(\"Endpoint %s not found in netagent, err=%v\", epname, perr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif sep[0].Spec.NodeUUID == ag.dscAgent.InfraAPI.GetDscName() {\n\t\t\t\t\tfoundLocal = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !foundLocal {\n\t\t\t\twaitCh <- fmt.Errorf(\"No local endpoint found on %s\", ag.dscAgent.InfraAPI.GetDscName())\n\t\t\t\treturn\n\t\t\t}\n\t\t\twaitCh <- nil\n\t\t}(ag)\n\t}\n\n\t// wait for all goroutines to complete\n\tfor i := 0; i < it.numAgents; i++ {\n\t\tAssertOk(c, <-waitCh, \"Endpoint info incorrect in datapath\")\n\n\t}\n\n\t// now delete the workloads\n\tfor idx := range it.agents {\n\t\terr := it.DeleteWorkload(\"default\", \"default\", fmt.Sprintf(\"testWorkload-%d\", idx))\n\t\tAssertOk(c, err, \"Error deleting workload\")\n\t}\n\n\tfor _, ag := range it.agents {\n\t\tgo func(ag *Dpagent) {\n\t\t\tif !CheckEventually(func() (bool, interface{}) {\n\t\t\t\tepMeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t}\n\t\t\t\tendpoints, _ := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.List, epMeta)\n\t\t\t\treturn len(endpoints) == 0, nil\n\t\t\t}, \"10ms\", it.pollTimeout()) {\n\t\t\t\twaitCh <- fmt.Errorf(\"Endpoint was not deleted from datapath\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twaitCh <- nil\n\t\t}(ag)\n\t}\n\n\t// wait for all goroutines to complete\n\tfor i := 0; i < it.numAgents; i++ {\n\t\tAssertOk(c, <-waitCh, \"Endpoint delete error\")\n\t}\n\n\t// delete the network\n\terr := it.DeleteNetwork(\"default\", \"Network-Vlan-1\")\n\tc.Assert(err, IsNil)\n\tAssertEventually(c, func() (bool, interface{}) {\n\t\t_, nerr := it.npmCtrler.StateMgr.FindNetwork(\"default\", \"Network-Vlan-1\")\n\t\treturn (nerr != nil), nil\n\t}, \"Network still found in statemgr\")\n}", "func (h *CRDHandler) EnsureCRD(meta *CRDMeta, namespacedScoped bool) (*apiextensionsv1.CustomResourceDefinition, error) {\n\tcrd, err := h.createOrUpdateCRD(meta, namespacedScoped)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// After CRD creation, it might take a few seconds for the RESTful API endpoint\n\t// to be created. Keeps watching the Established condition of BackendConfig\n\t// CRD to be true.\n\tif err := wait.PollImmediate(checkCRDEstablishedInterval, checkCRDEstablishedTimeout, func() (bool, error) {\n\t\tcrd, err = h.client.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), crd.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tfor _, c := range crd.Status.Conditions {\n\t\t\tif c.Type == apiextensionsv1.Established && c.Status == apiextensionsv1.ConditionTrue {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"timed out waiting for %v CRD to become Established: %v\", meta.kind, err)\n\t}\n\n\tklog.V(0).Infof(\"%v CRD is Established.\", meta.kind)\n\treturn crd, nil\n}", "func CreateOCRJobs(\n\tocrInstances []contracts.OffchainAggregator,\n\tbootstrapNode *client.ChainlinkK8sClient,\n\tworkerNodes []*client.ChainlinkK8sClient,\n\tmockValue int,\n\tmockserver *ctfClient.MockserverClient,\n) error {\n\tfor _, ocrInstance := range ocrInstances {\n\t\tbootstrapP2PIds, err := bootstrapNode.MustReadP2PKeys()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"reading P2P keys from bootstrap node have failed: %w\", err)\n\t\t}\n\t\tbootstrapP2PId := bootstrapP2PIds.Data[0].Attributes.PeerID\n\t\tbootstrapSpec := &client.OCRBootstrapJobSpec{\n\t\t\tName: fmt.Sprintf(\"bootstrap-%s\", uuid.New().String()),\n\t\t\tContractAddress: ocrInstance.Address(),\n\t\t\tP2PPeerID: bootstrapP2PId,\n\t\t\tIsBootstrapPeer: true,\n\t\t}\n\t\t_, err = bootstrapNode.MustCreateJob(bootstrapSpec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"creating bootstrap job have failed: %w\", err)\n\t\t}\n\n\t\tfor _, node := range workerNodes {\n\t\t\tnodeP2PIds, err := node.MustReadP2PKeys()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"reading P2P keys from OCR node have failed: %w\", err)\n\t\t\t}\n\t\t\tnodeP2PId := nodeP2PIds.Data[0].Attributes.PeerID\n\t\t\tnodeTransmitterAddress, err := node.PrimaryEthAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"getting primary ETH address from OCR node have failed: %w\", err)\n\t\t\t}\n\t\t\tnodeOCRKeys, err := node.MustReadOCRKeys()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"getting OCR keys from OCR node have failed: %w\", err)\n\t\t\t}\n\t\t\tnodeOCRKeyId := nodeOCRKeys.Data[0].ID\n\n\t\t\tnodeContractPairID, err := BuildNodeContractPairID(node, ocrInstance)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbta := &client.BridgeTypeAttributes{\n\t\t\t\tName: nodeContractPairID,\n\t\t\t\tURL: fmt.Sprintf(\"%s/%s\", mockserver.Config.ClusterURL, strings.TrimPrefix(nodeContractPairID, \"/\")),\n\t\t\t}\n\t\t\terr = SetAdapterResponse(mockValue, ocrInstance, node, mockserver)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"setting adapter response for OCR node failed: %w\", err)\n\t\t\t}\n\t\t\terr = node.MustCreateBridge(bta)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating bridge job have failed: %w\", err)\n\t\t\t}\n\n\t\t\tbootstrapPeers := []*client.ChainlinkClient{bootstrapNode.ChainlinkClient}\n\t\t\tocrSpec := &client.OCRTaskJobSpec{\n\t\t\t\tContractAddress: ocrInstance.Address(),\n\t\t\t\tP2PPeerID: nodeP2PId,\n\t\t\t\tP2PBootstrapPeers: bootstrapPeers,\n\t\t\t\tKeyBundleID: nodeOCRKeyId,\n\t\t\t\tTransmitterAddress: nodeTransmitterAddress,\n\t\t\t\tObservationSource: client.ObservationSourceSpecBridge(bta),\n\t\t\t}\n\t\t\t_, err = node.MustCreateJob(ocrSpec)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating OCR task job on OCR node have failed: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (cm *CertificateManager) WaitForCertDirReady() error {\n\ttimeout := time.Minute * 5\n\tselect {\n\tcase <-cm.certDirReady():\n\t\treturn nil\n\tcase <-time.After(timeout):\n\t\treturn fmt.Errorf(\"timed out after %s\", timeout.String())\n\t}\n}", "func checkNodesReady(c *client.Client, nt time.Duration, expect int) ([]string, error) {\n\t// First, keep getting all of the nodes until we get the number we expect.\n\tvar nodeList *api.NodeList\n\tvar errLast error\n\tstart := time.Now()\n\tfound := wait.Poll(poll, nt, func() (bool, error) {\n\t\t// Even though listNodes(...) has its own retries, a rolling-update\n\t\t// (GCE/GKE implementation of restart) can complete before the apiserver\n\t\t// knows about all of the nodes. Thus, we retry the list nodes call\n\t\t// until we get the expected number of nodes.\n\t\tnodeList, errLast = listNodes(c, labels.Everything(), fields.Everything())\n\t\tif errLast != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif len(nodeList.Items) != expect {\n\t\t\terrLast = fmt.Errorf(\"expected to find %d nodes but found only %d (%v elapsed)\",\n\t\t\t\texpect, len(nodeList.Items), time.Since(start))\n\t\t\tLogf(\"%v\", errLast)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}) == nil\n\tnodeNames := make([]string, len(nodeList.Items))\n\tfor i, n := range nodeList.Items {\n\t\tnodeNames[i] = n.ObjectMeta.Name\n\t}\n\tif !found {\n\t\treturn nodeNames, fmt.Errorf(\"couldn't find %d nodes within %v; last error: %v\",\n\t\t\texpect, nt, errLast)\n\t}\n\tLogf(\"Successfully found %d nodes\", expect)\n\n\t// Next, ensure in parallel that all the nodes are ready. We subtract the\n\t// time we spent waiting above.\n\ttimeout := nt - time.Since(start)\n\tresult := make(chan bool, len(nodeList.Items))\n\tfor _, n := range nodeNames {\n\t\tn := n\n\t\tgo func() { result <- waitForNodeToBeReady(c, n, timeout) }()\n\t}\n\tfailed := false\n\t// TODO(mbforbes): Change to `for range` syntax once we support only Go\n\t// >= 1.4.\n\tfor i := range nodeList.Items {\n\t\t_ = i\n\t\tif !<-result {\n\t\t\tfailed = true\n\t\t}\n\t}\n\tif failed {\n\t\treturn nodeNames, fmt.Errorf(\"at least one node failed to be ready\")\n\t}\n\treturn nodeNames, nil\n}", "func (b *Botanist) WaitUntilEtcdReady(ctx context.Context) error {\n\tvar (\n\t\tretryCountUntilSevere int\n\t\tinterval = 5 * time.Second\n\t\tsevereThreshold = 30 * time.Second\n\t\ttimeout = 5 * time.Minute\n\t)\n\n\treturn retry.UntilTimeout(ctx, interval, timeout, func(ctx context.Context) (done bool, err error) {\n\t\tretryCountUntilSevere++\n\n\t\tetcdList := &druidv1alpha1.EtcdList{}\n\t\tif err := b.K8sSeedClient.DirectClient().List(ctx, etcdList,\n\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\tclient.MatchingLabels{\"garden.sapcloud.io/role\": \"controlplane\"},\n\t\t); err != nil {\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\n\t\tif n := len(etcdList.Items); n < 2 {\n\t\t\tb.Logger.Info(\"Waiting until the etcd gets created...\")\n\t\t\treturn retry.MinorError(fmt.Errorf(\"only %d/%d etcd resources found\", n, 2))\n\t\t}\n\n\t\tvar lastErrors error\n\n\t\tfor _, etcd := range etcdList.Items {\n\t\t\tswitch {\n\t\t\tcase etcd.Status.LastError != nil:\n\t\t\t\treturn retry.MinorOrSevereError(retryCountUntilSevere, int(severeThreshold.Nanoseconds()/interval.Nanoseconds()), fmt.Errorf(\"%s reconciliation errored: %s\", etcd.Name, *etcd.Status.LastError))\n\t\t\tcase etcd.DeletionTimestamp != nil:\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s unexpectedly has a deletion timestamp\", etcd.Name))\n\t\t\tcase etcd.Status.ObservedGeneration == nil || etcd.Generation != *etcd.Status.ObservedGeneration:\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s reconciliation pending\", etcd.Name))\n\t\t\tcase metav1.HasAnnotation(etcd.ObjectMeta, v1beta1constants.GardenerOperation):\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s reconciliation in process\", etcd.Name))\n\t\t\tcase !utils.IsTrue(etcd.Status.Ready):\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s is not ready yet\", etcd.Name))\n\t\t\t}\n\t\t}\n\n\t\tif lastErrors == nil {\n\t\t\treturn retry.Ok()\n\t\t}\n\n\t\tb.Logger.Info(\"Waiting until the both etcds are ready...\")\n\t\treturn retry.MinorError(lastErrors)\n\t})\n}", "func waitUntilRDSInstanceCreated(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\trdsInstanceName := rdsClusterName + \"-0\" // TODO: this should be handled better\n\n\tinput := &rds.DescribeDBInstancesInput{\n\t\tDBInstanceIdentifier: aws.String(rdsInstanceName),\n\t}\n\n\tstart := time.Now()\n\tmaxWaitAttempts := 120\n\n\tfmt.Printf(\"Wait until RDS instance [%v] in cluster [%v] is fully created ...\\n\", rdsInstanceName, rdsClusterName)\n\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start)\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Instance creation elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBInstances(input)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Wait RDS instance create err %v\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Instance status: [%s]\\n\", *resp.DBInstances[0].DBInstanceStatus)\n\t\tif *resp.DBInstances[0].DBInstanceStatus== \"available\" {\n\t\t\tfmt.Printf(\"RDS instance [%v] created successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\tfmt.Printf(\"RDS instance [%v] created successfully in RDS cluster [%v]\\n\", rdsInstanceName, rdsClusterName)\n\treturn nil\n}", "func (c *EEBus) waitForConnection() error {\n\ttimeout := time.After(90 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\treturn os.ErrDeadlineExceeded\n\t\tcase connected := <-c.connectedC:\n\t\t\tif connected {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\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 (c *Client) WaitForDaemonSet(ns, name string, timeout time.Duration) error {\n\tif c.ApplyDryRun {\n\t\treturn nil\n\t}\n\tclient, err := c.GetClientset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdaemonsets := client.AppsV1().DaemonSets(ns)\n\tid := Name{Kind: \"Daemonset\", Name: name, Namespace: ns}\n\tstart := time.Now()\n\tmsg := false\n\tfor {\n\t\tdaemonset, err := daemonsets.Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif start.Add(timeout).Before(time.Now()) {\n\t\t\treturn fmt.Errorf(\"%s timeout waiting for daemonset to become ready\", id)\n\t\t}\n\n\t\tif daemonset != nil && daemonset.Status.NumberReady >= 1 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !msg {\n\t\t\tc.Infof(\"%s ⏳ waiting for at least 1 pod\", id)\n\t\t\tmsg = true\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}", "func recordCRs(namespaceDir string, namespace string) error {\n\tcrds, err := kubeList(namespace, \"crd\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// record all unique CRs floating about\n\tfor _, crd := range crds {\n\t\t// consider all installed CRDs that are solo-managed\n\t\tif !strings.Contains(crd, \"solo.io\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// if there are any existing CRs corresponding to this CRD\n\t\tcrs, err := kubeList(namespace, crd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(crs) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcrdDir := filepath.Join(namespaceDir, crd)\n\t\tif err := os.MkdirAll(crdDir, os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// we record each one in its own .yaml representation\n\t\tfor _, cr := range crs {\n\t\t\tf := fileAtPath(filepath.Join(crdDir, cr+\".yaml\"))\n\t\t\tcrDetails, err := kubeGet(namespace, crd, cr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tf.WriteString(crDetails)\n\t\t\tf.Close()\n\t\t}\n\t}\n\n\treturn nil\n}", "func WaitForDeletion(ctx context.Context, mcpKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {\n\t\tmcp := &machineconfigv1.MachineConfigPool{}\n\t\tif err := testclient.Client.Get(ctx, mcpKey, mcp); apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func waitForNewChildLB(ctx context.Context, ch *testutils.Channel) (*fakeChildBalancer, error) {\n\tval, err := ch.Receive(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error when waiting for a new edsLB: %v\", err)\n\t}\n\treturn val.(*fakeChildBalancer), nil\n}", "func WaitForClusterToTerminate(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) error {\n\tt.Logf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()}).String(),\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.CoreV1().Pods(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList, err := f.KubeClient.CoreV1().PersistentVolumeClaims(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Logf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitForAwsResource(name, event string, c *client.Client) error {\n\ttick := time.Tick(time.Second * 2)\n\ttimeout := time.After(time.Minute * 5)\n\tfmt.Printf(\"Waiting for %s \", name)\n\tfailedEv := event + \"_FAILED\"\n\tcompletedEv := event + \"_COMPLETE\"\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-tick:\n\t\t\trs, err := c.GetResource(name)\n\t\t\tif err != nil {\n\t\t\t\tif event == \"DELETE\" {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfmt.Print(\".\")\n\t\t\tif rs.Status == failedEv {\n\t\t\t\treturn fmt.Errorf(\"%s failed because of \\\"%s\\\"\", event, rs.StatusReason)\n\t\t\t}\n\t\t\tif rs.Status == completedEv {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\tfmt.Print(\"timeout (5 minutes). Skipping\")\n\t\t\tbreak Loop\n\t\t}\n\t}\n\n\treturn nil\n}", "func waitForClusterToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool { return cluster != nil },\n\t)\n}", "func TestRktDriver_Start_Wait_Stop_DNS(t *testing.T) {\n\tctestutil.RktCompatible(t)\n\tif !testutil.IsCI() {\n\t\tt.Parallel()\n\t}\n\n\trequire := require.New(t)\n\td := NewRktDriver(testlog.HCLogger(t))\n\tharness := dtestutil.NewDriverHarness(t, d)\n\n\ttask := &drivers.TaskConfig{\n\t\tID: uuid.Generate(),\n\t\tAllocID: uuid.Generate(),\n\t\tName: \"etcd\",\n\t\tResources: &drivers.Resources{\n\t\t\tNomadResources: &structs.AllocatedTaskResources{\n\t\t\t\tMemory: structs.AllocatedMemoryResources{\n\t\t\t\t\tMemoryMB: 128,\n\t\t\t\t},\n\t\t\t\tCpu: structs.AllocatedCpuResources{\n\t\t\t\t\tCpuShares: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t\tLinuxResources: &drivers.LinuxResources{\n\t\t\t\tMemoryLimitBytes: 134217728,\n\t\t\t\tCPUShares: 100,\n\t\t\t},\n\t\t},\n\t}\n\n\ttc := &TaskConfig{\n\t\tTrustPrefix: \"coreos.com/etcd\",\n\t\tImageName: \"coreos.com/etcd:v2.0.4\",\n\t\tCommand: \"/etcd\",\n\t\tDNSServers: []string{\"8.8.8.8\", \"8.8.4.4\"},\n\t\tDNSSearchDomains: []string{\"example.com\", \"example.org\", \"example.net\"},\n\t\tNet: []string{\"host\"},\n\t}\n\trequire.NoError(task.EncodeConcreteDriverConfig(&tc))\n\ttesttask.SetTaskConfigEnv(task)\n\tcleanup := harness.MkAllocDir(task, true)\n\tdefer cleanup()\n\n\thandle, driverNet, err := harness.StartTask(task)\n\trequire.NoError(err)\n\trequire.Nil(driverNet)\n\n\tch, err := harness.WaitTask(context.Background(), handle.Config.ID)\n\trequire.NoError(err)\n\n\trequire.NoError(harness.WaitUntilStarted(task.ID, 1*time.Second))\n\n\tgo func() {\n\t\tharness.StopTask(task.ID, 2*time.Second, \"SIGTERM\")\n\t}()\n\n\tselect {\n\tcase result := <-ch:\n\t\trequire.Equal(int(unix.SIGTERM), result.Signal)\n\tcase <-time.After(10 * time.Second):\n\t\trequire.Fail(\"timeout waiting for task to shutdown\")\n\t}\n\n\t// Ensure that the task is marked as dead, but account\n\t// for WaitTask() closing channel before internal state is updated\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tstatus, err := harness.InspectTask(task.ID)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"inspecting task failed: %v\", err)\n\t\t}\n\t\tif status.State != drivers.TaskStateExited {\n\t\t\treturn false, fmt.Errorf(\"task hasn't exited yet; status: %v\", status.State)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.NoError(err)\n\t})\n\n\trequire.NoError(harness.DestroyTask(task.ID, true))\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func TestWaitUntilAllNodesReady(t *testing.T) {\n\tt.Parallel()\n\n\toptions := NewKubectlOptions(\"\", \"\", \"default\")\n\n\tWaitUntilAllNodesReady(t, options, 12, 5*time.Second)\n\n\tnodes := GetNodes(t, options)\n\tnodeNames := map[string]bool{}\n\tfor _, node := range nodes {\n\t\tnodeNames[node.Name] = true\n\t}\n\n\treadyNodes := GetReadyNodes(t, options)\n\treadyNodeNames := map[string]bool{}\n\tfor _, node := range readyNodes {\n\t\treadyNodeNames[node.Name] = true\n\t}\n\n\tassert.Equal(t, nodeNames, readyNodeNames)\n}", "func wait(ctx context.Context, c TimedActuator,\n\tresChan chan error, cancel context.CancelFunc) error {\n\tif timeout := c.GetTimeout(); timeout != nil {\n\t\treturn waitWithTimeout(ctx, resChan, *timeout, cancel)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase err := <-resChan:\n\t\t\tif err != nil {\n\t\t\t\tcancel()\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *myClient) batchCreateSelfServiceContainer(containerList ...PatientContainer) (resultsList []map[string]interface{}, err error) {\n\tfor _, v := range containerList {\n\t\tif result, err := c.createSelfServiceContainer(v, false); result != nil && err == nil && (result[\"job\"] != nil || result[\"action\"] != nil) {\n\t\t\tresultsList = append(resultsList, result)\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tc.jobWaiter(resultsList...)\n\n\treturn resultsList, err\n}", "func WaitForCondition(mcpName string, conditionType machineconfigv1.MachineConfigPoolConditionType, conditionStatus corev1.ConditionStatus) {\n\n\tvar cnfNodes []corev1.Node\n\trunningOnSingleNode, err := cluster.IsSingleNode()\n\tExpectWithOffset(1, err).ToNot(HaveOccurred())\n\t// checking in eventually as in case of single node cluster the only node may\n\t// be rebooting\n\tEventuallyWithOffset(1, func() error {\n\t\tmcp, err := GetByName(mcpName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting MCP by name\")\n\t\t}\n\n\t\tnodeLabels := mcp.Spec.NodeSelector.MatchLabels\n\t\tkey, _ := components.GetFirstKeyAndValue(nodeLabels)\n\t\treq, err := labels.NewRequirement(key, selection.Exists, []string{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed creating node selector\")\n\t\t}\n\n\t\tselector := labels.NewSelector()\n\t\tselector = selector.Add(*req)\n\t\tcnfNodes, err = nodes.GetBySelector(selector)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting nodes by selector\")\n\t\t}\n\n\t\ttestlog.Infof(\"MCP %q is targeting %v node(s)\", mcp.Name, len(cnfNodes))\n\t\treturn nil\n\t}, cluster.ComputeTestTimeout(10*time.Minute, runningOnSingleNode), 5*time.Second).ShouldNot(HaveOccurred(), \"Failed to find CNF nodes by MCP %q\", mcpName)\n\n\t// timeout should be based on the number of worker-cnf nodes\n\ttimeout := time.Duration(len(cnfNodes)*mcpUpdateTimeoutPerNode) * time.Minute\n\tif len(cnfNodes) == 0 {\n\t\ttimeout = 2 * time.Minute\n\t}\n\n\tEventuallyWithOffset(1, func() corev1.ConditionStatus {\n\t\treturn GetConditionStatus(mcpName, conditionType)\n\t}, cluster.ComputeTestTimeout(timeout, runningOnSingleNode), 30*time.Second).Should(Equal(conditionStatus), \"Failed to find condition status by MCP %q\", mcpName)\n}", "func (c *knDynamicClient) ListCRDs(options metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\tgvr := schema.GroupVersionResource{\n\t\tGroup: crdGroup,\n\t\tVersion: crdVersion,\n\t\tResource: crdKinds,\n\t}\n\n\tuList, err := c.client.Resource(gvr).List(options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn uList, nil\n}", "func (c *myClient) discoverCDB(envName, cdbName, username, password string, wait bool) (results map[string]interface{}, err error) {\n\tnamespace := \"sourceconfig\"\n\tscObj, err := c.findSourceCongfigByNameAndEnvironmentName(cdbName, envName)\n\tscObjRef := scObj[\"reference\"]\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := fmt.Sprintf(\"%s/%s\", namespace, scObjRef)\n\tpostBody := fmt.Sprintf(`{\n\t\t\"type\": \"OracleSIConfig\", \n\t\t\"user\": \"%s\",\n\t\t\"credentials\": {\n\t\t\t\"type\": \"PasswordCredential\",\n\t\t\t\"password\": \"%s\"\n\t\t\t}\n\t\t}`, username, password)\n\taction, _, err := c.httpPost(url, postBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif wait {\n\t\tc.jobWaiter(action)\n\t}\n\treturn action, err\n\n}", "func WaitForPodsRunningReady(c clientset.Interface, ns string, minPods, allowedNotReadyPods int32, timeout time.Duration, ignoreLabels map[string]string) error {\n\tif minPods == -1 || allowedNotReadyPods == -1 {\n\t\treturn nil\n\t}\n\n\tignoreSelector := labels.SelectorFromSet(map[string]string{})\n\tstart := time.Now()\n\tframework.Logf(\"Waiting up to %v for all pods (need at least %d) in namespace '%s' to be running and ready\",\n\t\ttimeout, minPods, ns)\n\tvar ignoreNotReady bool\n\tbadPods := []v1.Pod{}\n\tdesiredPods := 0\n\tnotReady := int32(0)\n\tvar lastAPIError error\n\n\tif wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\t// We get the new list of pods, replication controllers, and\n\t\t// replica sets in every iteration because more pods come\n\t\t// online during startup and we want to ensure they are also\n\t\t// checked.\n\t\treplicas, replicaOk := int32(0), int32(0)\n\t\t// Clear API error from the last attempt in case the following calls succeed.\n\t\tlastAPIError = nil\n\n\t\trcList, err := c.CoreV1().ReplicationControllers(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tlastAPIError = err\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, false, \"listing replication controllers in namespace %s\", ns)\n\t\t}\n\t\tfor _, rc := range rcList.Items {\n\t\t\treplicas += *rc.Spec.Replicas\n\t\t\treplicaOk += rc.Status.ReadyReplicas\n\t\t}\n\n\t\trsList, err := c.AppsV1().ReplicaSets(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tlastAPIError = err\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, false, \"listing replication sets in namespace %s\", ns)\n\t\t}\n\t\tfor _, rs := range rsList.Items {\n\t\t\treplicas += *rs.Spec.Replicas\n\t\t\treplicaOk += rs.Status.ReadyReplicas\n\t\t}\n\n\t\tpodList, err := c.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tlastAPIError = err\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, false, \"listing pods in namespace %s\", ns)\n\t\t}\n\t\tnOk := int32(0)\n\t\tnotReady = int32(0)\n\t\tbadPods = []v1.Pod{}\n\t\tdesiredPods = len(podList.Items)\n\t\tfor _, pod := range podList.Items {\n\t\t\tif len(ignoreLabels) != 0 && ignoreSelector.Matches(labels.Set(pod.Labels)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tres, err := testutils.PodRunningReady(&pod)\n\t\t\tswitch {\n\t\t\tcase res && err == nil:\n\t\t\t\tnOk++\n\t\t\tcase pod.Status.Phase == v1.PodSucceeded:\n\t\t\t\tframework.Logf(\"The status of Pod %s is Succeeded, skipping waiting\", pod.ObjectMeta.Name)\n\t\t\t\t// it doesn't make sense to wait for this pod\n\t\t\t\tcontinue\n\t\t\tcase pod.Status.Phase != v1.PodFailed:\n\t\t\t\tframework.Logf(\"The status of Pod %s is %s (Ready = false), waiting for it to be either Running (with Ready = true) or Failed\", pod.ObjectMeta.Name, pod.Status.Phase)\n\t\t\t\tnotReady++\n\t\t\t\tbadPods = append(badPods, pod)\n\t\t\tdefault:\n\t\t\t\tif metav1.GetControllerOf(&pod) == nil {\n\t\t\t\t\tframework.Logf(\"Pod %s is Failed, but it's not controlled by a controller\", pod.ObjectMeta.Name)\n\t\t\t\t\tbadPods = append(badPods, pod)\n\t\t\t\t}\n\t\t\t\t// ignore failed pods that are controlled by some controller\n\t\t\t}\n\t\t}\n\n\t\tframework.Logf(\"%d / %d pods in namespace '%s' are running and ready (%d seconds elapsed)\",\n\t\t\tnOk, len(podList.Items), ns, int(time.Since(start).Seconds()))\n\t\tframework.Logf(\"expected %d pod replicas in namespace '%s', %d are Running and Ready.\", replicas, ns, replicaOk)\n\n\t\tif replicaOk == replicas && nOk >= minPods && len(badPods) == 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\tignoreNotReady = (notReady <= allowedNotReadyPods)\n\t\tLogPodStates(badPods)\n\t\treturn false, nil\n\t}) != nil {\n\t\tif !ignoreNotReady {\n\t\t\treturn errorBadPodsStates(badPods, desiredPods, ns, \"RUNNING and READY\", timeout, lastAPIError)\n\t\t}\n\t\tframework.Logf(\"Number of not-ready pods (%d) is below the allowed threshold (%d).\", notReady, allowedNotReadyPods)\n\t}\n\treturn nil\n}", "func ForDaemonSetReady(clName string, c kubernetes.Interface, namespace, daemonSetName string) error {\n\tctx := context.Background()\n\tlog.Debugf(\"Waiting up to %v for %s daemon set roll out %s ...\", defaults.WaitDurationResources, daemonSetName, clName)\n\tdeploymentContext, cancel := context.WithTimeout(ctx, defaults.WaitDurationResources)\n\twait.Until(func() {\n\t\tdaemonSet, err := c.AppsV1().DaemonSets(namespace).Get(daemonSetName, metav1.GetOptions{})\n\t\tif err == nil && daemonSet.Status.CurrentNumberScheduled > 0 {\n\t\t\tif daemonSet.Status.NumberReady == daemonSet.Status.DesiredNumberScheduled {\n\t\t\t\tlog.Infof(\"✔ %s successfully rolled out to %s, ready replicas: %v\", daemonSetName, clName, daemonSet.Status.NumberReady)\n\t\t\t\tcancel()\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"Still waiting for %s daemon set roll out for %s, ready replicas: %v\", daemonSetName, clName, daemonSet.Status.NumberReady)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debugf(\"Still waiting for %s daemon set roll out %s ...\", daemonSetName, clName)\n\t\t}\n\t}, 5*time.Second, deploymentContext.Done())\n\terr := deploymentContext.Err()\n\tif err != nil && err != context.Canceled {\n\t\treturn errors.Wrapf(err, \"Error waiting for %s daemon set roll out.\", daemonSetName)\n\t}\n\treturn nil\n}", "func WaitForInfraServices(ctx context.Context, kc *kubernetes.Clientset) error {\n\tfor _, app := range daemonsetWhitelist {\n\t\tlog.Infof(\"checking daemonset %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\tds, err := kc.AppsV1().DaemonSets(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\treturn ds.Status.DesiredNumberScheduled == ds.Status.CurrentNumberScheduled &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.NumberReady &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.UpdatedNumberScheduled &&\n\t\t\t\t\tds.Generation == ds.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, app := range deploymentWhitelist {\n\t\tlog.Infof(\"checking deployment %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\td, err := kc.AppsV1().Deployments(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\tspecReplicas := int32(1)\n\t\t\t\tif d.Spec.Replicas != nil {\n\t\t\t\t\tspecReplicas = *d.Spec.Replicas\n\t\t\t\t}\n\n\t\t\t\treturn specReplicas == d.Status.Replicas &&\n\t\t\t\t\tspecReplicas == d.Status.ReadyReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.AvailableReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.UpdatedReplicas &&\n\t\t\t\t\td.Generation == d.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func WaitForWantedNodes(cfg cbgt.Cfg, wantedNodes []string,\n\tcancelCh <-chan struct{}, secs int, ignoreWaitTimeOut bool) (\n\t[]string, error) {\n\tvar nodeDefWantedUUIDs []string\n\tfor i := 0; i < secs; i++ {\n\t\tselect {\n\t\tcase <-cancelCh:\n\t\t\treturn nil, ErrCtlCanceled\n\t\tdefault:\n\t\t}\n\n\t\tnodeDefsWanted, _, err :=\n\t\t\tcbgt.CfgGetNodeDefs(cfg, cbgt.NODE_DEFS_WANTED)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnodeDefWantedUUIDs = nil\n\t\tfor _, nodeDef := range nodeDefsWanted.NodeDefs {\n\t\t\tnodeDefWantedUUIDs = append(nodeDefWantedUUIDs, nodeDef.UUID)\n\t\t}\n\t\tif len(cbgt.StringsRemoveStrings(wantedNodes, nodeDefWantedUUIDs)) <= 0 {\n\t\t\treturn cbgt.StringsRemoveStrings(nodeDefWantedUUIDs, wantedNodes), nil\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\tif ignoreWaitTimeOut {\n\t\tlog.Printf(\"ctl: WaitForWantedNodes ignoreWaitTimeOut\")\n\t\treturn cbgt.StringsRemoveStrings(nodeDefWantedUUIDs, wantedNodes), nil\n\t}\n\treturn nil, fmt.Errorf(\"ctl: WaitForWantedNodes\"+\n\t\t\" could not attain wantedNodes: %#v,\"+\n\t\t\" only reached nodeDefWantedUUIDs: %#v\",\n\t\twantedNodes, nodeDefWantedUUIDs)\n}", "func cassandraClusterRollingRestartDCTest(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) {\n\tnamespace, err := ctx.GetWatchNamespace()\n\tif err != nil {\n\t\tt.Fatalf(\"Could not get namespace: %v\", err)\n\t}\n\n\tt.Log(\"Create the Cluster with 1 DC consisting of 1 rack of 1 node\")\n\n\tcc := mye2eutil.HelperInitCluster(t, f, ctx, \"cassandracluster-1DC.yaml\", namespace)\n\tt.Logf(\"Create CassandraCluster cassandracluster-1DC.yaml in namespace %s\", namespace)\n\n\t// use TestCtx's create helper to create the object and add a cleanup function for the new object\n\tif err := f.Client.Create(goctx.TODO(), cc, &framework.CleanupOptions{TestContext: ctx,\n\t\tTimeout: mye2eutil.CleanupTimeout,\n\t\tRetryInterval: mye2eutil.CleanupRetryInterval}); err != nil {\n\t\tt.Fatalf(\"Error Creating cassandracluster: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatefulset got an error: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\",\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatusDone got an error: %v\", err)\n\t}\n\n\tt.Log(\"Download statefulset and store current revision\")\n\tstatefulset, err := f.KubeClient.AppsV1().StatefulSets(namespace).Get(goctx.TODO(),\n\t\t\"cassandra-e2e-dc1-rack1\", metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Could not download statefulset: %v\", err)\n\t}\n\n\tstfsVersion := statefulset.Status.CurrentRevision\n\n\tt.Log(\"Download last version of CassandraCluster\")\n\tif err := f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\",\n\t\tNamespace: namespace}, cc); err != nil {\n\t\tt.Fatalf(\"Could not download last version of CassandraCluster: %v\", err)\n\t}\n\n\tt.Log(\"Trigger rolling restart of 1st DC by updating RollingRestart flag\")\n\n\tcc.Spec.Topology.DC[0].Rack[0].RollingRestart = true\n\n\tif err := f.Client.Update(goctx.TODO(), cc); err != nil {\n\t\tt.Fatalf(\"Could not update CassandraCluster: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatefulset got an error: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\",\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatusDone got an error: %v\", err)\n\t}\n\n\tt.Log(\"Download statefulset and check current revision has been updated\")\n\tstatefulset, err = f.KubeClient.AppsV1().StatefulSets(namespace).Get(goctx.TODO(),\n\t\t\"cassandra-e2e-dc1-rack1\", metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Could not download statefulset: %v\", err)\n\t}\n\n\tassert.NotEqual(t, stfsVersion, statefulset.Status.CurrentRevision)\n\n\tt.Logf(\"Current labels on statefulset : %v\", statefulset.Spec.Template.Labels)\n\n\t_, rollingRestartLabelExists := statefulset.Spec.Template.Labels[\"rolling-restart\"]\n\n\tt.Log(\"Assert that rolling-restart label has been added to statefulset\")\n\tassert.Equal(t, true, rollingRestartLabelExists)\n\n\tt.Log(\"Download last version of CassandraCluster and check RollingRestart flag has been cleaned out\")\n\n\t// Delete Topology in order to get it updated as a whole\n\tcc.Spec.Topology.DC = nil\n\n\tif err := f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\",\n\t\tNamespace: namespace}, cc); err != nil {\n\t\tt.Fatalf(\"Could not get CassandraCluster: %v\", err)\n\t}\n\n\tassert.Equal(t, false, cc.Spec.Topology.DC[0].Rack[0].RollingRestart)\n}", "func (c *Client) doWaitForStatus(eniID string, checkNum, checkInterval int, finalStatus string) error {\n\tfor i := 0; i < checkNum; i++ {\n\t\ttime.Sleep(time.Second * time.Duration(checkInterval))\n\t\tenis, err := c.queryENI(eniID, \"\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, eni := range enis {\n\t\t\tif *eni.NetworkInterfaceId == eniID {\n\t\t\t\tswitch *eni.State {\n\t\t\t\tcase ENI_STATUS_AVAILABLE:\n\t\t\t\t\tswitch finalStatus {\n\t\t\t\t\tcase ENI_STATUS_ATTACHED:\n\t\t\t\t\t\tif eni.Attachment != nil && eni.Attachment.InstanceId != nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is attached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not attached\", eniID)\n\t\t\t\t\tcase ENI_STATUS_DETACHED:\n\t\t\t\t\t\tif eni.Attachment == nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is detached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not detached\", eniID)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tblog.Infof(\"eni %s is %s now\", eniID, *eni.State)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase ENI_STATUS_PENDING, ENI_STATUS_ATTACHING, ENI_STATUS_DETACHING, ENI_STATUS_DELETING:\n\t\t\t\t\tblog.Infof(\"eni %s is %s\", eniID, *eni.State)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tblog.Errorf(\"timeout when wait for eni %s\", eniID)\n\treturn fmt.Errorf(\"timeout when wait for eni %s\", eniID)\n}" ]
[ "0.67166954", "0.6538773", "0.63380307", "0.6060883", "0.59197", "0.58800954", "0.5797496", "0.57853615", "0.5667254", "0.5638806", "0.55470073", "0.5496028", "0.54223436", "0.53780425", "0.5365897", "0.5323093", "0.531257", "0.5297731", "0.5264647", "0.5243112", "0.5234411", "0.52329737", "0.5190569", "0.51737976", "0.5144015", "0.51432973", "0.5127018", "0.51262957", "0.51257515", "0.5122304", "0.51106983", "0.5090236", "0.5076789", "0.5069465", "0.50233173", "0.5023079", "0.501304", "0.50108707", "0.49995363", "0.49907538", "0.49775904", "0.49704581", "0.49345723", "0.49238122", "0.49210507", "0.48825163", "0.48817804", "0.48638576", "0.48597008", "0.48441455", "0.48323083", "0.48282322", "0.48228025", "0.48221526", "0.48203245", "0.48100004", "0.480389", "0.47856343", "0.47785586", "0.47779053", "0.4756858", "0.47558862", "0.47432005", "0.474094", "0.4735022", "0.47203347", "0.47155368", "0.4708284", "0.46983895", "0.46951407", "0.46948498", "0.46944743", "0.46918064", "0.46869665", "0.46860653", "0.46852022", "0.46847296", "0.46806866", "0.46774364", "0.46561292", "0.46544445", "0.46514463", "0.4640565", "0.46380192", "0.46313044", "0.46272886", "0.46262628", "0.46173567", "0.4612599", "0.46043333", "0.45969072", "0.45961484", "0.45803806", "0.45787653", "0.4565336", "0.4562004", "0.4561452", "0.45532167", "0.45500863", "0.45483992" ]
0.83833635
0
DestroyWorkers destroys all MachineDeployment, MachineSet and Machine objects
DestroyWorkers уничтожает все MachineDeployment, MachineSet и Machine объекты
func DestroyWorkers(s *state.State) error { if !s.Cluster.MachineController.Deploy { s.Logger.Info("Skipping deleting workers because machine-controller is disabled in configuration.") return nil } if s.DynamicClient == nil { return fail.NoKubeClient() } ctx := context.Background() // Annotate nodes with kubermatic.io/skip-eviction=true to skip eviction s.Logger.Info("Annotating nodes to skip eviction...") nodes := &corev1.NodeList{} if err := s.DynamicClient.List(ctx, nodes); err != nil { return fail.KubeClient(err, "listing Nodes") } for _, node := range nodes.Items { nodeKey := dynclient.ObjectKey{Name: node.Name} retErr := retry.RetryOnConflict(retry.DefaultRetry, func() error { n := corev1.Node{} if err := s.DynamicClient.Get(ctx, nodeKey, &n); err != nil { return fail.KubeClient(err, "getting %T %s", n, nodeKey) } if n.Annotations == nil { n.Annotations = map[string]string{} } n.Annotations["kubermatic.io/skip-eviction"] = "true" return fail.KubeClient(s.DynamicClient.Update(ctx, &n), "updating %T %s", n, nodeKey) }) if retErr != nil { return retErr } } // Delete all MachineDeployment objects s.Logger.Info("Deleting MachineDeployment objects...") mdList := &clusterv1alpha1.MachineDeploymentList{} if err := s.DynamicClient.List(ctx, mdList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { if !errorsutil.IsNotFound(err) { return fail.KubeClient(err, "listing %T", mdList) } } for i := range mdList.Items { if err := s.DynamicClient.Delete(ctx, &mdList.Items[i]); err != nil { md := mdList.Items[i] return fail.KubeClient(err, "deleting %T %s", md, dynclient.ObjectKeyFromObject(&md)) } } // Delete all MachineSet objects s.Logger.Info("Deleting MachineSet objects...") msList := &clusterv1alpha1.MachineSetList{} if err := s.DynamicClient.List(ctx, msList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { if !errorsutil.IsNotFound(err) { return fail.KubeClient(err, "getting %T", mdList) } } for i := range msList.Items { if err := s.DynamicClient.Delete(ctx, &msList.Items[i]); err != nil { if !errorsutil.IsNotFound(err) { ms := msList.Items[i] return fail.KubeClient(err, "deleting %T %s", ms, dynclient.ObjectKeyFromObject(&ms)) } } } // Delete all Machine objects s.Logger.Info("Deleting Machine objects...") mList := &clusterv1alpha1.MachineList{} if err := s.DynamicClient.List(ctx, mList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { if !errorsutil.IsNotFound(err) { return fail.KubeClient(err, "getting %T", mList) } } for i := range mList.Items { if err := s.DynamicClient.Delete(ctx, &mList.Items[i]); err != nil { if !errorsutil.IsNotFound(err) { ma := mList.Items[i] return fail.KubeClient(err, "deleting %T %s", ma, dynclient.ObjectKeyFromObject(&ma)) } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bc *BaseCluster) Destroy() {\n\tfor _, m := range bc.Machines() {\n\t\tbc.numMachines--\n\t\tm.Destroy()\n\t}\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (w *worker) Terminate() {\n\tfor _, v := range w.allGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allNodes {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedNodes {\n\t\tv.Released()\n\t}\n\tif w.availableGateway != nil {\n\t\tw.availableGateway.Released()\n\t}\n\tif w.availableMaster != nil {\n\t\tw.availableMaster.Released()\n\t}\n\tif w.availableNode != nil {\n\t\tw.availableNode.Released()\n\t}\n}", "func KillWorkloads(clientset kubernetes.Interface) {\n\t// Look for namespace or default to default namespace\n\tnamespace := helpers.GetEnv(\"NAMESPACE\", \"default\")\n\t// Wait Group To handle the waiting for all deletes to complete\n\tvar wg sync.WaitGroup\n\twg.Add(6)\n\t// Delete all Deployments\n\tif helpers.CheckDeleteResourceAllowed(\"deployments\") {\n\t\tgo deleteDeployments(clientset, &namespace, &wg)\n\t}\n\t// Delete all Statefulsets\n\tif helpers.CheckDeleteResourceAllowed(\"statefulsets\") {\n\t\tgo deleteStatefulsets(clientset, &namespace, &wg)\n\t}\n\t// Delete Services\n\tif helpers.CheckDeleteResourceAllowed(\"services\") {\n\t\tgo deleteServices(clientset, &namespace, &wg)\n\t}\n\t// Delete All Secrets\n\tif helpers.CheckDeleteResourceAllowed(\"secrets\") {\n\t\tgo deleteSecrets(clientset, &namespace, &wg)\n\t}\n\t// Delete All Configmaps\n\tif helpers.CheckDeleteResourceAllowed(\"configmaps\") {\n\t\tgo deleteConfigMaps(clientset, &namespace, &wg)\n\t}\n\t// Delete All Daemonsets\n\tif helpers.CheckDeleteResourceAllowed(\"daemonsets\") {\n\t\tgo deleteDaemonSets(clientset, &namespace, &wg)\n\t}\n\t// wait for processes to finish\n\twg.Wait()\n}", "func KillWorkloads(clientset kubernetes.Interface) {\n\t// Look for namespace or default to default namespace\n\tnamespace := helpers.GetEnv(\"NAMESPACE\", \"default\")\n\t// Wait Group To handle the waiting for all deletes to complete\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\t// Delete all Deployments\n\tif helpers.CheckDeleteResourceAllowed(\"deployments\") {\n\t\tgo deleteDeployments(clientset, &namespace, &wg)\n\t}\n\t// Delete all Statefulsets\n\tif helpers.CheckDeleteResourceAllowed(\"statefulsets\") {\n\t\tgo deleteStatefulsets(clientset, &namespace, &wg)\n\t}\n\t// Delete Services\n\tif helpers.CheckDeleteResourceAllowed(\"services\") {\n\t\tgo deleteServices(clientset, &namespace, &wg)\n\t}\n\t// Delete All Secrets\n\tif helpers.CheckDeleteResourceAllowed(\"secrets\") {\n\t\tgo deleteSecrets(clientset, &namespace, &wg)\n\t}\n\t// Delete All Configmaps\n\tif helpers.CheckDeleteResourceAllowed(\"configmaps\") {\n\t\tgo deleteConfigMaps(clientset, &namespace, &wg)\n\t}\n\t// wait for processes to finish\n\twg.Wait()\n}", "func (d Driver) DestroyWorker(project, branch string) error {\n\tdPtr := &d\n\treturn dPtr.remove(context.Background(), d.containerID)\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.Address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.Address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.Address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (s *Server) stopWorkers() {\n\tfor k, w := range s.workers {\n\t\tw.stop()\n\n\t\t// fix nil exception\n\t\tdelete(s.workers, k)\n\t}\n}", "func (s *Server) StopWorkers() {\n\tfor _, v := range s.shardWorkers {\n\t\tclose(v.StopChan)\n\t}\n\n\ts.shardWorkers = nil\n}", "func (m *ManagerImpl) StopWorkers() {\n\tm.processor.StopWorkers()\n}", "func (_m *IProvider) KillAllWorkerProcesses() {\n\t_m.Called()\n}", "func (m *Manager) Delete() {\n\tm.machine.Infof(m.machine.Name(), \"Stopping manager\")\n\tm.cancel()\n\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tfor _, w := range m.watchers {\n\t\tw.Delete()\n\t}\n}", "func (s *Server) CleanupForDestroy() {\n\ts.CtxCancel()\n\ts.Events().Destroy()\n\ts.DestroyAllSinks()\n\ts.Websockets().CancelAll()\n\ts.powerLock.Destroy()\n}", "func (mr *MapReduce) KillWorkers() []int {\n\tl := make([]int, 0)\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false || reply.OK == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl = append(l, reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (manager *syncerManager) garbageCollectSyncer() {\n\tmanager.mu.Lock()\n\tdefer manager.mu.Unlock()\n\tfor key, syncer := range manager.syncerMap {\n\t\tif syncer.IsStopped() && !syncer.IsShuttingDown() {\n\t\t\tdelete(manager.syncerMap, key)\n\t\t}\n\t}\n}", "func (bq *InMemoryBuildQueue) TerminateWorkers(ctx context.Context, request *buildqueuestate.TerminateWorkersRequest) (*emptypb.Empty, error) {\n\tvar completionWakeups []chan struct{}\n\tbq.enter(bq.clock.Now())\n\tfor _, scq := range bq.sizeClassQueues {\n\t\tfor workerKey, w := range scq.workers {\n\t\t\tif workerMatchesPattern(workerKey.getWorkerID(), request.WorkerIdPattern) {\n\t\t\t\tw.terminating = true\n\t\t\t\tif t := w.currentTask; t != nil {\n\t\t\t\t\t// The task will be at the\n\t\t\t\t\t// EXECUTING stage, so it can\n\t\t\t\t\t// only transition to COMPLETED.\n\t\t\t\t\tcompletionWakeups = append(completionWakeups, t.stageChangeWakeup)\n\t\t\t\t} else if w.wakeup != nil {\n\t\t\t\t\t// Wake up the worker, so that\n\t\t\t\t\t// it's dequeued. This prevents\n\t\t\t\t\t// additional tasks to be\n\t\t\t\t\t// assigned to it.\n\t\t\t\t\tw.wakeUp(scq)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tbq.leave()\n\n\tfor _, completionWakeup := range completionWakeups {\n\t\tselect {\n\t\tcase <-completionWakeup:\n\t\t\t// Worker has become idle.\n\t\tcase <-ctx.Done():\n\t\t\t// Client has canceled the request.\n\t\t\treturn nil, util.StatusFromContext(ctx)\n\t\t}\n\t}\n\treturn &emptypb.Empty{}, nil\n}", "func (pm *Manager) cleanReservedPortsWorker() {\n\tfor {\n\t\ttime.Sleep(CleanReservedPortsInterval)\n\t\tpm.mu.Lock()\n\t\tfor name, ctx := range pm.reservedPorts {\n\t\t\tif ctx.Closed && time.Since(ctx.UpdateTime) > MaxPortReservedDuration {\n\t\t\t\tdelete(pm.reservedPorts, name)\n\t\t\t}\n\t\t}\n\t\tpm.mu.Unlock()\n\t}\n}", "func (m *manager) Shutdown() {\n\t// Cancel the context to stop any requests\n\tm.cancel()\n\n\t// Go through and shut everything down\n\tfor _, i := range m.instances {\n\t\ti.cleanup()\n\t}\n}", "func (d *OrderedDaemon) stopWorkers() {\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\t// stop all the workers\n\tif len(d.shutdownOrderWorker) > 0 {\n\t\t// initialize with the priority of the first worker\n\t\tprevPriority := d.workers[d.shutdownOrderWorker[0]].shutdownOrder\n\t\tfor _, name := range d.shutdownOrderWorker {\n\t\t\tworker := d.workers[name]\n\t\t\tif !worker.running.IsSet() {\n\t\t\t\t// the worker's shutdown channel will be automatically garbage collected\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// if the current worker has a lower priority...\n\t\t\tif worker.shutdownOrder < prevPriority {\n\t\t\t\t// wait for every worker in the previous shutdown priority to terminate\n\t\t\t\td.wgPerSameShutdownOrder[prevPriority].Wait()\n\t\t\t\tprevPriority = worker.shutdownOrder\n\t\t\t}\n\t\t\tif d.logger != nil {\n\t\t\t\td.logger.Debugf(\"Stopping Background Worker: %s ...\", name)\n\t\t\t}\n\t\t\tclose(worker.shutdownSignal)\n\t\t}\n\t\t// wait for the last priority to finish\n\t\td.wgPerSameShutdownOrder[prevPriority].Wait()\n\t}\n}", "func finalizer(w *Worker) {\n\tlog.Printf(\"Destroy worker %v\\n\", w.ID)\n}", "func (m *manager) Shutdown() {\n\t// Cancel the context to stop any requests\n\tm.cancel()\n\n\tm.instancesMu.RLock()\n\tdefer m.instancesMu.RUnlock()\n\n\t// Go through and shut everything down\n\tfor _, i := range m.instances {\n\t\ti.cleanup()\n\t}\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 (d *Deployer) Destroy(dep *Deployment, printServerLogs bool) {\n\tfor _, hsDep := range dep.HS {\n\t\tif printServerLogs {\n\t\t\tprintLogs(d.Docker, hsDep.ContainerID, hsDep.ContainerID)\n\t\t}\n\t\terr := d.Docker.ContainerKill(context.Background(), hsDep.ContainerID, \"KILL\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to destroy container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t\terr = d.Docker.ContainerRemove(context.Background(), hsDep.ContainerID, types.ContainerRemoveOptions{\n\t\t\tForce: true,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to remove container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t}\n}", "func (cr *Celery) GenerateWorkers() []*CeleryWorker {\n\tlabels := map[string]string{\n\t\t\"celery-app\": cr.Name,\n\t\t\"type\": \"worker\",\n\t}\n\tdefaultImage := cr.Spec.Image\n\tbrokerAddr := cr.Status.BrokerAddress\n\tworkers := make([]*CeleryWorker, 0)\n\tfor i, workerSpec := range cr.Spec.Workers {\n\t\tif workerSpec.Image == \"\" {\n\t\t\tworkerSpec.Image = defaultImage\n\t\t}\n\t\tworkerSpec.BrokerAddress = brokerAddr\n\t\tworker := &CeleryWorker{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: fmt.Sprintf(\"%s-worker-%d\", cr.GetName(), i+1),\n\t\t\t\tNamespace: cr.GetNamespace(),\n\t\t\t\tLabels: labels,\n\t\t\t},\n\t\t\tSpec: workerSpec,\n\t\t}\n\t\tworkers = append(workers, worker)\n\t}\n\treturn workers\n}", "func (m *Manager) Cleanup() error {\n\tclose(m.stop)\n\tfor _, clean := range m.c.Cleaners {\n\t\tif err := clean(m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn m.env.Stop()\n}", "func (m *Manager) Stop() {\n\tm.serverMutex.Lock()\n\tdefer m.serverMutex.Unlock()\n\n\tm.server = nil\n\n\tm.dropAllNeighbors()\n\n\tm.messageWorkerPool.Stop()\n\tm.messageRequestWorkerPool.Stop()\n}", "func (set HwlocCPUSet) Destroy() {\n\tset.BitMap.Destroy()\n}", "func WaitDestroy(s *state.State) error {\n\ts.Logger.Info(\"Waiting for all machines to get deleted...\")\n\n\treturn wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) {\n\t\tlist := &clusterv1alpha1.MachineList{}\n\t\tif err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\t\treturn false, fail.KubeClient(err, \"getting %T\", list)\n\t\t}\n\t\tif len(list.Items) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func (setup *SimpleTestSetup) TearDown() {\n\tsetup.harnessPool.DisposeAll()\n\tsetup.harnessWalletPool.DisposeAll()\n\t//setup.nodeGoBuilder.Dispose()\n\tsetup.WorkingDir.Dispose()\n}", "func (m *Machine) Delete() {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.manager.Delete()\n\n\tif m.backoffTimer != nil {\n\t\tm.backoffTimer.Stop()\n\t}\n\n\tif m.cancel != nil {\n\t\tm.Infof(\"runner\", \"Stopping\")\n\t\tm.cancel()\n\t}\n\n\tm.startTime = time.Time{}\n}", "func (cc *ClusterController) cleanup(c *cassandrav1alpha1.Cluster) error {\n\n\tfor _, r := range c.Spec.Datacenter.Racks {\n\t\tservices, err := cc.serviceLister.Services(c.Namespace).List(util.RackSelector(r, c))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error listing member services: %s\", err.Error())\n\t\t}\n\t\t// Get rack status. If it doesn't exist, the rack isn't yet created.\n\t\tstsName := util.StatefulSetNameForRack(r, c)\n\t\tsts, err := cc.statefulSetLister.StatefulSets(c.Namespace).Get(stsName)\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting statefulset %s: %s\", stsName, err.Error())\n\t\t}\n\t\tmemberCount := *sts.Spec.Replicas\n\t\tmemberServiceCount := int32(len(services))\n\t\t// If there are more services than members, some services need to be cleaned up\n\t\tif memberServiceCount > memberCount {\n\t\t\tmaxIndex := memberCount - 1\n\t\t\tfor _, svc := range services {\n\t\t\t\tsvcIndex, err := util.IndexFromName(svc.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(\"Unexpected error while parsing index from name %s : %s\", svc.Name, err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif svcIndex > maxIndex {\n\t\t\t\t\terr := cc.cleanupMemberResources(svc.Name, r, c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"error cleaning up member resources: %s\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"%s/%s - Successfully cleaned up cluster.\", c.Namespace, c.Name)\n\treturn nil\n}", "func (this *Healthcheck) UpdateWorkers(targets []core.Target) {\n\n\tresult := []*Worker{}\n\n\t// Keep or add needed workers\n\tfor _, t := range targets {\n\t\tvar keep *Worker\n\t\tfor i := range this.workers {\n\t\t\tc := this.workers[i]\n\t\t\tif t.EqualTo(c.target) {\n\t\t\t\tkeep = c\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif keep == nil {\n\t\t\tkeep = &Worker{\n\t\t\t\ttarget: t,\n\t\t\t\tstop: make(chan bool),\n\t\t\t\tout: this.Out,\n\t\t\t\tcfg: this.cfg,\n\t\t\t\tcheck: this.check,\n\t\t\t\tLastResult: CheckResult{\n\t\t\t\t\tLive: true,\n\t\t\t\t},\n\t\t\t}\n\t\t\tkeep.Start()\n\t\t}\n\t\tresult = append(result, keep)\n\t}\n\n\t// Stop needed workers\n\tfor i := range this.workers {\n\t\tc := this.workers[i]\n\t\tremove := true\n\t\tfor _, t := range targets {\n\t\t\tif c.target.EqualTo(t) {\n\t\t\t\tremove = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif remove {\n\t\t\tc.Stop()\n\t\t}\n\t}\n\n\tthis.workers = result\n\n}", "func cleanup() {\n\tfor _, cmd := range runningApps {\n\t\tcmd.Process.Kill()\n\t}\n}", "func removeWorkers(addrs []dist.Address) error {\n\tdirLock.Lock()\n\tdefer dirLock.Unlock()\n\n\t// cs 101 here we come\n\tres := make([]*dist.Address, 0)\n\tfor i := range directory {\n\t\trm := false\n\t\tfor k := range addrs {\n\t\t\tif directory[i].Equal(addrs[k]) {\n\t\t\t\trm = true\n\t\t\t}\n\t\t}\n\t\tif !rm {\n\t\t\tif directory[i].Valid() {\n\t\t\t\tres = append(res, directory[i])\n\t\t\t}\n\t\t}\n\t}\n\tdirectory = res\n\treturn nil\n}", "func (tr *TestRunner) CleanUp() error {\n\tfor imsi := range tr.imsis {\n\t\terr := deleteSubscribersFromHSS(imsi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, instance := range tr.activePCRFs {\n\t\terr := clearSubscribersFromPCRFPerInstance(instance)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, instance := range tr.activeOCSs {\n\t\terr := clearSubscribersFromOCSPerInstance(instance)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (a Apps) Destroy() error {\n\tfor _, app := range a {\n\t\tcmd, err := app.Destroy(false)\n\t\tif err != nil {\n\t\t\tapp.log.WithFields(logrus.Fields{\n\t\t\t\t\"app\": app.Name,\n\t\t\t\t\"cmd\": cmd,\n\t\t\t\t\"error\": err,\n\t\t\t}).Fatal(\"Failed running destroy\")\n\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (am *Manager) Clean() {\n\tfor name, m := range am.Materials {\n\t\tLogger.Printf(\"Manager: deleting Material '%s'\\n\", name)\n\t\tm.Clean()\n\t\tdelete(am.Materials, name)\n\t}\n\tfor name, m := range am.Meshes {\n\t\tLogger.Printf(\"Manager: deleting Mesh '%s'\\n\", name)\n\t\tm.Clean()\n\t\tdelete(am.Meshes, name)\n\t}\n\tfor set, prog := range am.Programs {\n\t\tLogger.Printf(\"Manager: deleting Program '%v'\\n\", set)\n\t\tgl.DeleteProgram(prog)\n\t\tdelete(am.Programs, set)\n\t}\n\tfor name, shader := range am.Shaders {\n\t\tLogger.Printf(\"Manager: deleting Shader '%s'\\n\", name)\n\t\tgl.DeleteShader(shader)\n\t\tdelete(am.Shaders, name)\n\t}\n\tfor name, tex := range am.Textures {\n\t\tLogger.Printf(\"Manager: deleting Texture '%s'\\n\", name)\n\t\ttex.Clean()\n\t\tdelete(am.Textures, name)\n\t}\n}", "func Cleanup(monitors []models.Application) {\n\tapps := database.Applications()\n\tfor i := range apps {\n\t\tapp := apps[i]\n\n\t\tif contains(app.Name, monitors) == false {\n\t\t\tdatabase.DeleteApplication(app.ID)\n\t\t\tdatabase.DeleteChecks(app.ID)\n\t\t}\n\t}\n}", "func (c *csiManager) Shutdown() {\n\t// Shut down the run loop\n\tc.shutdownCtxCancelFn()\n\n\t// Wait for plugin manager shutdown to complete so that we\n\t// don't try to shutdown instance managers while runLoop is\n\t// doing a resync\n\t<-c.shutdownCh\n\n\t// Shutdown all the instance managers in parallel\n\tvar wg sync.WaitGroup\n\tfor _, pluginMap := range c.instances {\n\t\tfor _, mgr := range pluginMap {\n\t\t\twg.Add(1)\n\t\t\tgo func(mgr *instanceManager) {\n\t\t\t\tmgr.shutdown()\n\t\t\t\twg.Done()\n\t\t\t}(mgr)\n\t\t}\n\t}\n\twg.Wait()\n}", "func DestroyResources(resources []DestroyableResource, dryRun bool, parallel int) int {\n\tnumOfResourcesToDelete := len(resources)\n\tnumOfDeletedResources := 0\n\n\tvar retryableResourceErrors []RetryDestroyError\n\n\tjobQueue := make(chan DestroyableResource, numOfResourcesToDelete)\n\n\tworkerResults := make(chan workerResult, numOfResourcesToDelete)\n\n\tfor workerID := 1; workerID <= parallel; workerID++ {\n\t\tgo worker(workerID, dryRun, jobQueue, workerResults)\n\t}\n\n\tlog.Debug(\"start distributing resources to workers for this run\")\n\n\tfor _, r := range resources {\n\t\tjobQueue <- r\n\t}\n\n\tclose(jobQueue)\n\n\tfor i := 1; i <= numOfResourcesToDelete; i++ {\n\t\tresult := <-workerResults\n\n\t\tif result.resourceHasBeenDeleted {\n\t\t\tnumOfDeletedResources++\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif result.Err != nil {\n\t\t\tretryableResourceErrors = append(retryableResourceErrors, *result.Err)\n\t\t}\n\t}\n\n\tif len(retryableResourceErrors) > 0 && numOfDeletedResources > 0 {\n\t\tvar resourcesToRetry []DestroyableResource\n\t\tfor _, retryErr := range retryableResourceErrors {\n\t\t\tresourcesToRetry = append(resourcesToRetry, retryErr.Resource)\n\t\t}\n\n\t\tnumOfDeletedResources += DestroyResources(resourcesToRetry, dryRun, parallel)\n\t}\n\n\tif len(retryableResourceErrors) > 0 && numOfDeletedResources == 0 {\n\t\tinternal.LogTitle(fmt.Sprintf(\"failed to delete the following resources (retries exceeded): %d\",\n\t\t\tlen(retryableResourceErrors)))\n\n\t\tfor _, err := range retryableResourceErrors {\n\t\t\tlog.WithError(err).WithField(\"id\", err.Resource.ID()).Warn(internal.Pad(err.Resource.Type()))\n\t\t}\n\t}\n\n\treturn numOfDeletedResources\n}", "func (dm *Manager) Manage(\n\tctx context.Context,\n\tworker func(context.Context, *Container) error,\n\tlabels ...string,\n) error {\n\n\ttype workerHandle struct {\n\t\tdone chan struct{}\n\t\tcancel context.CancelFunc\n\t}\n\n\t// Manage workers.\n\tmanagers := make(map[string]workerHandle)\n\n\tdefer func() {\n\t\t// cancel the remaining managers\n\t\tfor _, m := range managers {\n\t\t\tm.cancel()\n\t\t}\n\t\t// wait for the running managers to exit\n\t\tfor _, m := range managers {\n\t\t\t<-m.done\n\t\t}\n\t}()\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tstop := func(container string) {\n\t\tif m, ok := managers[container]; ok {\n\t\t\tm.cancel()\n\t\t\tdelete(managers, container)\n\n\t\t\ttimeout := time.NewTimer(workerShutdownTimeout)\n\t\t\tdefer timeout.Stop()\n\n\t\t\tticker := time.NewTicker(workerShutdownTick)\n\t\t\tdefer ticker.Stop()\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-m.done:\n\t\t\t\t\treturn\n\t\t\t\tcase <-timeout.C:\n\t\t\t\t\tdm.S().Panicw(\"timed out waiting for container worker to stop\", \"container\", container)\n\t\t\t\t\treturn\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\tdm.S().Errorw(\"waiting for container worker to stop\", \"container\", container)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tstart := func(container string) {\n\t\tif _, ok := managers[container]; ok {\n\t\t\treturn\n\t\t}\n\n\t\tcctx, cancel := context.WithCancel(ctx)\n\t\tdone := make(chan struct{})\n\t\tmanagers[container] = workerHandle{\n\t\t\tdone: done,\n\t\t\tcancel: cancel,\n\t\t}\n\t\tgo func() {\n\t\t\tdefer close(done)\n\t\t\thandle := dm.NewHandle(container)\n\t\t\terr := worker(cctx, handle)\n\t\t\tif err != nil {\n\t\t\t\thandle.S().Errorf(\"sidecar worker failed: %s\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Manage existing containers.\n\tnow := time.Now()\n\n\tlistFilter := filters.NewArgs()\n\tfor _, l := range labels {\n\t\tlistFilter.Add(\"label\", l)\n\t}\n\tnodes, err := dm.Client.ContainerList(ctx, types.ContainerListOptions{\n\t\tQuiet: true,\n\t\tLimit: -1,\n\t\tFilters: listFilter,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, n := range nodes {\n\t\tstart(n.ID)\n\t}\n\n\teventFilter := listFilter.Clone()\n\teventFilter.Add(\"type\", \"container\")\n\teventFilter.Add(\"event\", \"start\")\n\teventFilter.Add(\"event\", \"stop\")\n\n\t// Manage new containers.\n\teventCh, errs := dm.Client.Events(ctx, types.EventsOptions{\n\t\tFilters: eventFilter,\n\t\tSince: now.Format(time.RFC3339Nano),\n\t})\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-eventCh:\n\t\t\tswitch event.Status {\n\t\t\tcase \"start\":\n\t\t\t\tstart(event.ID)\n\t\t\tcase \"stop\":\n\t\t\t\tstop(event.ID)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"unexpected event: type=%s, status=%s\", event.Type, event.Status)\n\t\t\t}\n\t\tcase err := <-errs:\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (b *Builder) Shutdown() []error {\n\terrors := []error{}\n\tfor entry := b.localInstances.Back(); entry != nil; entry = entry.Prev() {\n\t\tif info, ok := (entry.Value).(*ProcessorInfo); !ok {\n\t\t\terrors = append(errors, fmt.Errorf(\"unexpected processor info entry in instances map\"))\n\t\t} else if err := info.instance.Shutdown(); err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\treturn errors\n}", "func (e *EventBus) Destroy() {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\t// Stop every pool that exists for a given callback topic.\n\tfor _, cp := range e.pools {\n\t\tcp.pool.Stop()\n\t}\n\n\te.pools = make(map[string]*CallbackPool)\n}", "func (e *Engine) shutdownVservers() {\n\tfor _, v := range e.vservers {\n\t\tv.stop()\n\t}\n\tfor name, v := range e.vservers {\n\t\t<-v.stopped\n\t\tdelete(e.vservers, name)\n\t}\n\te.vserverLock.Lock()\n\te.vserverSnapshots = make(map[string]*seesaw.Vserver)\n\te.vserverLock.Unlock()\n}", "func cleanUpNodes(provisioner provision.Provisioner) {\n\n\tfor _, machine := range provisioner.GetMachinesAll() {\n\t\tnodeName := machine.Name\n\t\texistNode := false\n\t\tfor _, node := range provisioner.Cluster.Nodes {\n\t\t\tif node.Name == nodeName {\n\t\t\t\tnode.Credential = \"\"\n\t\t\t\tnode.PublicIP = \"\"\n\t\t\t\tnode.PrivateIP = \"\"\n\t\t\t\texistNode = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif existNode {\n\t\t\tif err := provisioner.DrainAndDeleteNode(nodeName); err != nil {\n\t\t\t\tlogger.Warnf(\"[%s.%s] %s\", provisioner.Cluster.Namespace, provisioner.Cluster.Name, err.Error())\n\t\t\t}\n\t\t}\n\t}\n\tif err := provisioner.Cluster.PutStore(); err != nil {\n\t\tlogger.Warnf(\"[%s.%s] Failed to update a cluster-entity. (cause='%v')\", provisioner.Cluster.Namespace, provisioner.Cluster.Name, err)\n\t}\n\tlogger.Infof(\"[%s.%s] Garbage data has been cleaned.\", provisioner.Cluster.Namespace, provisioner.Cluster.Name)\n}", "func (jj *Juju) Destroy(user, service string) (*simplejson.Json, error) {\n id := jj.id(user, service)\n report := JSON(fmt.Sprintf(`{\"time\": \"%s\"}`, time.Now()))\n log.Infof(\"destroy juju service: %s\\n\", id)\n\n //Note For now this is massive and basic destruction\n unitArgs := []string{\"destroy-unit\", id + \"/0\", \"--show-log\"}\n serviceArgs := []string{\"destroy-service\", id, \"--show-log\"}\n\n cmd := exec.Command(\"juju\", \"status\", id, \"--format\", \"json\")\n output, err := cmd.CombinedOutput()\n if err != nil { return EmptyJSON(), err }\n status, err := simplejson.NewJson(output)\n machineID, err := status.GetPath(\"services\", id, \"units\", id+\"/0\", \"machine\").String()\n if err != nil { return EmptyJSON(), err }\n machineArgs := []string{\"destroy-machine\", machineID, \"--show-log\"}\n\n client, err := goresque.Dial(redisURL)\n if err != nil { return EmptyJSON(), err }\n log.Infof(\"enqueue destroy-unit\")\n client.Enqueue(workerClass, \"fork\", jj.Path, unitArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-service\")\n client.Enqueue(workerClass, \"fork\", jj.Path, serviceArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-machine\")\n client.Enqueue(workerClass, \"fork\", jj.Path, machineArgs)\n\n report.Set(\"provider\", \"juju\")\n report.Set(\"unit destroyed\", id + \"/0\")\n report.Set(\"service destroyed\", id)\n report.Set(\"machine destroyed\", machineID)\n report.Set(\"unit arguments\", unitArgs)\n report.Set(\"service arguments\", serviceArgs)\n report.Set(\"machine arguments\", machineArgs)\n return report, 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}", "func (s *Reconciler) Delete(ctx context.Context) error {\n\tvmSpec := &virtualmachines.Spec{\n\t\tName: s.scope.Machine.Name,\n\t}\n\n\t// Getting a vm object does not work here so let's assume\n\t// an instance is really being deleted\n\tif s.scope.Machine.Annotations == nil {\n\t\ts.scope.Machine.Annotations = make(map[string]string)\n\t}\n\ts.scope.Machine.Annotations[MachineInstanceStateAnnotationName] = string(machinev1.VMStateDeleting)\n\tvmStateDeleting := machinev1.VMStateDeleting\n\ts.scope.MachineStatus.VMState = &vmStateDeleting\n\n\terr := s.virtualMachinesSvc.Delete(ctx, vmSpec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete machine: %w\", err)\n\t}\n\n\tosDiskSpec := &disks.Spec{\n\t\tName: azure.GenerateOSDiskName(s.scope.Machine.Name),\n\t}\n\terr = s.disksSvc.Delete(ctx, osDiskSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"failed to delete OS disk: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.Vnet == \"\" {\n\t\treturn fmt.Errorf(\"MachineConfig vnet is missing on machine %s\", s.scope.Machine.Name)\n\t}\n\n\tnetworkInterfaceSpec := &networkinterfaces.Spec{\n\t\tName: azure.GenerateNetworkInterfaceName(s.scope.Machine.Name),\n\t\tVnetName: s.scope.MachineConfig.Vnet,\n\t}\n\n\terr = s.networkInterfacesSvc.Delete(ctx, networkInterfaceSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"Unable to delete network interface: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.PublicIP {\n\t\tpublicIPName, err := azure.GenerateMachinePublicIPName(s.scope.MachineConfig.Name, s.scope.Machine.Name)\n\t\tif err != nil {\n\t\t\t// Only when the generated name is longer than allowed by the Azure portal\n\t\t\t// That can happen only when\n\t\t\t// - machine name is changed (can't happen without creating a new CR)\n\t\t\t// - cluster name is changed (could happen but then we will get different name anyway)\n\t\t\t// - machine CR was created with too long public ip name (in which case no instance was created)\n\t\t\tklog.Info(\"Generated public IP name was too long, skipping deletion of the resource\")\n\t\t\treturn nil\n\t\t}\n\n\t\terr = s.publicIPSvc.Delete(ctx, &publicips.Spec{\n\t\t\tName: publicIPName,\n\t\t})\n\t\tif err != nil {\n\t\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\t\tName: s.scope.Machine.Name,\n\t\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\t\tReason: err.Error(),\n\t\t\t})\n\t\t\treturn fmt.Errorf(\"unable to delete Public IP: %w\", err)\n\t\t}\n\t}\n\n\t// Delete the availability set with the given name if no virtual machines are attached to it.\n\tif err := s.availabilitySetsSvc.Delete(ctx, &availabilitysets.Spec{\n\t\tName: s.getAvailibilitySetName(),\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to delete availability set: %w\", err)\n\t}\n\n\treturn nil\n}", "func tearDownVMs(t *testing.T, images []string, vmNum int, isSyncOffload bool) {\n\tfor i := 0; i < vmNum; i++ {\n\t\tlog.Infof(\"Shutting down VM %d, images: %s\", i, images[i%len(images)])\n\t\tvmIDString := strconv.Itoa(i)\n\t\tmessage, err := funcPool.RemoveInstance(vmIDString, images[i%len(images)], isSyncOffload)\n\t\trequire.NoError(t, err, \"Function returned error, \"+message)\n\t}\n}", "func (c *swimCluster) Destroy() {\n\tfor _, node := range c.nodes {\n\t\tnode.Destroy()\n\t}\n\tfor _, ch := range c.channels {\n\t\tch.Close()\n\t}\n}", "func (d *Dispatcher) StopAllWorkers() {\n\tfor _ = range d.workers {\n\t\td.queue <- nil\n\t}\n}", "func (s *JobApiTestSuite) cleanUp() {\n\ttest.DeleteAllRuns(s.runClient, s.resourceNamespace, s.T())\n\ttest.DeleteAllJobs(s.jobClient, s.resourceNamespace, s.T())\n\ttest.DeleteAllPipelines(s.pipelineClient, s.T())\n\ttest.DeleteAllExperiments(s.experimentClient, s.resourceNamespace, s.T())\n}", "func (n *Network) Cleanup() {\n\tdefer func() {\n\t\tlock.Unlock()\n\t\tn.T.Log(\"released test network lock\")\n\t}()\n\n\tn.T.Log(\"cleaning up test network...\")\n\n\tfor _, v := range n.Validators {\n\t\tif v.tmNode != nil && v.tmNode.IsRunning() {\n\t\t\t_ = v.tmNode.Stop()\n\t\t}\n\n\t\tif v.api != nil {\n\t\t\t_ = v.api.Close()\n\t\t}\n\n\t\tif v.grpc != nil {\n\t\t\tv.grpc.Stop()\n\t\t\tif v.grpcWeb != nil {\n\t\t\t\t_ = v.grpcWeb.Close()\n\t\t\t}\n\t\t}\n\t}\n\n\tif n.Config.CleanupDir {\n\t\t_ = os.RemoveAll(n.BaseDir)\n\t}\n\n\tn.T.Log(\"finished cleaning up test network\")\n}", "func (s *Server) RunWorkers() {\n\n\ts.shardWorkers = make([]*shardWorker, len(s.readyShards))\n\tfor i := 0; i < len(s.shardWorkers); i++ {\n\t\ts.shardWorkers[i] = &shardWorker{\n\t\t\tGCCHan: make(chan *GuildCreateEvt),\n\t\t\tStopChan: make(chan bool),\n\t\t\tserver: s,\n\t\t}\n\t\tgo s.shardWorkers[i].chunkQueueHandler()\n\t}\n\n\tgo s.eventQueuePuller()\n}", "func (lw *Manager) CleanUp(w *Waiter) {\n\tlw.mu.Lock()\n\tq := lw.waitingQueues[w.startTS]\n\tlw.mu.Unlock()\n\tif q != nil {\n\t\tq.removeWaiter(w)\n\t}\n}", "func (wq *WorkQueue) Clean() (workunits []*Workunit) {\n\tworkunt_list, err := wq.all.GetWorkunits()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, work := range workunt_list {\n\t\tid := work.Workunit_Unique_Identifier\n\t\tif work == nil || work.Info == nil {\n\t\t\tworkunits = append(workunits, work)\n\t\t\twq.Queue.Delete(id)\n\t\t\twq.Checkout.Delete(id)\n\t\t\twq.Suspend.Delete(id)\n\t\t\twq.all.Delete(id)\n\t\t\tid_str, _ := id.String()\n\t\t\tlogger.Error(\"error: in WorkQueue workunit %s is nil, deleted from queue\", id_str)\n\t\t}\n\t}\n\treturn\n}", "func (am *AssetManager) Clean() {\n\tfor name, model := range am.Models {\n\t\tmodel.Delete()\n\t\tdelete(am.Models, name)\n\t}\n\tfor name, tex := range am.Textures {\n\t\ttex.Delete()\n\t\tdelete(am.Textures, name)\n\t}\n\tfor name, prog := range am.Programs {\n\t\tprog.Delete()\n\t\tdelete(am.Programs, name)\n\t}\n}", "func (f *TestFramework) DestroyMachineSet() error {\n\tlog.Print(\"Destroying MachineSets\")\n\tif f.machineSet == nil {\n\t\tlog.Print(\"unable to find MachineSet to be deleted, was skip VM setup option selected ?\")\n\t\tlog.Print(\"MachineSets/Machines needs to be deleted manually \\nNot deleting MachineSets...\")\n\t\treturn nil\n\t}\n\terr := f.machineClient.MachineSets(\"openshift-machine-api\").Delete(context.TODO(), f.machineSet.Name, metav1.DeleteOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete MachineSet %v\", err)\n\t}\n\tlog.Print(\"MachineSets Destroyed\")\n\treturn nil\n}", "func (p *PodmanTestIntegration) Cleanup() {\n\tp.StopVarlink()\n\t// TODO\n\t// Stop all containers\n\t// Rm all containers\n\n\tif err := os.RemoveAll(p.TempDir); err != nil {\n\t\tfmt.Printf(\"%q\\n\", err)\n\t}\n\n\t// Clean up the registries configuration file ENV variable set in Create\n\tresetRegistriesConfigEnv()\n}", "func cleanup() {\n\tserver.Applications = []*types.ApplicationMetadata{}\n}", "func (m *ParallelMaster) Shutdown() {\n\tatomic.StoreInt32(&m.active, 0)\n\n\tfor i := uint(0); i < uint(m.totalWorkers); i++ {\n\t\tworker := <-m.freeWorkers\n\t\tcallWorker(worker, \"Shutdown\", new(interface{}), new(interface{}))\n\t}\n\n\tm.rpcListener.Close()\n\tclose(m.freeWorkers)\n}", "func (r *RealRunner) Clean() error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tfor pid, p := range r.processes {\n\t\tif err := p.Kill(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(r.processes, pid)\n\t}\n\treturn nil\n}", "func (dm *DaemonManager) Run(workers int, stopCh <-chan struct{}) {\n\tgo dm.dcController.Run(stopCh)\n\tgo dm.podController.Run(stopCh)\n\tgo dm.nodeController.Run(stopCh)\n\tfor i := 0; i < workers; i++ {\n\t\tgo util.Until(dm.worker, time.Second, stopCh)\n\t}\n\t<-stopCh\n\tglog.Infof(\"Shutting down Daemon Controller Manager\")\n\tdm.queue.ShutDown()\n}", "func Shutdown() {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tfor _, v := range instances {\n\t\tv.Shutdown()\n\t}\n}", "func cleanUp() {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tsignal.Notify(c, syscall.SIGTERM)\n\tsignal.Notify(c, syscall.SIGKILL)\n\tgo func() {\n\t\t<-c\n\t\t_ = pool.Close()\n\t\tos.Exit(0)\n\t}()\n}", "func (r *ContainerizedWorkloadReconciler) cleanupResources(ctx context.Context,\n\tworkload *oamv1alpha2.ContainerizedWorkload, deployUID, serviceUID *types.UID) error {\n\tlog := r.Log.WithValues(\"gc deployment\", workload.Name)\n\tvar deploy appsv1.Deployment\n\tvar service corev1.Service\n\tfor _, res := range workload.Status.Resources {\n\t\tuid := res.UID\n\t\tif res.Kind == KindDeployment {\n\t\t\tif uid != *deployUID {\n\t\t\t\tlog.Info(\"Found an orphaned deployment\", \"deployment UID\", *deployUID, \"orphaned UID\", uid)\n\t\t\t\tdn := client.ObjectKey{Name: res.Name, Namespace: workload.Namespace}\n\t\t\t\tif err := r.Get(ctx, dn, &deploy); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := r.Delete(ctx, &deploy); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Removed an orphaned deployment\", \"deployment UID\", *deployUID, \"orphaned UID\", uid)\n\t\t\t}\n\t\t} else if res.Kind == KindService {\n\t\t\tif uid != *serviceUID {\n\t\t\t\tlog.Info(\"Found an orphaned service\", \"orphaned UID\", uid)\n\t\t\t\tsn := client.ObjectKey{Name: res.Name, Namespace: workload.Namespace}\n\t\t\t\tif err := r.Get(ctx, sn, &service); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := r.Delete(ctx, &service); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Removed an orphaned service\", \"orphaned UID\", uid)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func ValidateWorkers(workers []core.Worker, infra *api.InfrastructureConfig, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, worker := range workers {\n\t\tpath := fldPath.Index(i)\n\n\t\tif worker.Volume == nil {\n\t\t\tallErrs = append(allErrs, field.Required(path.Child(\"volume\"), \"must not be nil\"))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, validateVolume(worker.Volume, path.Child(\"volume\"))...)\n\t\t}\n\n\t\tif length := len(worker.DataVolumes); length > maxDataVolumeCount {\n\t\t\tallErrs = append(allErrs, field.TooMany(path.Child(\"dataVolumes\"), length, maxDataVolumeCount))\n\t\t}\n\t\tfor j, volume := range worker.DataVolumes {\n\t\t\tdataVolPath := path.Child(\"dataVolumes\").Index(j)\n\t\t\tallErrs = append(allErrs, validateDataVolume(&volume, dataVolPath)...)\n\t\t}\n\n\t\t// Zones validation\n\t\tif infra.Zoned && len(worker.Zones) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(path.Child(\"zones\"), \"at least one zone must be configured for zoned clusters\"))\n\t\t\tcontinue\n\t\t}\n\n\t\tif !infra.Zoned && len(worker.Zones) > 0 {\n\t\t\tallErrs = append(allErrs, field.Required(path.Child(\"zones\"), \"zones must not be specified for non zoned clusters\"))\n\t\t\tcontinue\n\t\t}\n\n\t\tzones := sets.New[string]()\n\t\tfor j, zone := range worker.Zones {\n\t\t\tif zones.Has(zone) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"zones\").Index(j), zone, \"must only be specified once per worker group\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tzones.Insert(zone)\n\t\t}\n\n\t\tif !helper.IsUsingSingleSubnetLayout(infra) {\n\t\t\tinfraZones := sets.Set[string]{}\n\t\t\tfor _, zone := range infra.Networks.Zones {\n\t\t\t\tinfraZones.Insert(helper.InfrastructureZoneToString(zone.Name))\n\t\t\t}\n\n\t\t\tfor zoneIndex, workerZone := range worker.Zones {\n\t\t\t\tif !infraZones.Has(workerZone) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"zones\").Index(zoneIndex), workerZone, \"zone configuration must be specified in \\\"infrastructureConfig.networks.zones\\\"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}", "func (c *controller) Run(workers int, stopCh <-chan struct{}) {\n\tdefer runtimeutil.HandleCrash()\n\n\tglog.Info(\"Starting service-catalog controller\")\n\n\tvar waitGroup sync.WaitGroup\n\n\tfor i := 0; i < workers; i++ {\n\t\tcreateWorker(c.clusterServiceBrokerQueue, \"ClusterServiceBroker\", maxRetries, true, c.reconcileClusterServiceBrokerKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.clusterServiceClassQueue, \"ClusterServiceClass\", maxRetries, true, c.reconcileClusterServiceClassKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.clusterServicePlanQueue, \"ClusterServicePlan\", maxRetries, true, c.reconcileClusterServicePlanKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.instanceQueue, \"ServiceInstance\", maxRetries, true, c.reconcileServiceInstanceKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.bindingQueue, \"ServiceBinding\", maxRetries, true, c.reconcileServiceBindingKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.instancePollingQueue, \"InstancePoller\", maxRetries, false, c.requeueServiceInstanceForPoll, stopCh, &waitGroup)\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(scfeatures.NamespacedServiceBroker) {\n\t\t\tcreateWorker(c.serviceBrokerQueue, \"ServiceBroker\", maxRetries, true, c.reconcileServiceBrokerKey, stopCh, &waitGroup)\n\t\t}\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(scfeatures.AsyncBindingOperations) {\n\t\t\tcreateWorker(c.bindingPollingQueue, \"BindingPoller\", maxRetries, false, c.requeueServiceBindingForPoll, stopCh, &waitGroup)\n\t\t}\n\t}\n\n\t// this creates a worker specifically for monitoring\n\t// configmaps, as we don't have the watching polling queue\n\t// infrastructure set up for one configmap. Instead this is a\n\t// simple polling based worker\n\tc.createConfigMapMonitorWorker(stopCh, &waitGroup)\n\n\t<-stopCh\n\tglog.Info(\"Shutting down service-catalog controller\")\n\n\tc.clusterServiceBrokerQueue.ShutDown()\n\tc.clusterServiceClassQueue.ShutDown()\n\tc.clusterServicePlanQueue.ShutDown()\n\tc.instanceQueue.ShutDown()\n\tc.bindingQueue.ShutDown()\n\tc.instancePollingQueue.ShutDown()\n\tc.bindingPollingQueue.ShutDown()\n\n\tif utilfeature.DefaultFeatureGate.Enabled(scfeatures.NamespacedServiceBroker) {\n\t\tc.serviceBrokerQueue.ShutDown()\n\t}\n\n\twaitGroup.Wait()\n\tglog.Info(\"Shutdown service-catalog controller\")\n}", "func (w *watcher) cleanupWorker() {\n\tfor {\n\t\t// Wait a full period\n\t\ttime.Sleep(w.cleanupTimeout)\n\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.stopped.Done()\n\t\t\treturn\n\t\tdefault:\n\t\t\t// Check entries for timeout\n\t\t\tvar toDelete []string\n\t\t\ttimeout := time.Now().Add(-w.cleanupTimeout)\n\t\t\tw.RLock()\n\t\t\tfor key, lastSeen := range w.deleted {\n\t\t\t\tif lastSeen.Before(timeout) {\n\t\t\t\t\tlogp.Debug(\"docker\", \"Removing container %s after cool down timeout\", key)\n\t\t\t\t\ttoDelete = append(toDelete, key)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.RUnlock()\n\n\t\t\t// Delete timed out entries:\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tcontainer := w.Container(key)\n\t\t\t\tif container != nil {\n\t\t\t\t\tw.bus.Publish(bus.Event{\n\t\t\t\t\t\t\"delete\": true,\n\t\t\t\t\t\t\"container\": container,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tw.Lock()\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tdelete(w.deleted, key)\n\t\t\t\tdelete(w.containers, key)\n\t\t\t\tif w.shortID {\n\t\t\t\t\tdelete(w.containers, key[:shortIDLen])\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.Unlock()\n\t\t}\n\t}\n}", "func (wp *WorkerPool) SetWorkers(wrks []Worker){\n\twp.workerList = wrks\n}", "func (manager *syncerManager) ShutDown() {\n\tmanager.mu.Lock()\n\tdefer manager.mu.Unlock()\n\tfor _, s := range manager.syncerMap {\n\t\ts.Stop()\n\t}\n}", "func (db *mongoDatabase) Destroy(opts *DestroyOptions) error {\n\tif err := opts.Valid(); err != nil {\n\t\treturn err\n\t}\n\n\terr := new(multierror.Error)\n\n\tfor _, id := range opts.Stack.Machines {\n\t\tif e := modelhelper.DeleteMachine(id); e != nil {\n\t\t\terr = multierror.Append(err, e)\n\t\t}\n\t}\n\n\tif e := modelhelper.DeleteComputeStack(opts.Stack.Id.Hex()); e != nil {\n\t\terr = multierror.Append(err, e)\n\t}\n\n\treturn err.ErrorOrNil()\n}", "func (p *Provider) Reset(vms vm.List) error {\n\t// Map from project to map of zone to list of machines in that project/zone.\n\tprojectZoneMap := make(map[string]map[string][]string)\n\tfor _, v := range vms {\n\t\tif v.Provider != ProviderName {\n\t\t\treturn errors.Errorf(\"%s received VM instance from %s\", ProviderName, v.Provider)\n\t\t}\n\t\tif projectZoneMap[v.Project] == nil {\n\t\t\tprojectZoneMap[v.Project] = make(map[string][]string)\n\t\t}\n\n\t\tprojectZoneMap[v.Project][v.Zone] = append(projectZoneMap[v.Project][v.Zone], v.Name)\n\t}\n\n\tvar g errgroup.Group\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)\n\tdefer cancel()\n\tfor project, zoneMap := range projectZoneMap {\n\t\tfor zone, names := range zoneMap {\n\t\t\targs := []string{\n\t\t\t\t\"compute\", \"instances\", \"reset\",\n\t\t\t}\n\n\t\t\targs = append(args, \"--project\", project)\n\t\t\targs = append(args, \"--zone\", zone)\n\t\t\targs = append(args, names...)\n\n\t\t\tg.Go(func() error {\n\t\t\t\tcmd := exec.CommandContext(ctx, \"gcloud\", args...)\n\n\t\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Command: gcloud %s\\nOutput: %s\", args, output)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\n\treturn g.Wait()\n}", "func GenerateMachineDeploymentsManifest(s *state.State) (string, error) {\n\tif len(s.Cluster.DynamicWorkers) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\tobjs := []runtime.Object{}\n\tfor _, workerset := range s.Cluster.DynamicWorkers {\n\t\tmachinedeployment, err := createMachineDeployment(s.Cluster, workerset)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tmachinedeployment.TypeMeta = metav1.TypeMeta{\n\t\t\tAPIVersion: clusterv1alpha1.SchemeGroupVersion.String(),\n\t\t\tKind: \"MachineDeployment\",\n\t\t}\n\n\t\tobjs = append(objs, machinedeployment)\n\t}\n\n\treturn templates.KubernetesToYAML(objs)\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 (b *Builder) Cleanup() {\n\tb.mu.Lock()\n\tfor r := range b.running {\n\t\tr.Cleanup()\n\t}\n\tb.mu.Unlock()\n\tif !b.Preserve {\n\t\tdefer os.RemoveAll(b.Dir)\n\t}\n}", "func (p *Plugin) Cleanup(kubeclient kubernetes.Interface) {\n\tp.cleanedUp = true\n\tgracePeriod := int64(1)\n\tdeletionPolicy := metav1.DeletePropagationBackground\n\n\tlistOptions := p.listOptions()\n\tdeleteOptions := metav1.DeleteOptions{\n\t\tGracePeriodSeconds: &gracePeriod,\n\t\tPropagationPolicy: &deletionPolicy,\n\t}\n\n\t// Delete the DaemonSet created by this plugin\n\terr := kubeclient.ExtensionsV1beta1().DaemonSets(p.Namespace).DeleteCollection(\n\t\t&deleteOptions,\n\t\tlistOptions,\n\t)\n\tif err != nil {\n\t\terrlog.LogError(errors.Wrapf(err, \"could not delete DaemonSet %v for daemonset plugin %v\", p.daemonSetName(), p.GetName()))\n\t}\n\n\t// Delete the ConfigMap created by this plugin\n\terr = kubeclient.CoreV1().ConfigMaps(p.Namespace).DeleteCollection(\n\t\t&deleteOptions,\n\t\tlistOptions,\n\t)\n\tif err != nil {\n\t\terrlog.LogError(errors.Wrapf(err, \"could not delete ConfigMap %v for daemonset plugin %v\", p.configMapName(), p.GetName()))\n\t}\n}", "func (manager *Manager) Shutdown() {\n\tmanager.Proxy.Shutdown()\n\n\tfor _, connectionManager := range manager.ConnectionManagers {\n\t\tconnectionManager.Shutdown()\n\t}\n}", "func (i *Instance) Cleanup() {\n\tif err := i.client.DeleteInstance(i.Project, i.Zone, i.Name); err != nil {\n\t\tfmt.Printf(\"Error deleting instance: %v\\n\", err)\n\t}\n}", "func (p *Pool) Stop() {\n\tfor _, worker := range p.Workers {\n\t\tworker.Stop()\n\t}\n\tp.RunningBackground <-true\n}", "func (eng *Engine) Destroy() {\n\tfor _, rt := range eng.applied {\n\t\trt.destroy()\n\t}\n}", "func (l *LoadBalancerEmulator) Cleanup() ([]string, error) {\n\treturn l.applyOnLBServices(l.cleanupService)\n}", "func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.workqueue.ShutDown()\n\n\t// Start the informer factories to begin populating the informer caches\n\tklog.Info(\"Starting Load Balancer controller\")\n\n\t// Wait for the caches to be synced before starting workers\n\tklog.Info(\"Waiting for informer caches to sync\")\n\tif ok := cache.WaitForCacheSync(stopCh, c.servicesSynced); !ok {\n\t\treturn fmt.Errorf(\"failed to wait for caches to sync\")\n\t}\n\tklog.Info(\"Informer caches are synchronized, enqueueing job to remove the cleanup barrier\")\n\n\tklog.Info(\"Starting workers\")\n\tgo wait.Until(c.worker.Run, time.Second, stopCh)\n\n\t// 907s is chosen because:\n\t//\n\t// - it is prime, which randomizes the cleanups relative ordering against\n\t// other jobs.\n\t// - it is greater than three times the sync interval of the informer\n\t//\n\t// This way, we can be reasonably confident that we have heard about all\n\t// currently active services before we attempt to clean any seemingly\n\t// unused ports.\n\t//\n\t// In the past, there have been problems with ports being deleted even\n\t// though they were still in use by services. This had been caused by the\n\t// cleanup job running too early, despite the fact that we block on the\n\t// informer sync above; apparently, the informer sync wait sometimes\n\t// returns too early or we are missing events for some other, unclear\n\t// reason.\n\t//\n\t// In order to mitigate this problem, we now ensure that the first cleanup\n\t// happens only after three sync intervals (900 seconds).\n\tgo wait.Until(c.periodicCleanup, 907*time.Second, stopCh)\n\n\tklog.Info(\"Started workers\")\n\t<-stopCh\n\tklog.Info(\"Shutting down workers\")\n\n\treturn nil\n}", "func (c *ProjectFinalizerController) Run(stopCh <-chan struct{}, workers int) {\n\tdefer runtime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\t// Wait for the stores to fill\n\tif !cache.WaitForCacheSync(stopCh, c.controller.HasSynced) {\n\t\treturn\n\t}\n\n\tglog.V(5).Infof(\"Starting workers\")\n\tfor i := 0; i < workers; i++ {\n\t\tgo c.worker()\n\t}\n\t<-stopCh\n\tglog.V(1).Infof(\"Shutting down\")\n}", "func performCleanup(ctx context.Context, clientMap map[string]kubernetes.Interface, flags flags) error {\n\tfor _, cluster := range flags.memberClusters {\n\t\tc := clientMap[cluster]\n\t\tif err := cleanupClusterResources(ctx, c, cluster, flags.memberClusterNamespace); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed cleaning up cluster %s namespace %s: %w\", cluster, flags.memberClusterNamespace, err)\n\t\t}\n\t}\n\tc := clientMap[flags.centralCluster]\n\tif err := cleanupClusterResources(ctx, c, flags.centralCluster, flags.centralClusterNamespace); err != nil {\n\t\treturn xerrors.Errorf(\"failed cleaning up cluster %s namespace %s: %w\", flags.centralCluster, flags.centralClusterNamespace, err)\n\t}\n\treturn nil\n}", "func (m *member) Terminate(t *testing.T) {\n\tm.s.Stop()\n\tfor _, hs := range m.hss {\n\t\ths.CloseClientConnections()\n\t\ths.Close()\n\t}\n\tif err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func cleanUpTaskQueue() {\n\tlog.Println(\"Signalling Task Workers for CleanUp\")\n\n\tfor i := uint8(0); i < NumberOfTaskWorkers; i++ {\n\t\tzeroMQWorkerChannelIn <- true\n\t}\n\n\tlog.Println(\"Signalling Finished Waiting for response!\")\n\tfor i := uint8(0); i < NumberOfTaskWorkers; i++ {\n\t\t<-zeroMQWorkerChannelOut\n\t}\n\n\tlog.Println(\"Task Workers Cleanup Complete!\")\n\n\tlog.Println(\"Clearing Proxy\")\n\n\t// Set a Control\n\tzeroMQProxyControl, err := zeromq.MainZeroMQ.NewSocket(zmq4.Type(zmq4.REQ))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Clearing Proxy! Err: %v\\n\", err)\n\t}\n\n\terr = zeroMQProxyControl.Bind(zeromq.ZeromqMask + ProxyControlPort)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Clearing Proxy! Err: %v\\n\", err)\n\t}\n\n\tzeroMQProxyControl.Send(\"TERMINATE\", zmq4.Flag(0))\n\tzeroMQProxyControl.Recv(zmq4.Flag(0))\n\n\tlog.Println(\"Clearing Proxy Complete!\")\n}" ]
[ "0.6304216", "0.626198", "0.626198", "0.626198", "0.60066", "0.5894493", "0.5889124", "0.58310187", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.5772434", "0.56566495", "0.56443316", "0.5613604", "0.5529262", "0.5445959", "0.54036295", "0.53909564", "0.53738517", "0.53616863", "0.5354619", "0.530596", "0.52813846", "0.51862425", "0.5166823", "0.5157727", "0.5147629", "0.5139252", "0.5136502", "0.51335716", "0.5082757", "0.5063258", "0.50457597", "0.50453264", "0.5037611", "0.5027076", "0.5025537", "0.50061435", "0.49835023", "0.4976687", "0.4962522", "0.49582097", "0.49516472", "0.49496472", "0.4942959", "0.49409297", "0.4932638", "0.4901299", "0.49001807", "0.48985824", "0.48970324", "0.48966348", "0.48948556", "0.48942018", "0.48915267", "0.4874682", "0.48714358", "0.48692518", "0.48678476", "0.48677215", "0.4863963", "0.484804", "0.4821592", "0.48151612", "0.48122168", "0.48094028", "0.48090768", "0.4802615", "0.47976238", "0.47970122", "0.47920313", "0.47808284", "0.47780028", "0.477793", "0.47695932", "0.4743372", "0.47403035", "0.47380072", "0.47262585", "0.4714136", "0.47123194", "0.47097313", "0.4709158", "0.4702718", "0.47014618", "0.46996728", "0.4698815", "0.46882614", "0.46850872", "0.46799558", "0.46735936" ]
0.7957886
0
WaitDestroy waits for all Machines to be deleted
WaitDestroy ожидает удаления всех Machine
func WaitDestroy(s *state.State) error { s.Logger.Info("Waiting for all machines to get deleted...") return wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) { list := &clusterv1alpha1.MachineList{} if err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { return false, fail.KubeClient(err, "getting %T", list) } if len(list.Items) != 0 { return false, nil } return true, nil }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bc *BaseCluster) Destroy() {\n\tfor _, m := range bc.Machines() {\n\t\tbc.numMachines--\n\t\tm.Destroy()\n\t}\n}", "func WaitForDeletion(ctx context.Context, mcpKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {\n\t\tmcp := &machineconfigv1.MachineConfigPool{}\n\t\tif err := testclient.Client.Get(ctx, mcpKey, mcp); apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func waitAndCleanup() {\n\ttime.Sleep(1 * time.Second)\n\n\t// Disconnect from switches.\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tvrtrAgents[i].Delete()\n\t\tvxlanAgents[i].Delete()\n\t\tvlanAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tvlrtrAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\thostBridges[i].Delete()\n\t}\n\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vxlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[NUM_AGENT+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(2*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tbrName := \"vlrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(3*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\tbrName := \"hostBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[HB_AGENT_INDEX].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n}", "func WaitForCleanup() error {\n\tctx := context.Background()\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar (\n\t\tinterval = time.NewTicker(1 * time.Second)\n\t\ttimeout = time.NewTimer(1 * time.Minute)\n\t)\n\n\tfor range interval.C {\n\t\tselect {\n\t\tcase <-timeout.C:\n\t\t\treturn errors.New(\"timed out waiting for all easycontainers containers to get removed\")\n\t\tdefault:\n\t\t\t// only grab the containers created by easycontainers\n\t\t\targs := filters.NewArgs()\n\t\t\targs.Add(\"name\", \"/\"+prefix)\n\n\t\t\tcontainers, err := cli.ContainerList(ctx, types.ContainerListOptions{\n\t\t\t\tFilters: args,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(containers) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *Machine) WaitForPVCsDelete(namespace string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.PVCsDeleted(namespace)\n\t})\n}", "func DestroyWorkers(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\ts.Logger.Info(\"Skipping deleting workers because machine-controller is disabled in configuration.\")\n\n\t\treturn nil\n\t}\n\tif s.DynamicClient == nil {\n\t\treturn fail.NoKubeClient()\n\t}\n\n\tctx := context.Background()\n\n\t// Annotate nodes with kubermatic.io/skip-eviction=true to skip eviction\n\ts.Logger.Info(\"Annotating nodes to skip eviction...\")\n\tnodes := &corev1.NodeList{}\n\tif err := s.DynamicClient.List(ctx, nodes); err != nil {\n\t\treturn fail.KubeClient(err, \"listing Nodes\")\n\t}\n\n\tfor _, node := range nodes.Items {\n\t\tnodeKey := dynclient.ObjectKey{Name: node.Name}\n\n\t\tretErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t\tn := corev1.Node{}\n\t\t\tif err := s.DynamicClient.Get(ctx, nodeKey, &n); err != nil {\n\t\t\t\treturn fail.KubeClient(err, \"getting %T %s\", n, nodeKey)\n\t\t\t}\n\n\t\t\tif n.Annotations == nil {\n\t\t\t\tn.Annotations = map[string]string{}\n\t\t\t}\n\t\t\tn.Annotations[\"kubermatic.io/skip-eviction\"] = \"true\"\n\n\t\t\treturn fail.KubeClient(s.DynamicClient.Update(ctx, &n), \"updating %T %s\", n, nodeKey)\n\t\t})\n\n\t\tif retErr != nil {\n\t\t\treturn retErr\n\t\t}\n\t}\n\n\t// Delete all MachineDeployment objects\n\ts.Logger.Info(\"Deleting MachineDeployment objects...\")\n\tmdList := &clusterv1alpha1.MachineDeploymentList{}\n\tif err := s.DynamicClient.List(ctx, mdList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\tif !errorsutil.IsNotFound(err) {\n\t\t\treturn fail.KubeClient(err, \"listing %T\", mdList)\n\t\t}\n\t}\n\n\tfor i := range mdList.Items {\n\t\tif err := s.DynamicClient.Delete(ctx, &mdList.Items[i]); err != nil {\n\t\t\tmd := mdList.Items[i]\n\n\t\t\treturn fail.KubeClient(err, \"deleting %T %s\", md, dynclient.ObjectKeyFromObject(&md))\n\t\t}\n\t}\n\n\t// Delete all MachineSet objects\n\ts.Logger.Info(\"Deleting MachineSet objects...\")\n\tmsList := &clusterv1alpha1.MachineSetList{}\n\tif err := s.DynamicClient.List(ctx, msList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\tif !errorsutil.IsNotFound(err) {\n\t\t\treturn fail.KubeClient(err, \"getting %T\", mdList)\n\t\t}\n\t}\n\n\tfor i := range msList.Items {\n\t\tif err := s.DynamicClient.Delete(ctx, &msList.Items[i]); err != nil {\n\t\t\tif !errorsutil.IsNotFound(err) {\n\t\t\t\tms := msList.Items[i]\n\n\t\t\t\treturn fail.KubeClient(err, \"deleting %T %s\", ms, dynclient.ObjectKeyFromObject(&ms))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Delete all Machine objects\n\ts.Logger.Info(\"Deleting Machine objects...\")\n\tmList := &clusterv1alpha1.MachineList{}\n\tif err := s.DynamicClient.List(ctx, mList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\tif !errorsutil.IsNotFound(err) {\n\t\t\treturn fail.KubeClient(err, \"getting %T\", mList)\n\t\t}\n\t}\n\n\tfor i := range mList.Items {\n\t\tif err := s.DynamicClient.Delete(ctx, &mList.Items[i]); err != nil {\n\t\t\tif !errorsutil.IsNotFound(err) {\n\t\t\t\tma := mList.Items[i]\n\n\t\t\t\treturn fail.KubeClient(err, \"deleting %T %s\", ma, dynclient.ObjectKeyFromObject(&ma))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func WaitForZKClusterToTerminate(t *testing.T, k8client client.Client, z *zkapi.ZookeeperCluster) error {\n\tlog.Printf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(z.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func WaitForClusterToTerminate(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) error {\n\tt.Logf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()}).String(),\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.CoreV1().Pods(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList, err := f.KubeClient.CoreV1().PersistentVolumeClaims(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Logf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func (v VirtualMachine) Delete() error {\n\ttctx, tcancel := context.WithTimeout(context.Background(), time.Minute*5)\n\tdefer tcancel()\n\n\tpowerState, err := v.vm.PowerState(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Getting power state: %s\", powerState)\n\t}\n\n\tif powerState == \"poweredOn\" || powerState == \"suspended\" {\n\t\tpowerOff, err := v.vm.PowerOff(context.Background())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Shutting down virtual machine: %s\", err)\n\t\t}\n\n\t\terr = powerOff.Wait(tctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Waiting for machine to shut down: %s\", err)\n\t\t}\n\t}\n\n\tdestroy, err := v.vm.Destroy(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Destroying virtual machine: %s\", err)\n\t}\n\n\terr = destroy.Wait(tctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Waiting for machine to destroy: %s\", err)\n\t}\n\n\treturn nil\n}", "func assertDeletedWaitForCleanup(t *testing.T, cl client.Client, thing client.Object) {\n\tt.Helper()\n\tthingName := types.NamespacedName{\n\t\tName: thing.GetName(),\n\t\tNamespace: thing.GetNamespace(),\n\t}\n\tassertDeleted(t, cl, thing)\n\tif err := wait.PollImmediate(5*time.Second, 2*time.Minute, func() (bool, error) {\n\t\tif err := cl.Get(context.TODO(), thingName, thing); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\treturn false, nil\n\t}); err != nil {\n\t\tt.Fatalf(\"Timed out waiting for %s to be cleaned up: %v\", thing.GetName(), err)\n\t}\n}", "func (c *swimCluster) Destroy() {\n\tfor _, node := range c.nodes {\n\t\tnode.Destroy()\n\t}\n\tfor _, ch := range c.channels {\n\t\tch.Close()\n\t}\n}", "func (t *TestSpec) Destroy(delay time.Duration, base string) error {\n\tmanifestToDestroy := []string{\n\t\tt.GetManifestsPath(base),\n\t\tfmt.Sprintf(\"%s/%s\", base, t.NetworkPolicyName()),\n\t\tt.Destination.GetManifestPath(t, base),\n\t}\n\n\tdone := time.After(delay)\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tfor _, manifest := range manifestToDestroy {\n\t\t\t\tt.Kub.Delete(manifest)\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *PoolManager) vmWaitingCleanupLook() {\n\tlogger := log.WithName(\"vmWaitingCleanupLook\")\n\tc := time.Tick(3 * time.Second)\n\tlogger.Info(\"starting cleanup loop for waiting mac addresses\")\n\tfor _ = range c {\n\t\tp.poolMutex.Lock()\n\n\t\tconfigMap, err := p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Get(context.TODO(), names.WAITING_VMS_CONFIGMAP, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"failed to get config map\", \"configMapName\", names.WAITING_VMS_CONFIGMAP)\n\t\t\tp.poolMutex.Unlock()\n\t\t\tcontinue\n\t\t}\n\n\t\tconfigMapUpdateNeeded := false\n\t\tif configMap.Data == nil {\n\t\t\tlogger.V(1).Info(\"the configMap is empty\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"macPoolMap\", p.macPoolMap)\n\t\t\tp.poolMutex.Unlock()\n\t\t\tcontinue\n\t\t}\n\n\t\tfor macAddress, allocationTime := range configMap.Data {\n\t\t\tt, err := time.Parse(time.RFC3339, allocationTime)\n\t\t\tif err != nil {\n\t\t\t\t// TODO: remove the mac from the wait map??\n\t\t\t\tlogger.Error(err, \"failed to parse allocation time\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlogger.Info(\"data:\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"configMap.Data\", configMap.Data, \"macPoolMap\", p.macPoolMap)\n\n\t\t\tif time.Now().After(t.Add(time.Duration(p.waitTime) * time.Second)) {\n\t\t\t\tconfigMapUpdateNeeded = true\n\t\t\t\tdelete(configMap.Data, macAddress)\n\t\t\t\tmacAddress = strings.Replace(macAddress, \"-\", \":\", 5)\n\t\t\t\tdelete(p.macPoolMap, macAddress)\n\t\t\t\tlogger.Info(\"released mac address in waiting loop\", \"macAddress\", macAddress)\n\t\t\t}\n\t\t}\n\n\t\tif configMapUpdateNeeded {\n\t\t\t_, err = p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Update(context.TODO(), configMap, metav1.UpdateOptions{})\n\t\t}\n\n\t\tif err == nil {\n\t\t\tlogger.Info(\"the configMap successfully updated\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"macPoolMap\", p.macPoolMap)\n\t\t} else {\n\t\t\tlogger.Info(\"the configMap failed to update\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"macPoolMap\", p.macPoolMap)\n\t\t}\n\n\t\tp.poolMutex.Unlock()\n\t}\n}", "func (m *Machine) Delete() {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.manager.Delete()\n\n\tif m.backoffTimer != nil {\n\t\tm.backoffTimer.Stop()\n\t}\n\n\tif m.cancel != nil {\n\t\tm.Infof(\"runner\", \"Stopping\")\n\t\tm.cancel()\n\t}\n\n\tm.startTime = time.Time{}\n}", "func (m *Manager) RemoveAllAndWait() {\n\tctrls := m.removeAll()\n\tfor _, ctrl := range ctrls {\n\t\t<-ctrl.terminated\n\t}\n}", "func (m *Manager) RemoveAllAndWait() {\n\tctrls := m.removeAll()\n\tfor _, ctrl := range ctrls {\n\t\t<-ctrl.terminated\n\t}\n}", "func (s *Server) CleanupForDestroy() {\n\ts.CtxCancel()\n\ts.Events().Destroy()\n\ts.DestroyAllSinks()\n\ts.Websockets().CancelAll()\n\ts.powerLock.Destroy()\n}", "func (llrb *LLRB) Destroy() {\n\tclose(llrb.finch)\n\tfor llrb.dodestory() == false {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\tinfof(\"%v destroyed\\n\", llrb.logprefix)\n}", "func (m *Machine) WaitForPVsDelete(labels string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.PVsDeleted(labels)\n\t})\n}", "func (jj *Juju) Destroy(user, service string) (*simplejson.Json, error) {\n id := jj.id(user, service)\n report := JSON(fmt.Sprintf(`{\"time\": \"%s\"}`, time.Now()))\n log.Infof(\"destroy juju service: %s\\n\", id)\n\n //Note For now this is massive and basic destruction\n unitArgs := []string{\"destroy-unit\", id + \"/0\", \"--show-log\"}\n serviceArgs := []string{\"destroy-service\", id, \"--show-log\"}\n\n cmd := exec.Command(\"juju\", \"status\", id, \"--format\", \"json\")\n output, err := cmd.CombinedOutput()\n if err != nil { return EmptyJSON(), err }\n status, err := simplejson.NewJson(output)\n machineID, err := status.GetPath(\"services\", id, \"units\", id+\"/0\", \"machine\").String()\n if err != nil { return EmptyJSON(), err }\n machineArgs := []string{\"destroy-machine\", machineID, \"--show-log\"}\n\n client, err := goresque.Dial(redisURL)\n if err != nil { return EmptyJSON(), err }\n log.Infof(\"enqueue destroy-unit\")\n client.Enqueue(workerClass, \"fork\", jj.Path, unitArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-service\")\n client.Enqueue(workerClass, \"fork\", jj.Path, serviceArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-machine\")\n client.Enqueue(workerClass, \"fork\", jj.Path, machineArgs)\n\n report.Set(\"provider\", \"juju\")\n report.Set(\"unit destroyed\", id + \"/0\")\n report.Set(\"service destroyed\", id)\n report.Set(\"machine destroyed\", machineID)\n report.Set(\"unit arguments\", unitArgs)\n report.Set(\"service arguments\", serviceArgs)\n report.Set(\"machine arguments\", machineArgs)\n return report, nil\n}", "func (v *Vagrant) Teardown() {\n\tfor _, node := range v.nodes {\n\t\tvnode, ok := node.(*SSHNode)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"invalid node type encountered: %T\", vnode)\n\t\t\tcontinue\n\t\t}\n\t\tvnode.Cleanup()\n\t}\n\tvCmd := &VagrantCommand{ContivNodes: v.expectedNodes}\n\toutput, err := vCmd.RunWithOutput(\"destroy\", \"-f\")\n\tif err != nil {\n\t\tlog.Errorf(\"Vagrant destroy failed. Error: %s Output: \\n%s\\n\",\n\t\t\terr, output)\n\t}\n\n\tv.nodes = map[string]TestbedNode{}\n\tv.expectedNodes = 0\n}", "func (a *Actuator) Delete(c *clusterv1.Cluster, m *clusterv1.Machine) error {\n\tglog.Infof(\"Deleting machine %s for cluster %s.\", m.Name, c.Name)\n\n\tif a.machineSetupConfigGetter == nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"valid machineSetupConfigGetter is required\"), deleteEventAction)\n\t}\n\n\t// First get provider config\n\tmachineConfig, err := a.machineProviderConfig(m.Spec.ProviderConfig)\n\tif err != nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"Cannot unmarshal machine's providerConfig field: %v\", err), deleteEventAction)\n\t}\n\n\t// Now validate\n\tif err := a.validateMachine(m, machineConfig); err != nil {\n\t\treturn a.handleMachineError(m, err, deleteEventAction)\n\t}\n\n\t// Check if the machine exists (here we mean it is not bootstrapping.)\n\texists, err := a.Exists(c, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\tglog.Infof(\"Machine %s for cluster %s does not exists (maybe it is still bootstrapping), skipping.\", m.Name, c.Name)\n\t\treturn nil\n\t}\n\n\t// The exists case here.\n\tglog.Infof(\"Machine %s for cluster %s exists.\", m.Name, c.Name)\n\n\tconfigParams := &MachineParams{\n\t\tRoles: machineConfig.Roles,\n\t\tVersions: m.Spec.Versions,\n\t}\n\n\tmetadata, err := a.getMetadata(c, m, configParams, machineConfig.SSHConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Metadata retrieved: machine %s for cluster %s\", m.Name, c.Name)\n\n\tprivateKey, passPhrase, err := a.getPrivateKey(c, m.Namespace, machineConfig.SSHConfig.SecretName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Running shutdown script: machine %s for cluster %s...\", m.Name, c.Name)\n\n\tsshClient := ssh.NewSSHProviderClient(privateKey, passPhrase, machineConfig.SSHConfig)\n\n\tif err = sshClient.WriteFile(metadata.ShutdownScript, \"/var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"Error copying shutdown script: %v\", err)\n\t\treturn err\n\t}\n\n\tif err = sshClient.ProcessCMD(\"chmod +x /var/tmp/shutdownscript.sh && bash /var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"running shutdown script error: %v\", err)\n\t\treturn err\n\t}\n\n\ta.eventRecorder.Eventf(m, corev1.EventTypeNormal, \"Deleted\", \"Deleted Machine %v\", m.Name)\n\treturn nil\n}", "func vSphereRemoveHost(ctx context.Context, obj *object.HostSystem) error {\n\tdisconnectTask, err := obj.Disconnect(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := disconnectTask.Wait(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tdestroyTask, err := obj.Destroy(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn destroyTask.Wait(ctx)\n}", "func (o *ClusterUninstaller) destroyImages() error {\n\tfirstPassList, err := o.listImages()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(firstPassList.list()) == 0 {\n\t\treturn nil\n\t}\n\n\titems := o.insertPendingItems(imageTypeName, firstPassList.list())\n\tfor _, item := range items {\n\t\to.Logger.Debugf(\"destroyImages: firstPassList: %v / %v\", item.name, item.id)\n\t}\n\n\tctx, cancel := o.contextWithTimeout()\n\tdefer cancel()\n\n\tfor _, item := range items {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\to.Logger.Debugf(\"destroyImages: case <-ctx.Done()\")\n\t\t\treturn o.Context.Err() // we're cancelled, abort\n\t\tdefault:\n\t\t}\n\n\t\tbackoff := wait.Backoff{\n\t\t\tDuration: 15 * time.Second,\n\t\t\tFactor: 1.1,\n\t\t\tCap: leftInContext(ctx),\n\t\t\tSteps: math.MaxInt32}\n\t\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\t\terr2 := o.deleteImage(item)\n\t\t\tif err2 == nil {\n\t\t\t\treturn true, err2\n\t\t\t}\n\t\t\to.errorTracker.suppressWarning(item.key, err2, o.Logger)\n\t\t\treturn false, err2\n\t\t})\n\t\tif err != nil {\n\t\t\to.Logger.Fatal(\"destroyImages: ExponentialBackoffWithContext (destroy) returns \", err)\n\t\t}\n\t}\n\n\tif items = o.getPendingItems(imageTypeName); len(items) > 0 {\n\t\tfor _, item := range items {\n\t\t\to.Logger.Debugf(\"destroyImages: found %s in pending items\", item.name)\n\t\t}\n\t\treturn errors.Errorf(\"destroyImages: %d undeleted items pending\", len(items))\n\t}\n\n\tbackoff := wait.Backoff{\n\t\tDuration: 15 * time.Second,\n\t\tFactor: 1.1,\n\t\tCap: leftInContext(ctx),\n\t\tSteps: math.MaxInt32}\n\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\tsecondPassList, err2 := o.listImages()\n\t\tif err2 != nil {\n\t\t\treturn false, err2\n\t\t}\n\t\tif len(secondPassList) == 0 {\n\t\t\t// We finally don't see any remaining instances!\n\t\t\treturn true, nil\n\t\t}\n\t\tfor _, item := range secondPassList {\n\t\t\to.Logger.Debugf(\"destroyImages: found %s in second pass\", item.name)\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\to.Logger.Fatal(\"destroyImages: ExponentialBackoffWithContext (list) returns \", err)\n\t}\n\n\treturn nil\n}", "func (m *Mqtt) Destroy() error {\n\tm.token = m.client.Unsubscribe(\"go-mqtt/sample\")\n\tm.token.Wait()\n\tm.client.Disconnect(250)\n\treturn m.token.Error()\n}", "func (s *StepCreateVM) Cleanup(state multistep.StateBag) {\n\t_, cancelled := state.GetOk(multistep.StateCancelled)\n\t_, halted := state.GetOk(multistep.StateHalted)\n\tif !cancelled && !halted {\n\t\treturn\n\t}\n\n\tif vm, ok := state.GetOk(\"vm\"); ok {\n\t\tui := state.Get(\"ui\").(packer.Ui)\n\t\td := state.Get(\"driver\").(*Driver)\n\n\t\tui.Say(\"Destroying VM...\")\n\n\t\terr := d.DestroyVM(vm.(*object.VirtualMachine))\n\t\tif err != nil {\n\t\t\tui.Error(err.Error())\n\t\t}\n\t}\n}", "func (l *HostStateListener) cleanUpContainers(stateIDs []string, getLock bool) {\n\tplog.WithField(\"stateids\", stateIDs).Debug(\"cleaning up containers\")\n\t// Start shutting down all of the containers in parallel\n\twg := &sync.WaitGroup{}\n\tfor _, s := range stateIDs {\n\t\tcontainerExit := func() <-chan time.Time {\n\t\t\tif getLock {\n\t\t\t\tl.mu.RLock()\n\t\t\t\tdefer l.mu.RUnlock()\n\t\t\t}\n\t\t\t_, cExit := l.getExistingThread(s)\n\t\t\treturn cExit\n\t\t}()\n\t\twg.Add(1)\n\t\tgo func(stateID string, cExit <-chan time.Time) {\n\t\t\tdefer wg.Done()\n\t\t\tl.shutDownContainer(stateID, cExit)\n\t\t}(s, containerExit)\n\t}\n\n\t// Remove the threads from our internal thread list\n\t// Need to get the lock here if we don't already have it\n\tfunc() {\n\t\tif getLock {\n\t\t\tl.mu.Lock()\n\t\t\tdefer l.mu.Unlock()\n\t\t}\n\t\tfor _, s := range stateIDs {\n\t\t\tl.removeExistingThread(s)\n\t\t}\n\t}()\n\n\t// Wait for all containers to shut down\n\twg.Wait()\n}", "func (p *Pool) Destroy() {\n\tvar sig struct{}\n\tp.exitChan <- sig\n}", "func (o *ClusterUninstaller) destroyVPCs() error {\n\tfirstPassList, err := o.listVPCs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(firstPassList.list()) == 0 {\n\t\treturn nil\n\t}\n\n\titems := o.insertPendingItems(vpcTypeName, firstPassList.list())\n\n\tctx, cancel := o.contextWithTimeout()\n\tdefer cancel()\n\n\tfor _, item := range items {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\to.Logger.Debugf(\"destroyVPCs: case <-ctx.Done()\")\n\t\t\treturn o.Context.Err() // we're cancelled, abort\n\t\tdefault:\n\t\t}\n\n\t\tbackoff := wait.Backoff{\n\t\t\tDuration: 15 * time.Second,\n\t\t\tFactor: 1.1,\n\t\t\tCap: leftInContext(ctx),\n\t\t\tSteps: math.MaxInt32}\n\t\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\t\terr2 := o.deleteVPC(item)\n\t\t\tif err2 == nil {\n\t\t\t\treturn true, err2\n\t\t\t}\n\t\t\to.errorTracker.suppressWarning(item.key, err2, o.Logger)\n\t\t\treturn false, err2\n\t\t})\n\t\tif err != nil {\n\t\t\to.Logger.Fatal(\"destroyVPCs: ExponentialBackoffWithContext (destroy) returns \", err)\n\t\t}\n\t}\n\n\tif items = o.getPendingItems(vpcTypeName); len(items) > 0 {\n\t\tfor _, item := range items {\n\t\t\to.Logger.Debugf(\"destroyVPCs: found %s in pending items\", item.name)\n\t\t}\n\t\treturn errors.Errorf(\"destroyVPCs: %d undeleted items pending\", len(items))\n\t}\n\n\tbackoff := wait.Backoff{\n\t\tDuration: 15 * time.Second,\n\t\tFactor: 1.1,\n\t\tCap: leftInContext(ctx),\n\t\tSteps: math.MaxInt32}\n\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\tsecondPassList, err2 := o.listVPCs()\n\t\tif err2 != nil {\n\t\t\treturn false, err2\n\t\t}\n\t\tif len(secondPassList) == 0 {\n\t\t\t// We finally don't see any remaining instances!\n\t\t\treturn true, nil\n\t\t}\n\t\tfor _, item := range secondPassList {\n\t\t\to.Logger.Debugf(\"destroyVPCs: found %s in second pass\", item.name)\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\to.Logger.Fatal(\"destroyVPCs: ExponentialBackoffWithContext (list) returns \", err)\n\t}\n\n\treturn nil\n}", "func (m *member) Terminate(t *testing.T) {\n\tm.s.Stop()\n\tfor _, hs := range m.hss {\n\t\ths.CloseClientConnections()\n\t\ths.Close()\n\t}\n\tif err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (m *Manager) Delete() {\n\tm.machine.Infof(m.machine.Name(), \"Stopping manager\")\n\tm.cancel()\n\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tfor _, w := range m.watchers {\n\t\tw.Delete()\n\t}\n}", "func (o *ClusterUninstaller) destroyDisks() error {\n\tfound, err := o.listDisks()\n\tif err != nil {\n\t\treturn err\n\t}\n\titems := o.insertPendingItems(\"disk\", found)\n\tfor _, item := range items {\n\t\terr := o.deleteDisk(item)\n\t\tif err != nil {\n\t\t\to.errorTracker.suppressWarning(item.key, err, o.Logger)\n\t\t}\n\t}\n\n\tfor _, item := range items {\n\t\terr := o.waitForDiskDeletion(item)\n\t\tif err != nil {\n\t\t\to.errorTracker.suppressWarning(item.key, err, o.Logger)\n\t\t}\n\t}\n\n\tif items = o.getPendingItems(\"disk\"); len(items) > 0 {\n\t\treturn errors.Errorf(\"%d items pending\", len(items))\n\t}\n\treturn nil\n}", "func (f *TestFramework) DestroyMachineSet() error {\n\tlog.Print(\"Destroying MachineSets\")\n\tif f.machineSet == nil {\n\t\tlog.Print(\"unable to find MachineSet to be deleted, was skip VM setup option selected ?\")\n\t\tlog.Print(\"MachineSets/Machines needs to be deleted manually \\nNot deleting MachineSets...\")\n\t\treturn nil\n\t}\n\terr := f.machineClient.MachineSets(\"openshift-machine-api\").Delete(context.TODO(), f.machineSet.Name, metav1.DeleteOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete MachineSet %v\", err)\n\t}\n\tlog.Print(\"MachineSets Destroyed\")\n\treturn nil\n}", "func (rhost *rhostData) destroy() {\n\tif rhost.connected {\n\t\trhost.connected = false\n\t\trhost.wg.Done()\n\t}\n}", "func (tc *testContext) waitForServicesConfigMapDeletion(cmName string) error {\n\terr := wait.PollImmediate(retry.Interval, retry.ResourceChangeTimeout, func() (bool, error) {\n\t\t_, err := tc.client.K8s.CoreV1().ConfigMaps(wmcoNamespace).Get(context.TODO(), cmName, meta.GetOptions{})\n\t\tif err == nil {\n\t\t\t// Retry if the resource is found\n\t\t\treturn false, nil\n\t\t}\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"error retrieving ConfigMap: %s: %w\", cmName, err)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error waiting for ConfigMap deletion %s/%s: %w\", wmcoNamespace, cmName, err)\n\t}\n\treturn nil\n}", "func exitHostMM(ctx context.Context, host *object.HostSystem, timeout int32) {\n\ttask, err := host.ExitMaintenanceMode(ctx, timeout)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\t_, err = task.WaitForResult(ctx, nil)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tframework.Logf(\"Host: %v exited from maintenance mode\", host)\n}", "func (d *Deployer) Destroy(dep *Deployment, printServerLogs bool) {\n\tfor _, hsDep := range dep.HS {\n\t\tif printServerLogs {\n\t\t\tprintLogs(d.Docker, hsDep.ContainerID, hsDep.ContainerID)\n\t\t}\n\t\terr := d.Docker.ContainerKill(context.Background(), hsDep.ContainerID, \"KILL\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to destroy container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t\terr = d.Docker.ContainerRemove(context.Background(), hsDep.ContainerID, types.ContainerRemoveOptions{\n\t\t\tForce: true,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to remove container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t}\n}", "func (s *Reconciler) Delete(ctx context.Context) error {\n\tvmSpec := &virtualmachines.Spec{\n\t\tName: s.scope.Machine.Name,\n\t}\n\n\t// Getting a vm object does not work here so let's assume\n\t// an instance is really being deleted\n\tif s.scope.Machine.Annotations == nil {\n\t\ts.scope.Machine.Annotations = make(map[string]string)\n\t}\n\ts.scope.Machine.Annotations[MachineInstanceStateAnnotationName] = string(machinev1.VMStateDeleting)\n\tvmStateDeleting := machinev1.VMStateDeleting\n\ts.scope.MachineStatus.VMState = &vmStateDeleting\n\n\terr := s.virtualMachinesSvc.Delete(ctx, vmSpec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete machine: %w\", err)\n\t}\n\n\tosDiskSpec := &disks.Spec{\n\t\tName: azure.GenerateOSDiskName(s.scope.Machine.Name),\n\t}\n\terr = s.disksSvc.Delete(ctx, osDiskSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"failed to delete OS disk: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.Vnet == \"\" {\n\t\treturn fmt.Errorf(\"MachineConfig vnet is missing on machine %s\", s.scope.Machine.Name)\n\t}\n\n\tnetworkInterfaceSpec := &networkinterfaces.Spec{\n\t\tName: azure.GenerateNetworkInterfaceName(s.scope.Machine.Name),\n\t\tVnetName: s.scope.MachineConfig.Vnet,\n\t}\n\n\terr = s.networkInterfacesSvc.Delete(ctx, networkInterfaceSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"Unable to delete network interface: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.PublicIP {\n\t\tpublicIPName, err := azure.GenerateMachinePublicIPName(s.scope.MachineConfig.Name, s.scope.Machine.Name)\n\t\tif err != nil {\n\t\t\t// Only when the generated name is longer than allowed by the Azure portal\n\t\t\t// That can happen only when\n\t\t\t// - machine name is changed (can't happen without creating a new CR)\n\t\t\t// - cluster name is changed (could happen but then we will get different name anyway)\n\t\t\t// - machine CR was created with too long public ip name (in which case no instance was created)\n\t\t\tklog.Info(\"Generated public IP name was too long, skipping deletion of the resource\")\n\t\t\treturn nil\n\t\t}\n\n\t\terr = s.publicIPSvc.Delete(ctx, &publicips.Spec{\n\t\t\tName: publicIPName,\n\t\t})\n\t\tif err != nil {\n\t\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\t\tName: s.scope.Machine.Name,\n\t\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\t\tReason: err.Error(),\n\t\t\t})\n\t\t\treturn fmt.Errorf(\"unable to delete Public IP: %w\", err)\n\t\t}\n\t}\n\n\t// Delete the availability set with the given name if no virtual machines are attached to it.\n\tif err := s.availabilitySetsSvc.Delete(ctx, &availabilitysets.Spec{\n\t\tName: s.getAvailibilitySetName(),\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to delete availability set: %w\", err)\n\t}\n\n\treturn nil\n}", "func (p *MockDeployPlugin) Destroy(cluster *lang.Cluster, deployName string, params util.NestedParameterMap, eventLog *event.Log) error {\n\ttime.Sleep(p.SleepTime)\n\treturn nil\n}", "func (c *APIClient) WaitIstioMeshDeleted(orgID, workspaceID, meshID, timeout int) error {\n\tfor i := 1; i < timeout; i++ {\n\t\t_, err := c.GetIstioMesh(orgID, workspaceID, meshID)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"404\") {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn fmt.Errorf(\"timeout (%d seconds) reached before isto mesh deleted\", timeout)\n}", "func WaitTerminations(done chan bool) {\n\tremaining := SegmentListeners\n\tfor remaining > 0 {\n\t\tlog.Printf(\"WaitTerminations: waiting for %d listeners\\n\", remaining)\n\t\t_ = <-done\n\t\tremaining--\n\t}\n}", "func (m *Machine) WaitForStatefulSetDelete(namespace string, name string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\tfound, err := m.StatefulSetExist(namespace, name)\n\t\treturn !found, err\n\t})\n}", "func DelContainerForceMultyTime(c *check.C, cname string) {\n\tdone := make(chan bool, 1)\n\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\ttimeout := make(chan bool)\n\tgo func() {\n\t\ttime.Sleep(3 * time.Second)\n\t\ttimeout <- true\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-timeout:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tresp, _ := DelContainerForce(c, cname)\n\t\t\tif resp.StatusCode == 204 {\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}\n\t}\n}", "func (c CommitterProbe) WaitCleanup() {\n\tc.cleanWg.Wait()\n}", "func Test_Static_Pool_Destroy_And_Close_While_Wait(t *testing.T) {\n\tctx := context.Background()\n\tp, err := Initialize(\n\t\tctx,\n\t\tfunc() *exec.Cmd { return exec.Command(\"php\", \"../tests/client.php\", \"delay\", \"pipes\") },\n\t\tpipe.NewPipeFactory(),\n\t\t&Config{\n\t\t\tNumWorkers: 1,\n\t\t\tAllocateTimeout: time.Second,\n\t\t\tDestroyTimeout: time.Second,\n\t\t},\n\t)\n\n\tassert.NotNil(t, p)\n\tassert.NoError(t, err)\n\n\tgo func() {\n\t\t_, errP := p.Exec(&payload.Payload{Body: []byte(\"100\")})\n\t\tif errP != nil {\n\t\t\tt.Errorf(\"error executing payload: error %v\", err)\n\t\t}\n\t}()\n\ttime.Sleep(time.Millisecond * 100)\n\n\tp.Destroy(ctx)\n\t_, err = p.Exec(&payload.Payload{Body: []byte(\"100\")})\n\tassert.Error(t, err)\n}", "func (d *Death) WaitForDeath(closable ...io.Closer) (err error) {\n\td.wg.Wait()\n\td.log.Info(\"Shutdown started...\")\n\tcount := len(closable)\n\td.log.Debug(\"Closing \", count, \" objects\")\n\tif count > 0 {\n\t\treturn d.closeInMass(closable...)\n\t}\n\treturn nil\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func TestWaitUntilRunning(t *testing.T) {\n\tts := memorytopo.NewServer(\"cell1\")\n\tm := NewManager(ts)\n\n\t// Start it 3 times i.e. restart it 2 times.\n\tfor i := 1; i <= 3; i++ {\n\t\t// Run the manager in the background.\n\t\twg, _, cancel := StartManager(m)\n\n\t\t// Shut it down and wait for the shutdown to complete.\n\t\tcancel()\n\t\twg.Wait()\n\t}\n}", "func (rem *Remote) Destroy() {\n\trem.Manager.Destroy()\n}", "func (m *TimeServiceManager) Kill() {\n\tif len(m.Instances) > 0 {\n\t\tfmt.Printf(\"There are %d instances. \", len(m.Instances))\n\t\tn := rand.Intn(len(m.Instances))\n\t\tfmt.Printf(\"Killing Instance %d\\n\", n)\n\t\tclose(m.Instances[n].Dead)\n\t\tm.Instances = append(m.Instances[:n], m.Instances[n+1:]...)\n\t} else {\n\t\tfmt.Println(\"No instance to kill\")\n\t}\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func (e *EventBus) Destroy() {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\t// Stop every pool that exists for a given callback topic.\n\tfor _, cp := range e.pools {\n\t\tcp.pool.Stop()\n\t}\n\n\te.pools = make(map[string]*CallbackPool)\n}", "func WaitForDeletion(profileKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(time.Second, timeout, func() (bool, error) {\n\t\tprof := &performancev2.PerformanceProfile{}\n\t\tif err := testclient.Client.Get(context.TODO(), profileKey, prof); errors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func WaitForBKClusterToTerminate(t *testing.T, k8client client.Client, b *bkapi.BookkeeperCluster) error {\n\tlog.Printf(\"waiting for Bookkeeper cluster to terminate: %s\", b.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(b.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"bookkeeper_cluster\": b.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"bookkeeper cluster terminated: %s\", b.Name)\n\treturn nil\n}", "func (t *SubprocessTest) destroy() (err error) {\n\t// Make sure we clean up after ourselves after everything else below.\n\n\t// Close what is necessary.\n\tfor _, c := range t.ToClose {\n\t\tif c == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\togletest.ExpectEq(nil, c.Close())\n\t}\n\n\t// If we didn't try to mount the file system, there's nothing further to do.\n\tif t.mountSampleErr == nil {\n\t\treturn nil\n\t}\n\n\t// In the background, initiate an unmount.\n\tunmountErrChan := make(chan error)\n\tgo func() {\n\t\tunmountErrChan <- unmount(t.Dir)\n\t}()\n\n\t// Make sure we wait for the unmount, even if we've already returned early in\n\t// error. Return its error if we haven't seen any other error.\n\tdefer func() {\n\t\t// Wait.\n\t\tunmountErr := <-unmountErrChan\n\t\tif unmountErr != nil {\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"unmount:\", unmountErr)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = fmt.Errorf(\"unmount: %v\", unmountErr)\n\t\t\treturn\n\t\t}\n\n\t\t// Clean up.\n\t\togletest.ExpectEq(nil, os.Remove(t.Dir))\n\t}()\n\n\t// Wait for the subprocess.\n\tif err := <-t.mountSampleErr; err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func waitUntilRDSClusterDeleted(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\n\tinput := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(rdsClusterName),\n\t}\n\n\t// Check if Cluster exists\n\t_, err := rdsClientSess.DescribeDBClusters(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t} else {\n\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: DEBUG - fmt.Println(result)\n\tfmt.Printf(\"Wait until RDS cluster [%v] is fully deleted...\\n\", rdsClusterName)\n\n\tstart := time.Now()\n\n\tmaxWaitAttempts := 120\n\n\t// Check until deleted\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start).Seconds()\n\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Cluster deletion elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBClusters(input)\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\t\tfmt.Println(\"RDS Cluster deleted successfully\")\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"Cluster status: [%s]\\n\", *resp.DBClusters[0].Status)\n\t\tif *resp.DBClusters[0].Status == \"terminated\" {\n\t\t\tfmt.Printf(\"RDS cluster [%v] deleted successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\n\t// Timeout Err\n\treturn fmt.Errorf(\"RDS Cluster [%v] could not be deleted, exceed max wait attemps\\n\", rdsClusterName)\n}", "func waitForMachineSetToNotExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForObjectToNotExist(\n\t\tnamespace, name,\n\t\tfunc(namespace, name string) (metav1.Object, error) {\n\t\t\treturn getMachineSet(capiClient, namespace, name)\n\t\t},\n\t)\n}", "func (c *VMReplicaSet) orphan(cm *controller.VirtualMachineControllerRefManager, rs *virtv1.VirtualMachineReplicaSet, vms []*virtv1.VirtualMachine) error {\n\n\tvar wg sync.WaitGroup\n\terrChan := make(chan error, len(vms))\n\twg.Add(len(vms))\n\n\tfor _, vm := range vms {\n\t\tgo func(vm *virtv1.VirtualMachine) {\n\t\t\tdefer wg.Done()\n\t\t\terr := cm.ReleaseVirtualMachine(vm)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t}\n\t\t}(vm)\n\t}\n\twg.Wait()\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tdefault:\n\t}\n\treturn nil\n}", "func (w *worker) Terminate() {\n\tfor _, v := range w.allGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allNodes {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedNodes {\n\t\tv.Released()\n\t}\n\tif w.availableGateway != nil {\n\t\tw.availableGateway.Released()\n\t}\n\tif w.availableMaster != nil {\n\t\tw.availableMaster.Released()\n\t}\n\tif w.availableNode != nil {\n\t\tw.availableNode.Released()\n\t}\n}", "func WaitForDeletion(pod *corev1.Pod, timeout time.Duration) error {\n\treturn wait.PollImmediate(time.Second, timeout, func() (bool, error) {\n\t\tif err := testclient.Client.Get(context.TODO(), client.ObjectKeyFromObject(pod), pod); errors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func (gi *GrpcInvoker) Destroy() {\n\tgi.quitOnce.Do(func() {\n\t\tgi.BaseInvoker.Destroy()\n\t\tclient := gi.getClient()\n\t\tif client != nil {\n\t\t\tgi.setClient(nil)\n\t\t\tclient.Close()\n\t\t}\n\t})\n}", "func WaitForDeletion(cs *testclient.ClientSet, pod *corev1.Pod, timeout time.Duration) error {\n\treturn wait.PollImmediate(time.Second, timeout, func() (bool, error) {\n\t\t_, err := cs.Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{})\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func Destroy(name string, t ObjectType, deferred bool) error {\n\tcmd := &Cmd{\n\t\tObjset_type: uint64(t),\n\t}\n\treturn NvlistIoctl(zfsHandle.Fd(), ZFS_IOC_DESTROY, name, cmd, nil, nil, nil)\n}", "func WaitUntilDeleted(ctx context.Context, client client.Client, namespace, name string) error {\n\tmr := &resourcesv1alpha1.ManagedResource{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tif err := kutil.WaitUntilResourceDeleted(ctx, client, mr, IntervalWait); err != nil {\n\t\tresourcesAppliedCondition := gardencorev1beta1helper.GetCondition(mr.Status.Conditions, resourcesv1alpha1.ResourcesApplied)\n\t\tif resourcesAppliedCondition != nil && resourcesAppliedCondition.Status != gardencorev1beta1.ConditionTrue &&\n\t\t\t(resourcesAppliedCondition.Reason == resourcesv1alpha1.ConditionDeletionFailed || resourcesAppliedCondition.Reason == resourcesv1alpha1.ConditionDeletionPending) {\n\t\t\tdeleteError := fmt.Errorf(\"error while waiting for all resources to be deleted: %w:\\n%s\", err, resourcesAppliedCondition.Message)\n\t\t\treturn gardencorev1beta1helper.DetermineError(deleteError, deleteError.Error())\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func waitForSignals(unixSock string) {\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\n\tfor sig := range signals {\n\t\tlogrus.Debugf(\"Received signal %s , clean up...\", sig)\n\t\tif _, err := os.Stat(unixSock); err == nil {\n\t\t\tlogrus.Debugf(\"Remove %s\", unixSock)\n\t\t\tif err := os.Remove(unixSock); err != nil {\n\t\t\t\tlogrus.Errorf(\"Remove %s failed: %s\", unixSock, err.Error())\n\t\t\t}\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n}", "func (p *Provider) Reset(vms vm.List) error {\n\t// Map from project to map of zone to list of machines in that project/zone.\n\tprojectZoneMap := make(map[string]map[string][]string)\n\tfor _, v := range vms {\n\t\tif v.Provider != ProviderName {\n\t\t\treturn errors.Errorf(\"%s received VM instance from %s\", ProviderName, v.Provider)\n\t\t}\n\t\tif projectZoneMap[v.Project] == nil {\n\t\t\tprojectZoneMap[v.Project] = make(map[string][]string)\n\t\t}\n\n\t\tprojectZoneMap[v.Project][v.Zone] = append(projectZoneMap[v.Project][v.Zone], v.Name)\n\t}\n\n\tvar g errgroup.Group\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)\n\tdefer cancel()\n\tfor project, zoneMap := range projectZoneMap {\n\t\tfor zone, names := range zoneMap {\n\t\t\targs := []string{\n\t\t\t\t\"compute\", \"instances\", \"reset\",\n\t\t\t}\n\n\t\t\targs = append(args, \"--project\", project)\n\t\t\targs = append(args, \"--zone\", zone)\n\t\t\targs = append(args, names...)\n\n\t\t\tg.Go(func() error {\n\t\t\t\tcmd := exec.CommandContext(ctx, \"gcloud\", args...)\n\n\t\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Command: gcloud %s\\nOutput: %s\", args, output)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\n\treturn g.Wait()\n}", "func WaitForNamespacesDeleted(ctx context.Context, c clientset.Interface, namespaces []string, timeout time.Duration) error {\n\tginkgo.By(fmt.Sprintf(\"Waiting for namespaces %+v to vanish\", namespaces))\n\tnsMap := map[string]bool{}\n\tfor _, ns := range namespaces {\n\t\tnsMap[ns] = true\n\t}\n\t//Now POLL until all namespaces have been eradicated.\n\treturn wait.PollWithContext(ctx, 2*time.Second, timeout,\n\t\tfunc(ctx context.Context) (bool, error) {\n\t\t\tnsList, err := c.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tfor _, item := range nsList.Items {\n\t\t\t\tif _, ok := nsMap[item.Name]; ok {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n}", "func WaitForPravegaClusterToTerminate(t *testing.T, k8client client.Client, p *api.PravegaCluster) error {\n\tlog.Printf(\"waiting for pravega cluster to terminate: %s\", p.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(p.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(p.LabelsForPravegaCluster())},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"pravega cluster terminated: %s\", p.Name)\n\treturn nil\n}", "func tearDownVMs(t *testing.T, images []string, vmNum int, isSyncOffload bool) {\n\tfor i := 0; i < vmNum; i++ {\n\t\tlog.Infof(\"Shutting down VM %d, images: %s\", i, images[i%len(images)])\n\t\tvmIDString := strconv.Itoa(i)\n\t\tmessage, err := funcPool.RemoveInstance(vmIDString, images[i%len(images)], isSyncOffload)\n\t\trequire.NoError(t, err, \"Function returned error, \"+message)\n\t}\n}", "func (p *BuildAhTest) Cleanup() {\n\t// Nuke tempdir\n\tif err := os.RemoveAll(p.TempDir); err != nil {\n\t\tfmt.Printf(\"%q\\n\", err)\n\t}\n\tcleanup := p.BuildAh([]string{\"rmi\", \"-a\", \"-f\"})\n\tcleanup.WaitWithDefaultTimeout()\n}", "func (r *Reconciler) deleteMachine(\n\tctx context.Context,\n\tlog *zap.SugaredLogger,\n\tprov cloudprovidertypes.Provider,\n\tproviderName providerconfigtypes.CloudProvider,\n\tmachine *clusterv1alpha1.Machine,\n\tskipEviction bool,\n) (*reconcile.Result, error) {\n\tvar (\n\t\tshouldEvict bool\n\t\terr error\n\t)\n\n\tif !skipEviction {\n\t\tshouldEvict, err = r.shouldEvict(ctx, log, machine)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tshouldCleanUpVolumes, err := r.shouldCleanupVolumes(ctx, log, machine, providerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar evictedSomething, deletedSomething bool\n\tvar volumesFree = true\n\tif shouldEvict {\n\t\tevictedSomething, err = eviction.New(machine.Status.NodeRef.Name, r.client, r.kubeClient).Run(ctx, log)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to evict node %s: %w\", machine.Status.NodeRef.Name, err)\n\t\t}\n\t}\n\tif shouldCleanUpVolumes {\n\t\tdeletedSomething, volumesFree, err = poddeletion.New(machine.Status.NodeRef.Name, r.client, r.kubeClient).Run(ctx, log)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to delete pods bound to volumes running on node %s: %w\", machine.Status.NodeRef.Name, err)\n\t\t}\n\t}\n\n\tif evictedSomething || deletedSomething || !volumesFree {\n\t\treturn &reconcile.Result{RequeueAfter: 10 * time.Second}, nil\n\t}\n\n\tif result, err := r.deleteCloudProviderInstance(ctx, log, prov, machine); result != nil || err != nil {\n\t\treturn result, err\n\t}\n\n\t// Delete the node object only after the instance is gone, `deleteCloudProviderInstance`\n\t// returns with a nil-error after it triggers the instance deletion but it is async for\n\t// some providers hence the instance deletion may not been executed yet\n\t// `FinalizerDeleteInstance` stays until the instance is really gone thought, so we check\n\t// for that here\n\tif sets.NewString(machine.Finalizers...).Has(FinalizerDeleteInstance) {\n\t\treturn nil, nil\n\t}\n\n\tnodes, err := r.retrieveNodesRelatedToMachine(ctx, log, machine)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := r.deleteNodeForMachine(ctx, log, nodes, machine); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.metrics.Deprovisioning.Observe(time.Until(machine.DeletionTimestamp.Time).Abs().Seconds())\n\n\treturn nil, nil\n}", "func testWindowsNodeDeletion(t *testing.T) {\n\ttestCtx, err := NewTestContext()\n\trequire.NoError(t, err)\n\n\t// set expected node count to zero, since all Windows Nodes should be deleted in the test\n\texpectedNodeCount := int32(0)\n\t// Get all the Machines created by the e2e tests\n\t// For platform=none, the resulting slice is empty\n\te2eMachineSets, err := testCtx.client.Machine.MachineSets(clusterinfo.MachineAPINamespace).List(context.TODO(),\n\t\tmeta.ListOptions{LabelSelector: clusterinfo.MachineE2ELabel + \"=true\"})\n\trequire.NoError(t, err, \"error listing MachineSets\")\n\tvar windowsMachineSetWithLabel *mapi.MachineSet\n\tfor _, machineSet := range e2eMachineSets.Items {\n\t\tif machineSet.Spec.Selector.MatchLabels[clusterinfo.MachineOSIDLabel] == \"Windows\" {\n\t\t\twindowsMachineSetWithLabel = &machineSet\n\t\t\tbreak\n\t\t}\n\t}\n\t// skip the scale down step if there is no MachineSet with Windows label\n\tif windowsMachineSetWithLabel != nil {\n\t\t// Scale the Windows MachineSet to 0\n\t\twindowsMachineSetWithLabel.Spec.Replicas = &expectedNodeCount\n\t\t_, err = testCtx.client.Machine.MachineSets(clusterinfo.MachineAPINamespace).Update(context.TODO(),\n\t\t\twindowsMachineSetWithLabel, meta.UpdateOptions{})\n\t\trequire.NoError(t, err, \"error updating Windows MachineSet\")\n\n\t\t// we are waiting 10 minutes for all windows machines to get deleted.\n\t\terr = testCtx.waitForWindowsNodes(expectedNodeCount, true, false, false)\n\t\trequire.NoError(t, err, \"Windows node deletion failed\")\n\t}\n\tt.Run(\"BYOH node removal\", testCtx.testBYOHRemoval)\n\n\t// Cleanup all the MachineSets created by us.\n\tfor _, machineSet := range e2eMachineSets.Items {\n\t\tassert.NoError(t, testCtx.deleteMachineSet(&machineSet), \"error deleting MachineSet\")\n\t}\n\t// Phase is ignored during deletion, in this case we are just waiting for Machines to be deleted.\n\t_, err = testCtx.waitForWindowsMachines(int(expectedNodeCount), \"\", true)\n\trequire.NoError(t, err, \"Machine controller Windows machine deletion failed\")\n\n\t// TODO: Currently on vSphere it is impossible to delete a Machine after its node has been deleted.\n\t// This special casing should be removed as part of https://issues.redhat.com/browse/WINC-635\n\tif testCtx.GetType() != config.VSpherePlatformType {\n\t\t_, err = testCtx.waitForWindowsMachines(int(expectedNodeCount), \"\", false)\n\t\trequire.NoError(t, err, \"ConfigMap controller Windows machine deletion failed\")\n\t}\n\n\t// Test if prometheus configuration is updated to have no node entries in the endpoints object\n\tt.Run(\"Prometheus configuration\", testPrometheus)\n\n\t// Cleanup windows-instances ConfigMap\n\ttestCtx.deleteWindowsInstanceConfigMap()\n\n\t// Cleanup secrets created by us.\n\terr = testCtx.client.K8s.CoreV1().Secrets(\"openshift-machine-api\").Delete(context.TODO(), \"windows-user-data\", meta.DeleteOptions{})\n\trequire.NoError(t, err, \"could not delete userData secret\")\n\n\terr = testCtx.client.K8s.CoreV1().Secrets(\"openshift-windows-machine-config-operator\").Delete(context.TODO(), secrets.PrivateKeySecret, meta.DeleteOptions{})\n\trequire.NoError(t, err, \"could not delete privateKey secret\")\n\n\t// Cleanup wmco-test namespace created by us.\n\terr = testCtx.deleteNamespace(testCtx.workloadNamespace)\n\trequire.NoError(t, err, \"could not delete test namespace\")\n}", "func (c *Client) destroyContainer(ctx context.Context, id string, timeout int64) (*Message, error) {\n\t// TODO(ziren): if we just want to stop a container,\n\t// we may need lease to lock the snapshot of container,\n\t// in case, it be deleted by gc.\n\twrapperCli, err := c.Get(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get a containerd grpc client: %v\", err)\n\t}\n\n\tctx = leases.WithLease(ctx, wrapperCli.lease.ID)\n\n\tif !c.lock.TrylockWithRetry(ctx, id) {\n\t\treturn nil, errtypes.ErrLockfailed\n\t}\n\tdefer c.lock.Unlock(id)\n\n\tpack, err := c.watch.get(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if you call DestroyContainer to stop a container, will skip the hooks.\n\t// the caller need to execute the all hooks.\n\tpack.l.Lock()\n\tpack.skipStopHooks = true\n\tpack.l.Unlock()\n\tdefer func() {\n\t\tpack.l.Lock()\n\t\tpack.skipStopHooks = false\n\t\tpack.l.Unlock()\n\t}()\n\n\twaitExit := func() *Message {\n\t\treturn c.ProbeContainer(ctx, id, time.Duration(timeout)*time.Second)\n\t}\n\n\tvar msg *Message\n\n\t// TODO: set task request timeout by context timeout\n\tif err := pack.task.Kill(ctx, syscall.SIGTERM, containerd.WithKillAll); err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\treturn nil, errors.Wrap(err, \"failed to kill task\")\n\t\t}\n\t\tgoto clean\n\t}\n\t// wait for the task to exit.\n\tmsg = waitExit()\n\n\tif err := msg.RawError(); err != nil && errtypes.IsTimeout(err) {\n\t\t// timeout, use SIGKILL to retry.\n\t\tif err := pack.task.Kill(ctx, syscall.SIGKILL, containerd.WithKillAll); err != nil {\n\t\t\tif !errdefs.IsNotFound(err) {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to kill task\")\n\t\t\t}\n\t\t\tgoto clean\n\t\t}\n\t\tmsg = waitExit()\n\t}\n\n\t// ignore the error is stop time out\n\t// TODO: how to design the stop error is time out?\n\tif err := msg.RawError(); err != nil && !errtypes.IsTimeout(err) {\n\t\treturn nil, err\n\t}\n\nclean:\n\t// for normal destroy process, task.Delete() and container.Delete()\n\t// is done in ctrd/watch.go, after task exit. clean is task effect only\n\t// when unexcepted error happened in task exit process.\n\tif _, err := pack.task.Delete(ctx); err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\tlogrus.Errorf(\"failed to delete task %s again: %v\", pack.id, err)\n\t\t}\n\t}\n\tif err := pack.container.Delete(ctx); err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\treturn msg, errors.Wrap(err, \"failed to delete container\")\n\t\t}\n\t}\n\n\tlogrus.Infof(\"success to destroy container: %s\", id)\n\n\treturn msg, c.watch.remove(ctx, id)\n}", "func UntilVolumeCreated(t *testing.T) {\n\tnames := helpers.GetNames(\"UntilVolume\", 0, 1, 1, 2, 1, 0, 0, 0)\n\tnames.TearDown()\n\tdefer names.TearDown()\n\n\tout, err := helpers.GetOutput(\"safescale network list\")\n\trequire.Nil(t, err)\n\t_ = out\n\n\tfmt.Println(\"Creating network \" + names.Networks[0])\n\n\tout, err = helpers.GetOutput(\"safescale network create \" + names.Networks[0] + \" --cidr 192.168.47.0/24\")\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale network create \" + names.Networks[0] + \" --cidr 192.168.47.0/24\")\n\trequire.NotNil(t, err)\n\trequire.True(t, strings.Contains(out, \"already exist\"))\n\n\tfmt.Println(\"Creating VM \" + names.Hosts[0])\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[0] + \" --public --net \" + names.Networks[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[0] + \" --public --net \" + names.Networks[0])\n\trequire.NotNil(t, err)\n\trequire.True(t, strings.Contains(out, \"already exist\") || strings.Contains(out, \"already used\"))\n\n\tout, err = helpers.GetOutput(\"safescale host inspect \" + names.Hosts[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tfmt.Println(\"Creating VM \" + names.Hosts[1])\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[1] + \" --public --net \" + names.Networks[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[1] + \" --public --net \" + names.Networks[0])\n\trequire.NotNil(t, err)\n\trequire.True(t, strings.Contains(out, \"already exist\") || strings.Contains(out, \"already used\"))\n\n\tout, err = helpers.GetOutput(\"safescale volume list\")\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(out, \"null\"))\n\n\tfmt.Println(\"Creating Volume \" + names.Volumes[0])\n\n\tout, err = helpers.GetOutput(\"safescale volume create \" + names.Volumes[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale volume list\")\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(out, names.Volumes[0]))\n}", "func (cc *ClusterController) cleanup(c *cassandrav1alpha1.Cluster) error {\n\n\tfor _, r := range c.Spec.Datacenter.Racks {\n\t\tservices, err := cc.serviceLister.Services(c.Namespace).List(util.RackSelector(r, c))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error listing member services: %s\", err.Error())\n\t\t}\n\t\t// Get rack status. If it doesn't exist, the rack isn't yet created.\n\t\tstsName := util.StatefulSetNameForRack(r, c)\n\t\tsts, err := cc.statefulSetLister.StatefulSets(c.Namespace).Get(stsName)\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting statefulset %s: %s\", stsName, err.Error())\n\t\t}\n\t\tmemberCount := *sts.Spec.Replicas\n\t\tmemberServiceCount := int32(len(services))\n\t\t// If there are more services than members, some services need to be cleaned up\n\t\tif memberServiceCount > memberCount {\n\t\t\tmaxIndex := memberCount - 1\n\t\t\tfor _, svc := range services {\n\t\t\t\tsvcIndex, err := util.IndexFromName(svc.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(\"Unexpected error while parsing index from name %s : %s\", svc.Name, err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif svcIndex > maxIndex {\n\t\t\t\t\terr := cc.cleanupMemberResources(svc.Name, r, c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"error cleaning up member resources: %s\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"%s/%s - Successfully cleaned up cluster.\", c.Namespace, c.Name)\n\treturn nil\n}", "func (r *ReconcileCluster) isDeleteReady(ctx context.Context, cluster *v1alpha2.Cluster) error {\n\t// TODO(vincepri): List and delete MachineDeployments, MachineSets, Machines, and\n\t// block deletion until they're all deleted.\n\n\tif cluster.Spec.InfrastructureRef != nil {\n\t\t_, err := external.Get(r.Client, cluster.Spec.InfrastructureRef, cluster.Namespace)\n\t\tif err != nil && !apierrors.IsNotFound(err) {\n\t\t\treturn errors.Wrapf(err, \"failed to get %s %q for Cluster %q in namespace %q\",\n\t\t\t\tpath.Join(cluster.Spec.InfrastructureRef.APIVersion, cluster.Spec.InfrastructureRef.Kind),\n\t\t\t\tcluster.Spec.InfrastructureRef.Name, cluster.Name, cluster.Namespace)\n\t\t} else if err == nil {\n\t\t\treturn &capierrors.RequeueAfterError{RequeueAfter: 10 * time.Second}\n\t\t}\n\t}\n\n\treturn nil\n}", "func cleanupLoop(maxAgeSeconds float64) {\n\tfor {\n\t\ttime.Sleep(60 * time.Second)\n\t\tt := time.Now()\n\t\tfor project, creationTime := range dataTimestamp {\n\t\t\tmutex.Lock()\n\t\t\tif t.Sub(creationTime).Seconds() >= maxAgeSeconds {\n\t\t\t\tdelete(projectStatus, project)\n\t\t\t\tdelete(dataTimestamp, project)\n\t\t\t}\n\t\t\tmutex.Unlock()\n\t\t}\n\t}\n}", "func (a *MemberAwaitility) WaitUntilNSTemplateSetDeleted(name string) error {\n\treturn wait.Poll(a.RetryInterval, a.Timeout, func() (done bool, err error) {\n\t\tnsTmplSet := &toolchainv1alpha1.NSTemplateSet{}\n\t\tif err := a.Client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: a.Namespace}, nsTmplSet); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\ta.T.Logf(\"deleted NSTemplateSet '%s'\", name)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\ta.T.Logf(\"waiting for deletion of NSTemplateSet '%s'\", name)\n\t\treturn false, nil\n\t})\n}", "func PoolDestroy(name string) error {\n\tcmd := &Cmd{}\n\treturn NvlistIoctl(zfsHandle.Fd(), ZFS_IOC_POOL_DESTROY, name, cmd, nil, nil, nil)\n}", "func (p libvirtPlugin) Destroy(id instance.ID) error {\n\tl := log.WithField(\"instance\", id)\n\tl.Info(\"Destroying VM\")\n\n\tconn, err := libvirt.NewConnect(p.URI)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Connecting to libvirt\")\n\t}\n\tdefer conn.Close()\n\n\td, err := p.lookupInstanceByID(conn, id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Looking up domain\")\n\t}\n\n\tif err := destroyMetadataDisk(conn, d); err != nil {\n\t\tl.Errorf(\"Failed to destroy metadata disk: %s\", err)\n\t\t// Continue so we at least try and destroy the domain\n\t}\n\n\tif err := d.Destroy(); err != nil {\n\t\treturn errors.Wrap(err, \"Destroying domain\")\n\t}\n\n\treturn nil\n}", "func (w *watcher) cleanupWorker() {\n\tfor {\n\t\t// Wait a full period\n\t\ttime.Sleep(w.cleanupTimeout)\n\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.stopped.Done()\n\t\t\treturn\n\t\tdefault:\n\t\t\t// Check entries for timeout\n\t\t\tvar toDelete []string\n\t\t\ttimeout := time.Now().Add(-w.cleanupTimeout)\n\t\t\tw.RLock()\n\t\t\tfor key, lastSeen := range w.deleted {\n\t\t\t\tif lastSeen.Before(timeout) {\n\t\t\t\t\tlogp.Debug(\"docker\", \"Removing container %s after cool down timeout\", key)\n\t\t\t\t\ttoDelete = append(toDelete, key)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.RUnlock()\n\n\t\t\t// Delete timed out entries:\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tcontainer := w.Container(key)\n\t\t\t\tif container != nil {\n\t\t\t\t\tw.bus.Publish(bus.Event{\n\t\t\t\t\t\t\"delete\": true,\n\t\t\t\t\t\t\"container\": container,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tw.Lock()\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tdelete(w.deleted, key)\n\t\t\t\tdelete(w.containers, key)\n\t\t\t\tif w.shortID {\n\t\t\t\t\tdelete(w.containers, key[:shortIDLen])\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.Unlock()\n\t\t}\n\t}\n}", "func (s *LocalTests) deleteMachine(c *gc.C, machineId string) {\n\terr := s.testClient.StopMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n\n\t// wait for machine to be stopped\n\tfor !s.pollMachineState(c, machineId, \"stopped\") {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\terr = s.testClient.DeleteMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n}", "func destroyKnative() {\n\n\t//Make command options for Knative Setup\n\tco := utils.NewCommandOptions()\n\n\t//Install Openshift Serveless and Knative Serving\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-eventing.yaml\")\n\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-serving.yaml\")\n\tIOStreams, _, out, _ := genericclioptions.NewTestIOStreams()\n\n\tco.SwitchContext(\"knative-eventing\")\n\n\tlog.Info(\"Remove Openshift Serverless Operator and Knative Serving\")\n\tfor commandNumber, command := range co.Commands {\n\t\tif commandNumber == 1 {\n\t\t\tco.SwitchContext(\"knative-serving\")\n\t\t}\n\t\tcmd := delete.NewCmdDelete(co.CurrentFactory, IOStreams)\n\t\tcmd.Flags().Set(\"filename\", command)\n\t\tcmd.Run(cmd, []string{})\n\t\tlog.Info(out.String())\n\t\tout.Reset()\n\t\t//Allow time for Operator to distribute to all namespaces\n\t}\n\n\t/*\n\n\t\tcurrentCSV, err := exec.Command(\"bash\", \"-c\", \"./oc get subscription serverless-operator -n openshift-operators -o jsonpath='{.status.currentCSV}'\").Output()\n\t\terr = exec.Command(\"./oc\", \"delete\", \"subscription\", \"serverless-operator\", \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Ignore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\terr = exec.Command(\"./oc\", \"delete\", \"clusterserviceversion\", string(currentCSV), \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Igonore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\tos.Remove(\"oc\")\n\t*/\n\n}", "func deleteOrphanedAutoCreatedKAMs(resController *ClusterWatcher) error {\n\tif logger.IsEnabled(LogTypeEntry) {\n\t\tlogger.Log(CallerName(), LogTypeEntry, \"Delete orphaned auto-created KAMs\")\n\t}\n\n\tgvr, ok := resController.getWatchGVR(kindActionMappingGVR)\n\tif !ok {\n\t\terr := fmt.Errorf(\"Unable to get GVR for KAM\")\n\t\tif logger.IsEnabled(LogTypeError) {\n\t\t\tlogger.Log(CallerName(), LogTypeError, fmt.Sprintf(\"Error in deleteOrphanedAutoCreatedKAMs: %s\", err))\n\t\t}\n\t\treturn err\n\t}\n\tvar intf = resController.plugin.dynamicClient.Resource(gvr)\n\n\t// fetch the current resource\n\tvar unstructuredList *unstructured.UnstructuredList\n\tvar err error\n\tunstructuredList, err = intf.List(metav1.ListOptions{LabelSelector: \"kappnav.kam.auto-created=true\"})\n\tif err != nil {\n\t\t// TODO: check error code. Most likely resource does not exist\n\t\treturn err\n\t}\n\n\tfor _, unstructuredObj := range unstructuredList.Items {\n\t\tvar kamResInfo = &resourceInfo{}\n\t\tresController.parseResource(&unstructuredObj, kamResInfo)\n\t\tif logger.IsEnabled(LogTypeDebug) {\n\t\t\tlogger.Log(CallerName(), LogTypeDebug,\n\t\t\t\tfmt.Sprintf(\"DeleteOrphanedAutoCreatedKAMs kam: %s\", kamResInfo.name))\n\t\t}\n\n\t\tif autoCreateKAMMap != nil {\n\t\t\tmaps := autoCreateKAMMap[kamResInfo.namespace]\n\t\t\texists, _ := maps[kamResInfo.name]\n\n\t\t\t// delete auto-create kam if no resource exists in the map\n\t\t\tif exists != kamTrue {\n\t\t\t\tif logger.IsEnabled(LogTypeDebug) {\n\t\t\t\t\tlogger.Log(CallerName(), LogTypeDebug,\n\t\t\t\t\t\tfmt.Sprintf(\"Deleting the auto-created KAM: %s/%s\", kamResInfo.namespace, kamResInfo.name))\n\t\t\t\t}\n\t\t\t\terr := deleteResource(resController, kamResInfo)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif logger.IsEnabled(LogTypeError) {\n\t\t\t\t\t\tlogger.Log(CallerName(), LogTypeError,\n\t\t\t\t\t\t\tfmt.Sprintf(\"Error deleting orphaned kam: %s/%s. Error: %s\", kamResInfo.namespace, kamResInfo.name, err))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif logger.IsEnabled(LogTypeInfo) {\n\t\t\t\t\t\tlogger.Log(CallerName(), LogTypeInfo,\n\t\t\t\t\t\t\tfmt.Sprintf(\"Deleted orphaned auto-created kam %s/%s\", kamResInfo.namespace, kamResInfo.name))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif logger.IsEnabled(LogTypeExit) {\n\t\tlogger.Log(CallerName(), LogTypeExit, \"Delete orphaned auto-created KAMs\")\n\t}\n\treturn nil\n}", "func (c *bdCommon) destroy(ctx context.Context, stack *thrapb.Stack) []*thrapb.ActionResult {\n\tar := make([]*thrapb.ActionResult, 0, len(stack.Components))\n\n\tfor _, comp := range stack.Components {\n\t\tr := &thrapb.ActionResult{\n\t\t\tAction: \"destroy\",\n\t\t\tResource: comp.ID,\n\t\t\tError: c.crt.Remove(ctx, comp.ID+\".\"+stack.ID),\n\t\t}\n\t\tar = append(ar, r)\n\t}\n\n\treturn ar\n}", "func Cleanup() {\n\tif _, err := _etcdClient.Delete(context.Background(), \"\", clientv3.WithPrefix()); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func assertCleanup(ns string, selectors ...string) {\n\tvar e error\n\tverifyCleanupFunc := func() (bool, error) {\n\t\te = nil\n\t\tfor _, selector := range selectors {\n\t\t\tresources := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"rc,svc\", \"-l\", selector, \"--no-headers\")\n\t\t\tif resources != \"\" {\n\t\t\t\te = fmt.Errorf(\"Resources left running after stop:\\n%s\", resources)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tpods := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", \"-l\", selector, \"-o\", \"go-template={{ range .items }}{{ if not .metadata.deletionTimestamp }}{{ .metadata.name }}{{ \\\"\\\\n\\\" }}{{ end }}{{ end }}\")\n\t\t\tif pods != \"\" {\n\t\t\t\te = fmt.Errorf(\"Pods left unterminated after stop:\\n%s\", pods)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}\n\terr := wait.PollImmediate(500*time.Millisecond, 1*time.Minute, verifyCleanupFunc)\n\tif err != nil {\n\t\tframework.Failf(e.Error())\n\t}\n}", "func (c *LoadAgentCluster) Shutdown() {\n\tvar wg sync.WaitGroup\n\twg.Add(len(c.agents))\n\tfor _, ag := range c.agents {\n\t\tgo func(ag *client.Agent) {\n\t\t\tdefer wg.Done()\n\t\t\tif _, err := ag.Destroy(); err != nil {\n\t\t\t\tc.log.Error(\"cluster: failed to stop agent\", mlog.Err(err))\n\t\t\t}\n\t\t}(ag)\n\t}\n\twg.Wait()\n}", "func (s *Cloudformation) WaitUntilStackDeleted() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.StackName()),\n\t}\n\n\terr = svc.WaitUntilStackDeleteComplete(&stackInputs)\n\treturn\n}", "func removeRBDLocks(instance *ec2.Instance) {\n\taddress, found := hosts[instance.InstanceId]\n\tif !found {\n\t\tglog.Errorf(\"The instance: %s was not found in the hosts map\", instance.InstanceId)\n\t\treturn\n\t}\n\tglog.Infof(\"Instance: %s, address: %s, state: %s, checking for locks\", instance.InstanceId, address, instance.State.Name)\n\n\tvar deleted = false\n\n\tfor i := 0; i < 3; i++ {\n\t\terr := rbdClient.UnlockClient(address)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to unlock the images, attempting again if possible\")\n\t\t\t<-time.After(time.Duration(5) * time.Second)\n\t\t}\n\t\tdeleted = true\n\t}\n\n\tif !deleted {\n\t\tglog.Errorf(\"Failed to unlock any images that could have been held by client: %s\", address)\n\t}\n\n\t// step: delete from the hosts map\n\tdelete(hosts, instance.InstanceId)\n}", "func TestKillRandom(t *testing.T) {\n\tprocAttr := new(os.ProcAttr)\n\tprocAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}\n\n\tclusterSize := 9\n\targGroup, etcds, err := createCluster(clusterSize, procAttr, false)\n\n\tif err != nil {\n\t\tt.Fatal(\"cannot create cluster\")\n\t}\n\n\tdefer destroyCluster(etcds)\n\n\tleaderChan := make(chan string, 1)\n\n\ttime.Sleep(3 * time.Second)\n\n\tgo leaderMonitor(clusterSize, 4, leaderChan)\n\n\ttoKill := make(map[int]bool)\n\n\tfor i := 0; i < 20; i++ {\n\t\tfmt.Printf(\"TestKillRandom Round[%d/20]\\n\", i)\n\n\t\tj := 0\n\t\tfor {\n\n\t\t\tr := rand.Int31n(9)\n\t\t\tif _, ok := toKill[int(r)]; !ok {\n\t\t\t\tj++\n\t\t\t\ttoKill[int(r)] = true\n\t\t\t}\n\n\t\t\tif j > 3 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\n\t\tfor num, _ := range toKill {\n\t\t\tetcds[num].Kill()\n\t\t\tetcds[num].Release()\n\t\t}\n\n\t\t<-leaderChan\n\n\t\tfor num, _ := range toKill {\n\t\t\tetcds[num], err = os.StartProcess(\"etcd\", argGroup[num], procAttr)\n\t\t}\n\n\t\ttoKill = make(map[int]bool)\n\t}\n\n\t<-leaderChan\n\n}", "func (b *Botanist) WaitUntilContainerRuntimeResourcesDeleted(ctx context.Context) error {\n\tvar (\n\t\tlastError *gardencorev1beta1.LastError\n\t\tcontainerRuntimes = &extensionsv1alpha1.ContainerRuntimeList{}\n\t)\n\n\tif err := b.K8sSeedClient.Client().List(ctx, containerRuntimes, client.InNamespace(b.Shoot.SeedNamespace)); err != nil {\n\t\treturn err\n\t}\n\n\tfns := make([]flow.TaskFn, 0, len(containerRuntimes.Items))\n\tfor _, containerRuntime := range containerRuntimes.Items {\n\t\tif containerRuntime.GetDeletionTimestamp() == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar (\n\t\t\tname = containerRuntime.Name\n\t\t\tnamespace = containerRuntime.Namespace\n\t\t)\n\n\t\tfns = append(fns, func(ctx context.Context) error {\n\t\t\tif err := retry.UntilTimeout(ctx, DefaultInterval, shoot.ExtensionDefaultTimeout, func(ctx context.Context) (bool, error) {\n\t\t\t\tretrievedContainerRuntime := extensionsv1alpha1.ContainerRuntime{}\n\t\t\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(namespace, name), &retrievedContainerRuntime); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\treturn retry.Ok()\n\t\t\t\t\t}\n\t\t\t\t\treturn retry.SevereError(err)\n\t\t\t\t}\n\n\t\t\t\tif lastErr := retrievedContainerRuntime.Status.LastError; lastErr != nil {\n\t\t\t\t\tb.Logger.Errorf(\"Container runtime %s did not get deleted yet, lastError is: %s\", name, lastErr.Description)\n\t\t\t\t\tlastError = lastErr\n\t\t\t\t}\n\n\t\t\t\treturn retry.MinorError(gardencorev1beta1helper.WrapWithLastError(fmt.Errorf(\"container runtime %s is still present\", name), lastError))\n\t\t\t}); err != nil {\n\t\t\t\tmessage := \"Failed waiting for container runtime delete\"\n\t\t\t\tif lastError != nil {\n\t\t\t\t\treturn gardencorev1beta1helper.DetermineError(errors.New(lastError.Description), fmt.Sprintf(\"%s: %s\", message, lastError.Description))\n\t\t\t\t}\n\t\t\t\treturn gardencorev1beta1helper.DetermineError(err, fmt.Sprintf(\"%s: %s\", message, err.Error()))\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn flow.Parallel(fns...)(ctx)\n}", "func (b *Botanist) WaitUntilNodesDeleted(ctx context.Context) error {\n\treturn retry.Until(ctx, 5*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tnodesList := &corev1.NodeList{}\n\t\tif err := b.K8sShootClient.Client().List(ctx, nodesList); err != nil {\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\n\t\tif len(nodesList.Items) == 0 {\n\t\t\treturn retry.Ok()\n\t\t}\n\n\t\tb.Logger.Infof(\"Waiting until all nodes have been deleted in the shoot cluster...\")\n\t\treturn retry.MinorError(fmt.Errorf(\"not all nodes have been deleted in the shoot cluster\"))\n\t})\n}", "func TestAllocRunner_TerminalUpdate_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\t// Ensure task takes some time\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Driver = \"mock_driver\"\n\ttask.Config[\"run_for\"] = \"10s\"\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusRunning {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusRunning)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Update the alloc to be terminal which should cause the alloc runner to\n\t// stop the tasks and wait for a destroy.\n\tupdate := ar.alloc.Copy()\n\tupdate.DesiredStatus = structs.AllocDesiredStatusStop\n\tar.Update(update)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory still exists\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err != nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir destroyed: %v\", ar.allocDir.AllocDir)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Send the destroy signal and ensure the AllocRunner cleans up.\n\tar.Destroy()\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory was cleaned\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn false, fmt.Errorf(\"stat err: %v\", err)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n}", "func KillWorkloads(clientset kubernetes.Interface) {\n\t// Look for namespace or default to default namespace\n\tnamespace := helpers.GetEnv(\"NAMESPACE\", \"default\")\n\t// Wait Group To handle the waiting for all deletes to complete\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\t// Delete all Deployments\n\tif helpers.CheckDeleteResourceAllowed(\"deployments\") {\n\t\tgo deleteDeployments(clientset, &namespace, &wg)\n\t}\n\t// Delete all Statefulsets\n\tif helpers.CheckDeleteResourceAllowed(\"statefulsets\") {\n\t\tgo deleteStatefulsets(clientset, &namespace, &wg)\n\t}\n\t// Delete Services\n\tif helpers.CheckDeleteResourceAllowed(\"services\") {\n\t\tgo deleteServices(clientset, &namespace, &wg)\n\t}\n\t// Delete All Secrets\n\tif helpers.CheckDeleteResourceAllowed(\"secrets\") {\n\t\tgo deleteSecrets(clientset, &namespace, &wg)\n\t}\n\t// Delete All Configmaps\n\tif helpers.CheckDeleteResourceAllowed(\"configmaps\") {\n\t\tgo deleteConfigMaps(clientset, &namespace, &wg)\n\t}\n\t// wait for processes to finish\n\twg.Wait()\n}", "func (s *service) waitForExit(cmd *exec.Cmd) {\n\tif err := cmd.Wait(); err != nil {\n\t\tlogrus.Debugf(\"Envoy terminated: %v\", err.Error())\n\t} else {\n\t\tlogrus.Debug(\"Envoy process exited\")\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tdelete(s.cmdMap, cmd)\n}", "func (a Apps) Destroy() error {\n\tfor _, app := range a {\n\t\tcmd, err := app.Destroy(false)\n\t\tif err != nil {\n\t\t\tapp.log.WithFields(logrus.Fields{\n\t\t\t\t\"app\": app.Name,\n\t\t\t\t\"cmd\": cmd,\n\t\t\t\t\"error\": err,\n\t\t\t}).Fatal(\"Failed running destroy\")\n\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *Environment) Destroy() error {\n\t// We set it to stopping than offline to prevent crash detection from being triggered.\n\te.SetState(environment.ProcessStoppingState)\n\n\terr := e.client.ContainerRemove(context.Background(), e.Id, types.ContainerRemoveOptions{\n\t\tRemoveVolumes: true,\n\t\tRemoveLinks: false,\n\t\tForce: true,\n\t})\n\n\te.SetState(environment.ProcessOfflineState)\n\n\t// Don't trigger a destroy failure if we try to delete a container that does not\n\t// exist on the system. We're just a step ahead of ourselves in that case.\n\t//\n\t// @see https://github.com/pterodactyl/panel/issues/2001\n\tif err != nil && client.IsErrNotFound(err) {\n\t\treturn nil\n\t}\n\n\treturn err\n}", "func deletePodAndWaitForVolsToDetach(ctx context.Context, client clientset.Interface, namespace string, pod *v1.Pod) {\n\tginkgo.By(fmt.Sprintf(\"Deleting pod: %s\", pod.Name))\n\tvolhandles := []string{}\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tpv := getPvFromClaim(client, namespace, vol.PersistentVolumeClaim.ClaimName)\n\t\tvolhandles = append(volhandles, pv.Spec.CSI.VolumeHandle)\n\n\t}\n\terr := fpod.DeletePodWithWait(client, pod)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tfor _, volHandle := range volhandles {\n\t\tginkgo.By(\"Verify volume is detached from the node\")\n\t\tisDiskDetached, err := e2eVSphere.waitForVolumeDetachedFromNode(client, volHandle, pod.Spec.NodeName)\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tgomega.Expect(isDiskDetached).To(gomega.BeTrue(), fmt.Sprintf(\"Volume %q is not detached from the node %q\", volHandle, pod.Spec.NodeName))\n\t}\n}", "func Test_Static_Pool_Slow_Destroy(t *testing.T) {\n\tp, err := Initialize(\n\t\tcontext.Background(),\n\t\tfunc() *exec.Cmd { return exec.Command(\"php\", \"../tests/slow-destroy.php\", \"echo\", \"pipes\") },\n\t\tpipe.NewPipeFactory(),\n\t\t&Config{\n\t\t\tNumWorkers: 5,\n\t\t\tAllocateTimeout: time.Second,\n\t\t\tDestroyTimeout: time.Second,\n\t\t},\n\t)\n\n\tassert.NoError(t, err)\n\tassert.NotNil(t, p)\n\n\tp.Destroy(context.Background())\n}" ]
[ "0.65745693", "0.62703717", "0.62244946", "0.6161704", "0.60007936", "0.59899086", "0.57228744", "0.57008475", "0.567827", "0.56474024", "0.5596537", "0.55710554", "0.5490832", "0.5463808", "0.5462064", "0.5462064", "0.5438312", "0.5418636", "0.54070365", "0.5403932", "0.53660274", "0.5349717", "0.5330852", "0.52951485", "0.5268077", "0.5267356", "0.52608323", "0.52602494", "0.52596587", "0.5246797", "0.5245758", "0.52388424", "0.5238593", "0.52378666", "0.52375025", "0.52365243", "0.5235231", "0.5217944", "0.5201435", "0.5176623", "0.5174985", "0.5168728", "0.51634073", "0.51619345", "0.51534975", "0.514595", "0.5126944", "0.5126774", "0.51092106", "0.5108924", "0.51043725", "0.5098054", "0.5091963", "0.5091717", "0.50839376", "0.5076857", "0.50457245", "0.50307846", "0.50292486", "0.5022505", "0.50106514", "0.5006638", "0.500452", "0.49972105", "0.49946114", "0.4990956", "0.49888918", "0.49854335", "0.49813792", "0.4976736", "0.49762982", "0.49635243", "0.49612102", "0.49581292", "0.49545822", "0.49526906", "0.49492246", "0.49464327", "0.49442768", "0.49439073", "0.4938832", "0.492988", "0.49234495", "0.49226913", "0.49153486", "0.49127087", "0.49073142", "0.49012437", "0.4900286", "0.4894278", "0.48911053", "0.4887985", "0.48852283", "0.4880859", "0.48760846", "0.48754144", "0.48735985", "0.48731175", "0.48727545", "0.48610416" ]
0.7794994
0
waitForMachineController waits for machinecontroller to become running
waitForMachineController ожидает, пока machinecontroller станет запущенным
func waitForMachineController(ctx context.Context, client dynclient.Client) error { condFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{ Namespace: resources.MachineControllerNameSpace, LabelSelector: labels.SelectorFromSet(map[string]string{ appLabelKey: resources.MachineControllerName, }), }) return fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), "waiting for machine-controller to became ready") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func waitForMachineState(api *cloudapi.Client, id, state string, timeout time.Duration) error {\n\treturn waitFor(\n\t\tfunc() (bool, error) {\n\t\t\tcurrentState, err := readMachineState(api, id)\n\t\t\treturn currentState == state, err\n\t\t},\n\t\tmachineStateChangeCheckInterval,\n\t\tmachineStateChangeTimeout,\n\t)\n}", "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func waitForWebhook(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerWebhookName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller webhook to became ready\")\n}", "func WaitReady(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\ts.Logger.Infoln(\"Waiting for machine-controller to come up...\")\n\n\tif err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForWebhook(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForMachineController(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\treturn waitForCRDs(s)\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func TestWaitUntilRunning(t *testing.T) {\n\tts := memorytopo.NewServer(\"cell1\")\n\tm := NewManager(ts)\n\n\t// Start it 3 times i.e. restart it 2 times.\n\tfor i := 1; i <= 3; i++ {\n\t\t// Run the manager in the background.\n\t\twg, _, cancel := StartManager(m)\n\n\t\t// Shut it down and wait for the shutdown to complete.\n\t\tcancel()\n\t\twg.Wait()\n\t}\n}", "func CheckMachine(machine string) error {\n\tbars := make([]*pb.ProgressBar, 0)\n\tvar wg sync.WaitGroup\n\tvar path = getPath()\n\tvar machinePath = filepath.Join(path, machine, machine+\".vbox\")\n\n\tfmt.Println(\"[+] Checking virtual machine\")\n\t// checking file location\n\tif !fileExists(machinePath) {\n\t\trepository, err := repo.NewRepositoryVM()\n\n\t\t// checking local repository\n\t\tif repository.GetURL() == \"\" {\n\t\t\treturn errors.New(\"URL is not set for downloading VBox image\")\n\t\t}\n\n\t\tdst := filepath.Join(repository.Dir(), repository.GetVersion())\n\t\tfileName := repository.Name()\n\n\t\t// download virtual machine\n\t\tif !fileExists(filepath.Join(dst, fileName)) {\n\t\t\tfmt.Println(\"[+] Starting virtual machine download\")\n\t\t\tvar bar1 *pb.ProgressBar\n\t\t\tvar err error\n\n\t\t\tfileName, bar1, err = repo.DownloadAsync(repository, &wg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbar1.Prefix(fmt.Sprintf(\"[+] Download %-15s\", fileName))\n\t\t\tif bar1.Total > 0 {\n\t\t\t\tbars = append(bars, bar1)\n\t\t\t}\n\t\t\tpool, err := pb.StartPool(bars...)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\twg.Wait()\n\t\t\tpool.Stop()\n\n\t\t\ttime.Sleep(time.Second * 2)\n\t\t}\n\n\t\t// unzip virtual machine\n\t\terr = help.Unzip(filepath.Join(dst, fileName), path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\tif !isActive(machinePath) {\n\t\tfmt.Printf(\"[+] Registering %s\\n\", machine)\n\t\t_, err := help.ExecCmd(\"VBoxManage\",\n\t\t\t[]string{\n\t\t\t\t\"registervm\",\n\t\t\t\tfmt.Sprintf(\"%s\", machinePath),\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"[+] Done\")\n\t}\n\treturn nil\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func waitForCRDs(s *state.State) error {\n\tcondFn := clientutil.CRDsReadyCondition(s.Context, s.DynamicClient, CRDNames())\n\terr := wait.PollUntilContextTimeout(s.Context, 5*time.Second, 3*time.Minute, false, condFn.WithContext())\n\n\treturn fail.KubeClient(err, \"waiting for machine-controller CRDs to became ready\")\n}", "func (c *EC2) WaitUntilSystemStatusOk(input *DescribeInstanceStatusInput) error {\n\treturn c.WaitUntilSystemStatusOkWithContext(aws.BackgroundContext(), input)\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 (rcc *rotateCertsCmd) waitForControlPlaneReadiness() error {\n\tlog.Info(\"Checking health of control plane components\")\n\tpods := make([]string, 0)\n\tfor _, n := range rcc.cs.Properties.GetMasterVMNameList() {\n\t\tfor _, c := range []string{kubeAddonManager, kubeAPIServer, kubeControllerManager, kubeScheduler} {\n\t\t\tpods = append(pods, fmt.Sprintf(\"%s-%s\", c, n))\n\t\t}\n\t}\n\tif err := ops.WaitForReady(rcc.kubeClient, metav1.NamespaceSystem, pods, rotateCertsDefaultInterval, rotateCertsDefaultTimeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for control plane containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func (s *LocalTests) createMachine(c *gc.C) *cloudapi.Machine {\n\tmachine, err := s.testClient.CreateMachine(cloudapi.CreateMachineOpts{Package: localPackageName, Image: localImageID})\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(machine, gc.NotNil)\n\n\t// wait for machine to be provisioned\n\tfor !s.pollMachineState(c, machine.Id, \"running\") {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\treturn machine\n}", "func AddMachineControllerToManager(ctx *context.ControllerManagerContext, mgr manager.Manager) error {\n\n\tvar (\n\t\tcontrolledType = &infrav1.VSphereMachine{}\n\t\tcontrolledTypeName = reflect.TypeOf(controlledType).Elem().Name()\n\t\tcontrolledTypeGVK = infrav1.GroupVersion.WithKind(controlledTypeName)\n\n\t\tcontrollerNameShort = fmt.Sprintf(\"%s-controller\", strings.ToLower(controlledTypeName))\n\t\tcontrollerNameLong = fmt.Sprintf(\"%s/%s/%s\", ctx.Namespace, ctx.Name, controllerNameShort)\n\t)\n\n\t// Build the controller context.\n\tcontrollerContext := &context.ControllerContext{\n\t\tControllerManagerContext: ctx,\n\t\tName: controllerNameShort,\n\t\tRecorder: record.New(mgr.GetEventRecorderFor(controllerNameLong)),\n\t\tLogger: ctx.Logger.WithName(controllerNameShort),\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\t// Watch the controlled, infrastructure resource.\n\t\tFor(controlledType).\n\t\t// Watch any VSphereVM resources owned by the controlled type.\n\t\tWatches(\n\t\t\t&source.Kind{Type: &infrav1.VSphereVM{}},\n\t\t\t&handler.EnqueueRequestForOwner{OwnerType: controlledType, IsController: false},\n\t\t).\n\t\t// Watch the CAPI resource that owns this infrastructure resource.\n\t\tWatches(\n\t\t\t&source.Kind{Type: &clusterv1.Machine{}},\n\t\t\t&handler.EnqueueRequestsFromMapFunc{\n\t\t\t\tToRequests: clusterutilv1.MachineToInfrastructureMapFunc(controlledTypeGVK),\n\t\t\t},\n\t\t).\n\t\t// Watch a GenericEvent channel for the controlled resource.\n\t\t//\n\t\t// This is useful when there are events outside of Kubernetes that\n\t\t// should cause a resource to be synchronized, such as a goroutine\n\t\t// waiting on some asynchronous, external task to complete.\n\t\tWatches(\n\t\t\t&source.Channel{Source: ctx.GetGenericEventChannelFor(controlledTypeGVK)},\n\t\t\t&handler.EnqueueRequestForObject{},\n\t\t).\n\t\tComplete(machineReconciler{ControllerContext: controllerContext})\n}", "func waitForHelmRunning(ctx context.Context, configPath string) error {\n\tfor {\n\t\tcmd := exec.Command(\"helm\", \"ls\", \"--kubeconfig\", configPath)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stderr = &out\n\t\tcmd.Run()\n\t\tif out.String() == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.Wrap(ctx.Err(), \"timed out waiting for helm to become ready\")\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t}\n}", "func AddMachineControllerToManager(ctx *context.ControllerManagerContext, mgr manager.Manager) error {\n\n\tvar (\n\t\tcontrolledType = &infrav1.VSphereMachine{}\n\t\tcontrolledTypeName = reflect.TypeOf(controlledType).Elem().Name()\n\t\tcontrolledTypeGVK = infrav1.GroupVersion.WithKind(controlledTypeName)\n\n\t\tcontrollerNameShort = fmt.Sprintf(\"%s-controller\", strings.ToLower(controlledTypeName))\n\t\tcontrollerNameLong = fmt.Sprintf(\"%s/%s/%s\", ctx.Namespace, ctx.Name, controllerNameShort)\n\t)\n\n\t// Build the controller context.\n\tcontrollerContext := &context.ControllerContext{\n\t\tControllerManagerContext: ctx,\n\t\tName: controllerNameShort,\n\t\tRecorder: record.New(mgr.GetEventRecorderFor(controllerNameLong)),\n\t\tLogger: ctx.Logger.WithName(controllerNameShort),\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\t// Watch the controlled, infrastructure resource.\n\t\tFor(controlledType).\n\t\t// Watch the CAPI resource that owns this infrastructure resource.\n\t\tWatches(\n\t\t\t&source.Kind{Type: &clusterv1.Machine{}},\n\t\t\t&handler.EnqueueRequestsFromMapFunc{\n\t\t\t\tToRequests: clusterutilv1.MachineToInfrastructureMapFunc(controlledTypeGVK),\n\t\t\t},\n\t\t).\n\t\t// Watch a GenericEvent channel for the controlled resource.\n\t\t//\n\t\t// This is useful when there are events outside of Kubernetes that\n\t\t// should cause a resource to be synchronized, such as a goroutine\n\t\t// waiting on some asynchronous, external task to complete.\n\t\tWatches(\n\t\t\t&source.Channel{Source: ctx.GetGenericEventChannelFor(controlledTypeGVK)},\n\t\t\t&handler.EnqueueRequestForObject{},\n\t\t).\n\t\tComplete(machineReconciler{ControllerContext: controllerContext})\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.Queue.ShutDown()\n\tlog.Debug(\"pgcluster Contoller: received stop signal, worker queue told to shutdown\")\n}", "func Wait(dev *model.Dev, okStatusList []config.UpState) error {\n\toktetoLog.Spinner(\"Activating your development container...\")\n\toktetoLog.StartSpinner()\n\tdefer oktetoLog.StopSpinner()\n\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\texit := make(chan error, 1)\n\n\tgo func() {\n\n\t\tticker := time.NewTicker(500 * time.Millisecond)\n\t\tfor {\n\t\t\tstatus, err := config.GetState(dev.Name, dev.Namespace)\n\t\t\tif err != nil {\n\t\t\t\texit <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif status == config.Failed {\n\t\t\t\texit <- fmt.Errorf(\"your development container has failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, okStatus := range okStatusList {\n\t\t\t\tif status == okStatus {\n\t\t\t\t\texit <- nil\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\toktetoLog.Infof(\"CTRL+C received, starting shutdown sequence\")\n\t\toktetoLog.StopSpinner()\n\t\treturn oktetoErrors.ErrIntSig\n\tcase err := <-exit:\n\t\tif err != nil {\n\t\t\toktetoLog.Infof(\"exit signal received due to error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.workqueue.ShutDown()\n\tlog.Debug(\"Namespace Contoller: received stop signal, worker queue told to shutdown\")\n}", "func (r *volumeReactor) waitForIdle() {\n\tr.ctrl.runningOperations.WaitForCompletion()\n\t// Check every 10ms if the controller does something and stop if it's\n\t// idle.\n\toldChanges := -1\n\tfor {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\tchanges := r.GetChangeCount()\n\t\tif changes == oldChanges {\n\t\t\t// No changes for last 10ms -> controller must be idle.\n\t\t\tbreak\n\t\t}\n\t\toldChanges = changes\n\t}\n}", "func (r *volumeReactor) waitForIdle() {\n\tr.ctrl.runningOperations.WaitForCompletion()\n\t// Check every 10ms if the controller does something and stop if it's\n\t// idle.\n\toldChanges := -1\n\tfor {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\tchanges := r.getChangeCount()\n\t\tif changes == oldChanges {\n\t\t\t// No changes for last 10ms -> controller must be idle.\n\t\t\tbreak\n\t\t}\n\t\toldChanges = changes\n\t}\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (k *kubelet) waitForNodeReady() error {\n\tkc, _ := k.config.AdminConfig.ToYAMLString() //nolint:errcheck // This is checked in Validate().\n\n\tc, err := client.NewClient([]byte(kc))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating kubernetes client: %w\", err)\n\t}\n\n\treturn c.WaitForNodeReady(k.config.Name)\n}", "func (f *TestFramework) getWindowsMachines(vmCount int, skipVMSetup bool) ([]mapi.Machine, error) {\n\tlog.Print(\"Waiting for Machines...\")\n\twindowsOSLabel := \"machine.openshift.io/os-id\"\n\tvar provisionedMachines []mapi.Machine\n\t// it takes approximately 12 minutes in the CI for all the machines to appear.\n\ttimeOut := 12 * time.Minute\n\tif skipVMSetup {\n\t\ttimeOut = 1 * time.Minute\n\t}\n\tstartTime := time.Now()\n\tfor i := 0; time.Since(startTime) <= timeOut; i++ {\n\t\tallMachines := &mapi.MachineList{}\n\t\tallMachines, err := f.machineClient.Machines(\"openshift-machine-api\").List(context.TODO(), metav1.ListOptions{LabelSelector: windowsOSLabel})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list machines: %v\", err)\n\t\t}\n\t\tprovisionedMachines = []mapi.Machine{}\n\n\t\tphaseProvisioned := \"Provisioned\"\n\n\t\tfor _, machine := range allMachines.Items {\n\t\t\tinstanceStatus := machine.Status\n\t\t\tif instanceStatus.Phase != nil && *instanceStatus.Phase == phaseProvisioned {\n\t\t\t\tprovisionedMachines = append(provisionedMachines, machine)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\tif skipVMSetup {\n\t\tif vmCount == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no Windows VMs found\")\n\t\t}\n\t\treturn provisionedMachines, nil\n\t}\n\tif vmCount == len(provisionedMachines) {\n\t\treturn provisionedMachines, nil\n\t}\n\treturn nil, fmt.Errorf(\"expected VM count %d but got %d\", vmCount, len(provisionedMachines))\n}", "func waitForSystemTime() {\n\ttime.Sleep(150 * time.Millisecond)\n}", "func Control(mk utils.CommandMaker, clk utils.Timer, lg Logger) {\n\tmaker = mk\n\tclock = clk\n\tlogger = lg\n\n\tacquireData()\n\n\terr := initClient()\n\tif err != nil {\n\t\tlogger.LogFatalf(\"Control: unable to initialize gRPC client: %v\", err)\n\t}\n\n\tdefer destroyEnvironment()\n\n\tinitEnvironment()\n\ttok, err := getToken()\n\tif err != nil {\n\t\tlogger.LogFatalf(\"Control: could not acquire device token: %v\", err)\n\t}\n\tdeviceToken = tok\n\tps := makeProbes()\n\trwg, err := startResolver()\n\tif err != nil {\n\t\tlogger.LogFatalf(\"Control: unable to start resolver: %v\", err)\n\t}\n\tpwg := startProbes(ps)\n\n\terr = communicate()\n\tif err != nil {\n\t\tlogger.LogErrorf(\"Control: communication error, %v\", err)\n\t}\n\n\tstopProbes(pwg)\n\tstopResolver(rwg)\n\n\terr = confirmStop()\n\n\t// Connection was lost to the controller, so assume it has terminated and delete VM instance\n\tif err != nil {\n\t\tdeleteVM()\n\t}\n}", "func WaitDestroy(s *state.State) error {\n\ts.Logger.Info(\"Waiting for all machines to get deleted...\")\n\n\treturn wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) {\n\t\tlist := &clusterv1alpha1.MachineList{}\n\t\tif err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\t\treturn false, fail.KubeClient(err, \"getting %T\", list)\n\t\t}\n\t\tif len(list.Items) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func waitForSystemdActiveState(units []string, maxAttempts int) (errch chan error) {\n\terrchan := make(chan error)\n\tvar wg sync.WaitGroup\n\tfor _, name := range units {\n\t\twg.Add(1)\n\t\tgo checkSystemdActiveState(name, maxAttempts, &wg, errchan)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errchan)\n\t}()\n\n\treturn errchan\n}", "func StartControllers(s *options.MCMServer,\n\tcontrolCoreKubeconfig *rest.Config,\n\ttargetCoreKubeconfig *rest.Config,\n\tcontrolMachineClientBuilder machinecontroller.ClientBuilder,\n\tcontrolCoreClientBuilder corecontroller.ClientBuilder,\n\ttargetCoreClientBuilder corecontroller.ClientBuilder,\n\trecorder record.EventRecorder,\n\tstop <-chan struct{}) error {\n\n\tklog.V(5).Info(\"Getting available resources\")\n\tavailableResources, err := getAvailableResources(controlCoreClientBuilder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontrolMachineClient := controlMachineClientBuilder.ClientOrDie(controllerManagerAgentName).MachineV1alpha1()\n\n\tcontrolCoreKubeconfig = rest.AddUserAgent(controlCoreKubeconfig, controllerManagerAgentName)\n\tcontrolCoreClient, err := kubernetes.NewForConfig(controlCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\ttargetCoreKubeconfig = rest.AddUserAgent(targetCoreKubeconfig, controllerManagerAgentName)\n\ttargetCoreClient, err := kubernetes.NewForConfig(targetCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\tif availableResources[machineGVR] || availableResources[machineSetGVR] || availableResources[machineDeploymentGVR] {\n\t\tklog.V(5).Infof(\"Creating shared informers; resync interval: %v\", s.MinResyncPeriod)\n\n\t\tcontrolMachineInformerFactory := machineinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolMachineClientBuilder.ClientOrDie(\"control-machine-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\tcontrolCoreInformerFactory := coreinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolCoreClientBuilder.ClientOrDie(\"control-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\ttargetCoreInformerFactory := coreinformers.NewSharedInformerFactory(\n\t\t\ttargetCoreClientBuilder.ClientOrDie(\"target-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t)\n\n\t\t// All shared informers are v1alpha1 API level\n\t\tmachineSharedInformers := controlMachineInformerFactory.Machine().V1alpha1()\n\n\t\tklog.V(5).Infof(\"Creating controllers...\")\n\t\tmcmcontroller, err := mcmcontroller.NewController(\n\t\t\ts.Namespace,\n\t\t\tcontrolMachineClient,\n\t\t\tcontrolCoreClient,\n\t\t\ttargetCoreClient,\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumes(),\n\t\t\tcontrolCoreInformerFactory.Core().V1().Secrets(),\n\t\t\ttargetCoreInformerFactory.Core().V1().Nodes(),\n\t\t\tmachineSharedInformers.OpenStackMachineClasses(),\n\t\t\tmachineSharedInformers.AWSMachineClasses(),\n\t\t\tmachineSharedInformers.AzureMachineClasses(),\n\t\t\tmachineSharedInformers.GCPMachineClasses(),\n\t\t\tmachineSharedInformers.AlicloudMachineClasses(),\n\t\t\tmachineSharedInformers.PacketMachineClasses(),\n\t\t\tmachineSharedInformers.Machines(),\n\t\t\tmachineSharedInformers.MachineSets(),\n\t\t\tmachineSharedInformers.MachineDeployments(),\n\t\t\trecorder,\n\t\t\ts.SafetyOptions,\n\t\t\ts.NodeConditions,\n\t\t\ts.BootstrapTokenAuthExtraGroups,\n\t\t\ts.DeleteMigratedMachineClass,\n\t\t\ts.AutoscalerScaleDownAnnotationDuringRollout,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(1).Info(\"Starting shared informers\")\n\n\t\tcontrolMachineInformerFactory.Start(stop)\n\t\tcontrolCoreInformerFactory.Start(stop)\n\t\ttargetCoreInformerFactory.Start(stop)\n\n\t\tklog.V(5).Info(\"Running controller\")\n\t\tgo mcmcontroller.Run(int(s.ConcurrentNodeSyncs), stop)\n\n\t} else {\n\t\treturn fmt.Errorf(\"unable to start machine controller: API GroupVersion %q or %q or %q is not available; \\nFound: %#v\", machineGVR, machineSetGVR, machineDeploymentGVR, availableResources)\n\t}\n\n\tselect {}\n}", "func (machine *Machine) Create(e *expect.GExpect, root *Root, server *Server) error {\n\ttasks := []*Task{\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\t`cd('/')`,\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\t`edit:/`,\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`\nif '%s' == 'UnixMachine':\n\tcmo.createUnixMachine('%s')\n\tprint 'XxXsuccessXxX'\nelif '%[1]s' == 'Machine':\n\tcmo.createUnixMachine('%[2]s')\n\tprint 'XxXsuccessXxX'\nelse:\n\tprint 'XxXfailedXxX'\n`, machine.Type, machine.Name),\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\t`XxXsuccessXxX`,\n\t\t\t\t`weblogic.descriptor.BeanAlreadyExistsException: Bean already exists`,\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cd('/Machines/%s/NodeManager/%[1]s')`, machine.Name),\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'edit:/Machines/%s/NodeManager/%[1]s'`, machine.Name),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setListenAddress('%s')`, machine.Host),\n\t\t\t\t`cmo.getListenAddress()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'%s'`, machine.Host),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setListenPort(%s)`, machine.Port),\n\t\t\t\t`cmo.getListenPort()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`%s`, machine.Port),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setNMType('%s')`, machine.Protocol),\n\t\t\t\t`cmo.getNMType()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(\"'%s'\", machine.Protocol),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cd('/Servers/%s')`, server.Name),\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'edit:/Servers/%s'`, server.Name),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setMachine(getMBean('/Machines/%s'))`, machine.Name),\n\t\t\t\t`cmo.getMachine()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`\\[MBeanServerInvocationHandler\\]com.bea:Name=%s,Type=%s`, machine.Name, machine.Type),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t}\n\tfor _, task := range tasks {\n\t\tif err := RunTask(task, \"Machine-Create\", e); err != nil {\n\t\t\tserver.ReturnStatus = ret.Failed\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Manager) waitForFinish() {\n\tm.state.wg.Wait()\n}", "func waitForRunning(s drmaa.Session, jobId string, hostCh chan string) {\n\t// Wait for running job\n\td, _ := time.ParseDuration(\"500ms\")\n\tps, _ := s.JobPs(jobId)\n\tfor ps != drmaa.PsRunning {\n\t\ttime.Sleep(d)\n\t\tps, _ = s.JobPs(jobId)\n\t}\n\n\t// Get hostname\n\tjobStatus, err := gestatus.GetJobStatus(&s, jobId)\n\tif err != nil {\n\t\tfmt.Printf(\"Error in getting hostname for job %s: %s\\n\", jobId, err.Error())\n\t\thostCh <- \"\"\n\t\treturn\n\t}\n\thostname := jobStatus.DestinationHostList()\n\thostCh <- strings.Join(hostname, \"\")\n}", "func (v *MachineVM) Stop(name string, _ machine.StopOptions) error {\n\t// check if the qmp socket is there. if not, qemu instance is gone\n\tif _, err := os.Stat(v.QMPMonitor.Address); os.IsNotExist(err) {\n\t\t// Right now it is NOT an error to stop a stopped machine\n\t\tlogrus.Debugf(\"QMP monitor socket %v does not exist\", v.QMPMonitor.Address)\n\t\treturn nil\n\t}\n\tqmpMonitor, err := qmp.NewSocketMonitor(v.QMPMonitor.Network, v.QMPMonitor.Address, v.QMPMonitor.Timeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Simple JSON formation for the QAPI\n\tstopCommand := struct {\n\t\tExecute string `json:\"execute\"`\n\t}{\n\t\tExecute: \"system_powerdown\",\n\t}\n\tinput, err := json.Marshal(stopCommand)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := qmpMonitor.Connect(); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := qmpMonitor.Disconnect(); err != nil {\n\t\t\tlogrus.Error(err)\n\t\t}\n\t}()\n\tif _, err = qmpMonitor.Run(input); err != nil {\n\t\treturn err\n\t}\n\tqemuSocketFile, pidFile, err := v.getSocketandPid()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := os.Stat(pidFile); os.IsNotExist(err) {\n\t\tlogrus.Infof(\"pid file %s does not exist\", pidFile)\n\t\treturn nil\n\t}\n\tpidString, err := ioutil.ReadFile(pidFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpidNum, err := strconv.Atoi(string(pidString))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp, err := os.FindProcess(pidNum)\n\tif p == nil && err != nil {\n\t\treturn err\n\t}\n\t// Kill the process\n\tif err := p.Kill(); err != nil {\n\t\treturn err\n\t}\n\t// Remove the pidfile\n\tif err := os.Remove(pidFile); err != nil && !errors.Is(err, os.ErrNotExist) {\n\t\tlogrus.Warn(err)\n\t}\n\t// Remove socket\n\treturn os.Remove(qemuSocketFile)\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func (rcc *rotateCertsCmd) waitForKubeSystemReadiness() error {\n\tlog.Info(\"Checking health of all kube-system pods\")\n\ttimeout := time.Duration(len(rcc.nodes)) * time.Duration(float64(time.Minute)*1.25)\n\tif rotateCertsDefaultTimeout > timeout {\n\t\ttimeout = rotateCertsDefaultTimeout\n\t}\n\tif err := ops.WaitForAllInNamespaceReady(rcc.kubeClient, metav1.NamespaceSystem, rotateCertsDefaultInterval, timeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for kube-system containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func waitForClusterProvisioned(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Provisioned\n\t\t},\n\t)\n}", "func (mgr *l3Manager) waitBackend() {\n\tlog.Printf(\"L3: Waiting backend to terminate\")\n\t<-mgr.done\n\tlog.Printf(\"L3: Backend terminated\")\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func Run(s *options.MCMServer) error {\n\t// To help debugging, immediately log version\n\tklog.V(4).Infof(\"Version: %+v\", version.Get())\n\tif err := s.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\n\t//kubeconfig for the cluster for which machine-controller-manager will create machines.\n\ttargetkubeconfig, err := clientcmd.BuildConfigFromFlags(\"\", s.TargetKubeconfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontrolkubeconfig := targetkubeconfig\n\n\tif s.ControlKubeconfig != \"\" {\n\t\tif s.ControlKubeconfig == \"inClusterConfig\" {\n\t\t\t//use inClusterConfig when controller is running inside clus\n\t\t\tcontrolkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", \"\")\n\t\t} else {\n\t\t\t//kubeconfig for the seedcluster where MachineCRDs are supposed to be registered.\n\t\t\tcontrolkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", s.ControlKubeconfig)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// PROTOBUF WONT WORK\n\t// kubeconfig.ContentConfig.ContentType = s.ContentType\n\t// Override kubeconfig qps/burst settings from flags\n\ttargetkubeconfig.QPS = s.KubeAPIQPS\n\tcontrolkubeconfig.QPS = s.KubeAPIQPS\n\ttargetkubeconfig.Burst = int(s.KubeAPIBurst)\n\tcontrolkubeconfig.Burst = int(s.KubeAPIBurst)\n\ttargetkubeconfig.Timeout = targetkubeconfigTimeout\n\tcontrolkubeconfig.Timeout = controlkubeconfigTimeout\n\n\tkubeClientControl, err := kubernetes.NewForConfig(\n\t\trest.AddUserAgent(controlkubeconfig, \"machine-controller-manager\"),\n\t)\n\tif err != nil {\n\t\tklog.Fatalf(\"Invalid API configuration for kubeconfig-control: %v\", err)\n\t}\n\n\tleaderElectionClient := kubernetes.NewForConfigOrDie(rest.AddUserAgent(controlkubeconfig, \"machine-leader-election\"))\n\tklog.V(4).Info(\"Starting http server and mux\")\n\tgo startHTTP(s)\n\n\trecorder := createRecorder(kubeClientControl)\n\n\trun := func(ctx context.Context) {\n\t\tvar stop <-chan struct{}\n\t\t// Control plane client used to interact with machine APIs\n\t\tcontrolMachineClientBuilder := machinecontroller.SimpleClientBuilder{\n\t\t\tClientConfig: controlkubeconfig,\n\t\t}\n\t\t// Control plane client used to interact with core kubernetes objects\n\t\tcontrolCoreClientBuilder := corecontroller.SimpleControllerClientBuilder{\n\t\t\tClientConfig: controlkubeconfig,\n\t\t}\n\t\t// Target plane client used to interact with core kubernetes objects\n\t\ttargetCoreClientBuilder := corecontroller.SimpleControllerClientBuilder{\n\t\t\tClientConfig: targetkubeconfig,\n\t\t}\n\n\t\terr := StartControllers(\n\t\t\ts,\n\t\t\tcontrolkubeconfig,\n\t\t\ttargetkubeconfig,\n\t\t\tcontrolMachineClientBuilder,\n\t\t\tcontrolCoreClientBuilder,\n\t\t\ttargetCoreClientBuilder,\n\t\t\trecorder,\n\t\t\tstop,\n\t\t)\n\n\t\tklog.Fatalf(\"error running controllers: %v\", err)\n\t\tpanic(\"unreachable\")\n\n\t}\n\n\tif !s.LeaderElection.LeaderElect {\n\t\trun(nil)\n\t\tpanic(\"unreachable\")\n\t}\n\n\tid, err := os.Hostname()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trl, err := resourcelock.New(\n\t\ts.LeaderElection.ResourceLock,\n\t\ts.Namespace,\n\t\t\"machine-controller-manager\",\n\t\tleaderElectionClient.CoreV1(),\n\t\tleaderElectionClient.CoordinationV1(),\n\t\tresourcelock.ResourceLockConfig{\n\t\t\tIdentity: id,\n\t\t\tEventRecorder: recorder,\n\t\t},\n\t)\n\tif err != nil {\n\t\tklog.Fatalf(\"error creating lock: %v\", err)\n\t}\n\n\tctx := context.TODO()\n\tleaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{\n\t\tLock: rl,\n\t\tLeaseDuration: s.LeaderElection.LeaseDuration.Duration,\n\t\tRenewDeadline: s.LeaderElection.RenewDeadline.Duration,\n\t\tRetryPeriod: s.LeaderElection.RetryPeriod.Duration,\n\t\tCallbacks: leaderelection.LeaderCallbacks{\n\t\t\tOnStartedLeading: run,\n\t\t\tOnStoppedLeading: func() {\n\t\t\t\tklog.Fatalf(\"leaderelection lost\")\n\t\t\t},\n\t\t},\n\t})\n\tpanic(\"unreachable\")\n}", "func instanceController() {\n\t// terminate is used for killing an instance of a task.\n\tcommands := map[string]*exec.Cmd{}\n\tvar terminate = func(name string, cmd *exec.Cmd) {\n\t\tif cmd.Process == nil {\n\t\t\treturn\n\t\t}\n\n\t\tpid := cmd.Process.Pid\n\t\terr := cmd.Process.Kill()\n\t\tif err == nil {\n\t\t\tcmd.Process.Wait()\n\t\t}\n\t\tdelete(commands, name)\n\t\tlog.Trace.Printf(`Active instance of \"%s\" (PID %d) has been terminated.`, name, pid)\n\t}\n\n\t// Clean up on termination.\n\tdefer func() {\n\t\tfor name, cmd := range commands {\n\t\t\tterminate(name, cmd)\n\t\t}\n\t\tstopped <- true\n\t}()\n\n\t// Waiting till we are asked to run/restart some tasks or exit\n\t// and following the orders.\n\tfor {\n\t\tswitch m := <-channel; m.action {\n\t\tcase \"start\":\n\t\t\t// Check whether we have already had an instance of the\n\t\t\t// requested task.\n\t\t\tcmd, ok := commands[m.name]\n\t\t\tif ok {\n\t\t\t\t// If so, terminate it first.\n\t\t\t\tterminate(m.name, cmd)\n\t\t\t}\n\n\t\t\t// If this is the first time this command is requested\n\t\t\t// to be run, initialize things.\n\t\t\tn, as := parseTask(m.task)\n\t\t\tlog.Trace.Printf(`Preparing \"%s\"...`, n)\n\t\t\tcmd = exec.Command(n, as...)\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\tcmd.Stdout = os.Stdout\n\n\t\t\t// Starting the task.\n\t\t\tlog.Trace.Printf(\"Starting a new instance of `%s` (%v)...\", n, as)\n\t\t\terr := cmd.Start()\n\t\t\tif err != nil {\n\t\t\t\tlog.Error.Printf(\"Failed to start a command `%s`, error: %v.\", n, err)\n\t\t\t}\n\t\t\tcommands[m.name] = cmd // Register the command so we can terminate it.\n\t\tcase \"exit\":\n\t\t\treturn\n\t\t}\n\t}\n}", "func (v *MachineVM) Start(name string, _ machine.StartOptions) error {\n\tvar (\n\t\tconn net.Conn\n\t\terr error\n\t\tqemuSocketConn net.Conn\n\t\twait time.Duration = time.Millisecond * 500\n\t)\n\n\tif err := v.startHostNetworking(); err != nil {\n\t\treturn errors.Errorf(\"unable to start host networking: %q\", err)\n\t}\n\n\trtPath, err := getRuntimeDir()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the temporary podman dir is not created, create it\n\tpodmanTempDir := filepath.Join(rtPath, \"podman\")\n\tif _, err := os.Stat(podmanTempDir); os.IsNotExist(err) {\n\t\tif mkdirErr := os.MkdirAll(podmanTempDir, 0755); mkdirErr != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tqemuSocketPath, _, err := v.getSocketandPid()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// If the qemusocketpath exists and the vm is off/down, we should rm\n\t// it before the dial as to avoid a segv\n\tif err := os.Remove(qemuSocketPath); err != nil && !errors.Is(err, os.ErrNotExist) {\n\t\tlogrus.Warn(err)\n\t}\n\tfor i := 0; i < 6; i++ {\n\t\tqemuSocketConn, err = net.Dial(\"unix\", qemuSocketPath)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(wait)\n\t\twait++\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfd, err := qemuSocketConn.(*net.UnixConn).File()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tattr := new(os.ProcAttr)\n\tfiles := []*os.File{os.Stdin, os.Stdout, os.Stderr, fd}\n\tattr.Files = files\n\tlogrus.Debug(v.CmdLine)\n\tcmd := v.CmdLine\n\n\t// Disable graphic window when not in debug mode\n\t// Done in start, so we're not suck with the debug level we used on init\n\tif logrus.GetLevel() != logrus.DebugLevel {\n\t\tcmd = append(cmd, \"-display\", \"none\")\n\t}\n\n\t_, err = os.StartProcess(v.CmdLine[0], cmd, attr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Waiting for VM ...\")\n\tsocketPath, err := getRuntimeDir()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The socket is not made until the qemu process is running so here\n\t// we do a backoff waiting for it. Once we have a conn, we break and\n\t// then wait to read it.\n\tfor i := 0; i < 6; i++ {\n\t\tconn, err = net.Dial(\"unix\", filepath.Join(socketPath, \"podman\", v.Name+\"_ready.sock\"))\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(wait)\n\t\twait++\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = bufio.NewReader(conn).ReadString('\\n')\n\treturn err\n}", "func waitForMachineSetToNotExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForObjectToNotExist(\n\t\tnamespace, name,\n\t\tfunc(namespace, name string) (metav1.Object, error) {\n\t\t\treturn getMachineSet(capiClient, namespace, name)\n\t\t},\n\t)\n}", "func waitForGlusterContainer() error {\n\n\t//Check if docker gluster container is up and running\n\tfor {\n\t\tglusterServerContainerVal, err := helpers.GetSystemDockerNode(\"gluster-server\")\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error in checking docker gluster container for status \", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tif len(glusterServerContainerVal) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\trwolog.Debug(\"Sleeping for 10 seconds to get gluster docker container up\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func waitForResult() {\n\twork := make(chan string)\n\n\tgo func() {\n\t\ttime.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)\n\t\twork <- \"Done\"\n\t}()\n\n\ttime.Sleep(time.Second)\n\tmanager := <-work\n\n\tfmt.Printf(\"%+v\\n\", manager)\n}", "func (mod *Module)WaitTillStartupDone(){\n\tfor mod.hasRunStartup == false{//wait for startup to stop running\n\t\ttime.Sleep(time.Millisecond*10)\n\t}\n}", "func (d *vimInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func (c *Client) doWaitForStatus(eniID string, checkNum, checkInterval int, finalStatus string) error {\n\tfor i := 0; i < checkNum; i++ {\n\t\ttime.Sleep(time.Second * time.Duration(checkInterval))\n\t\tenis, err := c.queryENI(eniID, \"\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, eni := range enis {\n\t\t\tif *eni.NetworkInterfaceId == eniID {\n\t\t\t\tswitch *eni.State {\n\t\t\t\tcase ENI_STATUS_AVAILABLE:\n\t\t\t\t\tswitch finalStatus {\n\t\t\t\t\tcase ENI_STATUS_ATTACHED:\n\t\t\t\t\t\tif eni.Attachment != nil && eni.Attachment.InstanceId != nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is attached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not attached\", eniID)\n\t\t\t\t\tcase ENI_STATUS_DETACHED:\n\t\t\t\t\t\tif eni.Attachment == nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is detached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not detached\", eniID)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tblog.Infof(\"eni %s is %s now\", eniID, *eni.State)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase ENI_STATUS_PENDING, ENI_STATUS_ATTACHING, ENI_STATUS_DETACHING, ENI_STATUS_DELETING:\n\t\t\t\t\tblog.Infof(\"eni %s is %s\", eniID, *eni.State)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tblog.Errorf(\"timeout when wait for eni %s\", eniID)\n\treturn fmt.Errorf(\"timeout when wait for eni %s\", eniID)\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal, min, max int32) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\td, err := cs.AppsV1Interface.Deployments(\"openshift-machine-config-operator\").Get(context.TODO(), \"etcd-quorum-guard\", metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// By this point the deployment should exist.\n\t\t\tfmt.Printf(\" error waiting for etcd-quorum-guard deployment to exist: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tif d.Status.Replicas < 1 {\n\t\t\tfmt.Println(\"operator deployment has no replicas\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.Replicas == expectedTotal &&\n\t\t\td.Status.AvailableReplicas >= min &&\n\t\t\td.Status.AvailableReplicas <= max {\n\t\t\tfmt.Printf(\" Deployment is ready! %d %d\\n\", d.Status.Replicas, d.Status.AvailableReplicas)\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\tfor pod, info := range pods {\n\t\tif info.status == \"Running\" {\n\t\t\tnode := info.node\n\t\t\tif node == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Pod %s not associated with a node\", pod)\n\t\t\t}\n\t\t\tif _, ok := nodes[node]; !ok {\n\t\t\t\treturn fmt.Errorf(\"pod %s running on %s, not a master\", pod, node)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *conntrackInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func (vm *VirtualMachine) WaitUntilReady(client SkytapClient) (*VirtualMachine, error) {\n\treturn vm.WaitUntilInState(client, []string{RunStateStop, RunStateStart, RunStatePause}, false)\n}", "func WaitForCondition(mcpName string, conditionType machineconfigv1.MachineConfigPoolConditionType, conditionStatus corev1.ConditionStatus) {\n\n\tvar cnfNodes []corev1.Node\n\trunningOnSingleNode, err := cluster.IsSingleNode()\n\tExpectWithOffset(1, err).ToNot(HaveOccurred())\n\t// checking in eventually as in case of single node cluster the only node may\n\t// be rebooting\n\tEventuallyWithOffset(1, func() error {\n\t\tmcp, err := GetByName(mcpName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting MCP by name\")\n\t\t}\n\n\t\tnodeLabels := mcp.Spec.NodeSelector.MatchLabels\n\t\tkey, _ := components.GetFirstKeyAndValue(nodeLabels)\n\t\treq, err := labels.NewRequirement(key, selection.Exists, []string{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed creating node selector\")\n\t\t}\n\n\t\tselector := labels.NewSelector()\n\t\tselector = selector.Add(*req)\n\t\tcnfNodes, err = nodes.GetBySelector(selector)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting nodes by selector\")\n\t\t}\n\n\t\ttestlog.Infof(\"MCP %q is targeting %v node(s)\", mcp.Name, len(cnfNodes))\n\t\treturn nil\n\t}, cluster.ComputeTestTimeout(10*time.Minute, runningOnSingleNode), 5*time.Second).ShouldNot(HaveOccurred(), \"Failed to find CNF nodes by MCP %q\", mcpName)\n\n\t// timeout should be based on the number of worker-cnf nodes\n\ttimeout := time.Duration(len(cnfNodes)*mcpUpdateTimeoutPerNode) * time.Minute\n\tif len(cnfNodes) == 0 {\n\t\ttimeout = 2 * time.Minute\n\t}\n\n\tEventuallyWithOffset(1, func() corev1.ConditionStatus {\n\t\treturn GetConditionStatus(mcpName, conditionType)\n\t}, cluster.ComputeTestTimeout(timeout, runningOnSingleNode), 30*time.Second).Should(Equal(conditionStatus), \"Failed to find condition status by MCP %q\", mcpName)\n}", "func (c *controller) waitKnativeServiceReady(\n\tctx context.Context,\n\tsvcName string,\n\tnamespace string,\n) error {\n\t// Init ticker to check status every second\n\tticker := time.NewTicker(time.Second)\n\tdefer ticker.Stop()\n\n\t// Init knative ServicesGetter\n\tservices := c.knServingClient.Services(namespace)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tterminationMessage := c.getKnativePodTerminationMessage(svcName, namespace)\n\t\t\tif terminationMessage == \"\" {\n\t\t\t\t// Pod was not created (as with invalid image names), get status messages from the knative service.\n\t\t\t\tsvc, err := services.Get(svcName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\tterminationMessage = err.Error()\n\t\t\t\t} else {\n\t\t\t\t\tterminationMessage = getKnServiceStatusMessages(svc)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"timeout waiting for service %s to be ready:\\n%s\", svcName, terminationMessage)\n\t\tcase <-ticker.C:\n\t\t\tsvc, err := services.Get(svcName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to get service status for %s: %v\", svcName, err)\n\t\t\t}\n\n\t\t\tif svc.Status.IsReady() {\n\t\t\t\t// Service is completely ready\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *Actuator) Create(c *clusterv1.Cluster, m *clusterv1.Machine) error {\n\tglog.Infof(\"Creating machine %s for cluster %s.\", m.Name, c.Name)\n\tif a.machineSetupConfigGetter == nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"valid machineSetupConfigGetter is required\"), createEventAction)\n\t}\n\n\t// First get provider config\n\tmachineConfig, err := a.machineProviderConfig(m.Spec.ProviderConfig)\n\tif err != nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"Cannot unmarshal machine's providerConfig field: %v\", err), createEventAction)\n\t}\n\n\t// Now validate\n\tif err := a.validateMachine(m, machineConfig); err != nil {\n\t\treturn a.handleMachineError(m, err, createEventAction)\n\t}\n\n\t// check if the machine exists (here we mean we haven't provisioned it yet.)\n\texists, err := a.Exists(c, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif exists {\n\t\tglog.Infof(\"Machine %s for cluster %s exists, skipping.\", m.Name, c.Name)\n\t\treturn nil\n\t}\n\n\t// The doesn't exist case here.\n\tglog.Infof(\"Machine %s for cluster %s doesn't exist.\", m.Name, c.Name)\n\n\tconfigParams := &MachineParams{\n\t\tRoles: machineConfig.Roles,\n\t\tVersions: m.Spec.Versions,\n\t}\n\n\tmetadata, err := a.getMetadata(c, m, configParams, machineConfig.SSHConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Metadata retrieved: machine %s for cluster %s\", m.Name, c.Name)\n\n\t// Here we deploy and run the scripts to the node.\n\tprivateKey, passPhrase, err := a.getPrivateKey(c, m.Namespace, machineConfig.SSHConfig.SecretName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Running startup script: machine %s for cluster %s...\", m.Name, c.Name)\n\n\tsshClient := ssh.NewSSHProviderClient(privateKey, passPhrase, machineConfig.SSHConfig)\n\n\tif err = sshClient.WriteFile(metadata.StartupScript, \"/var/tmp/startupscript.sh\"); err != nil {\n\t\tglog.Errorf(\"Error copying startup script: %v\", err)\n\t\treturn err\n\t}\n\n\tif err = sshClient.ProcessCMD(\"chmod +x /var/tmp/startupscript.sh && bash /var/tmp/startupscript.sh\"); err != nil {\n\t\tglog.Errorf(\"running startup script error: %v\", err)\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Annotating machine %s for cluster %s.\", m.Name, c.Name)\n\n\t// TODO find a way to do this in the cluster controller\n\tif util.IsMaster(m) {\n\t\terr = a.updateClusterObjectEndpoint(c, m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// create kubeconfig secret\n\t\terr = a.createKubeconfigSecret(c, m, sshClient)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ta.eventRecorder.Eventf(m, corev1.EventTypeNormal, \"Created\", \"Created Machine %v\", m.Name)\n\treturn a.updateAnnotations(c, m)\n}", "func waitForServer(client *http.Client, serverAddress string) error {\n\tvar err error\n\t// wait for the server to come up\n\tfor i := 0; i < 10; i++ {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\t_, err = client.Get(\"http://\" + serverAddress)\n\t\tif err == nil {\n\t\t\treturn nil // server is up now\n\t\t}\n\t}\n\treturn fmt.Errorf(\"timed out waiting for server %s to come up: %w\", serverAddress, err)\n}", "func (s *LocalTests) deleteMachine(c *gc.C, machineId string) {\n\terr := s.testClient.StopMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n\n\t// wait for machine to be stopped\n\tfor !s.pollMachineState(c, machineId, \"stopped\") {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\terr = s.testClient.DeleteMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n}", "func TestRequestStopFromMovingUp(t *testing.T) {\n\t// setup\n\tdwController := setup(t, 2, Up, []common.PiPin{common.OpenerStop})\n\n\t// test\n\tdwController.SetStopRequested() // send the stop request\n\twaitForStatus(t, 2, 2, Stopped, dwController, 3*time.Second) // verify that the dumbwaiter is now stopped\n}", "func (m *Machine) waitForSocket(timeout time.Duration, exitchan chan error) error {\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\n\tticker := time.NewTicker(10 * time.Millisecond)\n\n\tdefer func() {\n\t\tcancel()\n\t\tticker.Stop()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase err := <-exitchan:\n\t\t\treturn err\n\t\tcase <-ticker.C:\n\t\t\tif _, err := os.Stat(m.Cfg.SocketPath); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Send test HTTP request to make sure socket is available\n\t\t\tif _, err := m.client.GetMachineConfiguration(); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *Controller) Run(ctx context.Context) error {\n\t// Start the informer factories to begin populating the informer caches\n\tc.log.Infof(\"starting step control loop, node name: %s\", c.nodeName)\n\n\t// 初始化runner\n\tc.log.Info(\"init controller engine\")\n\tif err := engine.Init(c.wc, c.informer.Recorder()); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.sync(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tc.waitDown(ctx)\n\treturn nil\n}", "func (c *controller) WaitAndUpdateNodesStatus(ctx context.Context, wg *sync.WaitGroup, removeUninitializedTaint bool) {\n\tapproveCtx, approveCancel := context.WithCancel(ctx)\n\tdefer func() {\n\t\tapproveCancel()\n\t\tc.log.Infof(\"WaitAndUpdateNodesStatus finished\")\n\t\twg.Done()\n\t}()\n\t// starting approve csrs\n\tgo c.ApproveCsrs(approveCtx)\n\n\tc.log.Infof(\"Waiting till all nodes will join and update status to assisted installer\")\n\t_ = utils.WaitForPredicateParamsWithContext(ctx, LongWaitTimeout, GeneralWaitInterval, c.waitAndUpdateNodesStatus, removeUninitializedTaint)\n}", "func waitForHosts(path string) {\n\toldPwd := sh.Pwd()\n\tsh.Cd(path)\n\tlog.Debug(\"Ensuring ansible-playbook can be executed properly\")\n\tsh.SetE(exec.Command(\"ansible-playbook\", \"--version\"))\n\tpathToPlaybook := \"./playbooks/wait-for-hosts.yml\"\n\tansibleCommand := []string{\n\t\t\"-i\", \"plugins/inventory/terraform.py\",\n\t\t\"-e\", \"ansible_python_interpreter=\" + strings.TrimSpace(pythonBinary),\n\t\t\"-e\", \"@security.yml\",\n\t\tpathToPlaybook,\n\t}\n\tcmd := exec.Command(\"ansible-playbook\", ansibleCommand...)\n\tlog.Info(\"Waiting for SSH access to hosts...\")\n\toutStr, err := ExecuteWithOutput(cmd)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"command\": cmd.Args,\n\t\t\t\"output\": outStr,\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalf(\"Couldn't execute playbook %s\", pathToPlaybook)\n\t}\n\tsh.Cd(oldPwd)\n}", "func waitForAPI(ctx context.Context, client *gophercloud.ServiceClient) {\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\t// NOTE: Some versions of Ironic inspector returns 404 for /v1/ but 200 for /v1,\n\t// which seems to be the default behavior for Flask. Remove the trailing slash\n\t// from the client endpoint.\n\tendpoint := strings.TrimSuffix(client.Endpoint, \"/\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for API to become available...\")\n\n\t\t\tr, err := httpClient.Get(endpoint)\n\t\t\tif err == nil {\n\t\t\t\tstatusCode := r.StatusCode\n\t\t\t\tr.Body.Close()\n\t\t\t\tif statusCode == http.StatusOK {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (m *MeshReconciler) waitForCRD(name string, client runtimeclient.Client) error {\n\tm.logger.WithField(\"name\", name).Debug(\"waiting for CRD\")\n\n\tbackoffConfig := backoff.ConstantBackoffConfig{\n\t\tDelay: time.Duration(backoffDelaySeconds) * time.Second,\n\t\tMaxRetries: backoffMaxretries,\n\t}\n\tbackoffPolicy := backoff.NewConstantBackoffPolicy(backoffConfig)\n\n\tvar crd apiextensionsv1beta1.CustomResourceDefinition\n\terr := backoff.Retry(func() error {\n\t\terr := client.Get(context.Background(), types.NamespacedName{\n\t\t\tName: name,\n\t\t}, &crd)\n\t\tif err != nil {\n\t\t\treturn errors.WrapIf(err, \"could not get CRD\")\n\t\t}\n\n\t\tfor _, condition := range crd.Status.Conditions {\n\t\t\tif condition.Type == apiextensionsv1beta1.Established {\n\t\t\t\tif condition.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn errors.New(\"CRD is not established yet\")\n\t}, backoffPolicy)\n\n\treturn err\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n\tlog.Printf(\"[TEST] thats all folks\")\n}", "func (m *Machine) startVMM(ctx context.Context) error {\n\tm.logger.Printf(\"Called startVMM(), setting up a VMM on %s\", m.Cfg.SocketPath)\n\tstartCmd := m.cmd.Start\n\n\tm.logger.Debugf(\"Starting %v\", m.cmd.Args)\n\n\tvar err error\n\tif m.Cfg.NetNS != \"\" && m.Cfg.JailerCfg == nil {\n\t\t// If the VM needs to be started in a netns but no jailer netns was configured,\n\t\t// start the vmm child process in the netns directly here.\n\t\terr = ns.WithNetNSPath(m.Cfg.NetNS, func(_ ns.NetNS) error {\n\t\t\treturn startCmd()\n\t\t})\n\t} else {\n\t\t// Else, just start the process normally as it's either not in a netns or will\n\t\t// be placed in one by the jailer process instead.\n\t\terr = startCmd()\n\t}\n\n\tif err != nil {\n\t\tm.logger.Errorf(\"Failed to start VMM: %s\", err)\n\n\t\tm.fatalErr = err\n\t\tclose(m.exitCh)\n\n\t\treturn err\n\t}\n\tm.logger.Debugf(\"VMM started socket path is %s\", m.Cfg.SocketPath)\n\n\tm.cleanupFuncs = append(m.cleanupFuncs,\n\t\tfunc() error {\n\t\t\tif err := os.Remove(m.Cfg.SocketPath); !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\n\terrCh := make(chan error)\n\tgo func() {\n\t\twaitErr := m.cmd.Wait()\n\t\tif waitErr != nil {\n\t\t\tm.logger.Warnf(\"firecracker exited: %s\", waitErr.Error())\n\t\t} else {\n\t\t\tm.logger.Printf(\"firecracker exited: status=0\")\n\t\t}\n\n\t\tcleanupErr := m.doCleanup()\n\t\tif cleanupErr != nil {\n\t\t\tm.logger.Errorf(\"failed to cleanup after VM exit: %v\", cleanupErr)\n\t\t}\n\n\t\terrCh <- multierror.Append(waitErr, cleanupErr).ErrorOrNil()\n\n\t\t// Notify subscribers that there will be no more values.\n\t\t// When err is nil, two reads are performed (waitForSocket and close exitCh goroutine),\n\t\t// second one never ends as it tries to read from empty channel.\n\t\tclose(errCh)\n\t}()\n\n\tm.setupSignals()\n\n\t// Wait for firecracker to initialize:\n\terr = m.waitForSocket(time.Duration(m.client.firecrackerInitTimeout)*time.Second, errCh)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"Firecracker did not create API socket %s\", m.Cfg.SocketPath)\n\t\tm.fatalErr = err\n\t\tclose(m.exitCh)\n\n\t\treturn err\n\t}\n\n\t// This goroutine is used to kill the process by context cancelletion,\n\t// but doesn't tell anyone about that.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\terr := m.stopVMM()\n\t\tif err != nil {\n\t\t\tm.logger.WithError(err).Errorf(\"failed to stop vm %q\", m.Cfg.VMID)\n\t\t}\n\t}()\n\n\t// This goroutine is used to tell clients that the process is stopped\n\t// (gracefully or not).\n\tgo func() {\n\t\tm.fatalErr = <-errCh\n\t\tm.logger.Debugf(\"closing the exitCh %v\", m.fatalErr)\n\t\tclose(m.exitCh)\n\t}()\n\n\tm.logger.Debugf(\"returning from startVMM()\")\n\treturn nil\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func (j *Juju) ControllerReady() (bool, error) {\n\ttmp := \"JUJU_DATA=\" + JujuDataPrefix + j.Name\n\tcmd := exec.Command(\"juju\", \"models\", \"--format=json\")\n\tcmd.Env = append(os.Environ(), tmp)\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"ControllerReady error: %v: %s\", err, err.(*exec.ExitError).Stderr)\n\t}\n\n\terr = json.Unmarshal([]byte(out), &jModels)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"ControllerReady unmarshal error: %v: %s\", err, err.(*exec.ExitError).Stderr)\n\t}\n\n\tlog.Debugf(\"ControllerReady: %+v\", jModels)\n\tfor k := range jModels.Models {\n\t\tif jModels.Models[k].ShortName == j.Name {\n\t\t\tstatus := jModels.Models[k].Status[\"current\"]\n\t\t\tif status == \"available\" {\n\t\t\t\tlog.WithFields(logrus.Fields{\"name\": j.Name}).Info(\"Controller Ready\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\tlog.WithFields(logrus.Fields{\"name\": j.Name}).Info(\"Controller Not Ready\")\n\treturn false, nil\n}", "func WaitForBKClusterToTerminate(t *testing.T, k8client client.Client, b *bkapi.BookkeeperCluster) error {\n\tlog.Printf(\"waiting for Bookkeeper cluster to terminate: %s\", b.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(b.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"bookkeeper_cluster\": b.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"bookkeeper cluster terminated: %s\", b.Name)\n\treturn nil\n}", "func waitForClusterReady(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Ready\n\t\t},\n\t)\n}", "func (ins *EC2RemoteClient) makeReady() error {\n\t// Check Instance is running - will error if instance doesn't exist\n\tresult, err := ins.ec2Client.DescribeInstanceStatus(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting instance status : %s\", err)\n\t}\n\n\t// Start instance if needed\n\tif len(result.InstanceStatuses) == 0 || *result.InstanceStatuses[0].InstanceState.Name != \"running\" {\n\t\terr = ins.startInstance()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t\t}\n\t}\n\n\t// Get Public IP address from ec2\n\terr = ins.getIPAddress()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting IP address : %s\", err)\n\t}\n\n\t// Set up SSH connection\n\tins.cmdClient, err = sshCmdClient.NewSSHCmdClient(ins.instanceIP, ins.sshCredentials)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check we can at least run a trivial command\n\texitStatus, err := ins.RunCommand(\"true\")\n\tif err != nil || exitStatus != 0 {\n\t\treturn fmt.Errorf(\"Error running commands on instance : %s\", err)\n\t}\n\n\treturn err\n}", "func waitForKnativeCrdsRegistered(timeout, interval time.Duration) error {\n\telapsed := time.Duration(0)\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(interval):\n\t\t\tif err := kubectl(nil, \"get\", \"images.caching.internal.knative.dev\"); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\telapsed += interval\n\t\t\tif elapsed > timeout {\n\t\t\t\treturn errors.Errorf(\"failed to confirm knative crd registration after %v\", timeout)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *LocalTests) pollMachineState(c *gc.C, machineId, state string) bool {\n\tmachineConfig, err := s.testClient.GetMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n\treturn strings.EqualFold(machineConfig.State, state)\n}", "func (s *ServiceManager) Wait() (err error) {\n\tcases := s.buildSelectCases()\n\n\t// waits for the ServiceManager to confirm running state\n\t<-s.waitForRunning\n\t// waitForRunning will never be used again, discard memory\n\tclose(s.waitForRunning)\n\ts.waitForRunning = nil\n\n\trunning := true\n\tfor running {\n\t\t// chosen is the index of the selected case\n\t\t// recv is the value obtained, which will always be a SignalControl function\n\t\t// ok = false if the channel is closed\n\t\tchosen, recv, ok := reflect.Select(cases)\n\t\tif !ok {\n\t\t\t// not OK: channel was closed, remove from the list as we'll never receive any messages on it\n\t\t\t// It makes no sense to listen to it any more\n\t\t\tl := 0\n\t\t\ts.mu.Lock()\n\t\t\ts.removeSignaler(chosen)\n\t\t\tl = len(s.signalers)\n\t\t\ts.mu.Unlock()\n\t\t\tif l == 0 {\n\t\t\t\t// we're out of channels, stop the for loop\n\t\t\t\t// We'll need to wait for the server to end-itself. Closing channels does not stop the service,\n\t\t\t\t// but only the means of stopping that service\n\t\t\t\terr = <-s.waitForIteratorDone\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// we need to re-build the missing cases as now one is missing\n\t\t\tcases = s.buildSelectCases()\n\t\t\tcontinue\n\t\t}\n\n\t\t// Channel was not closed, we received a message\n\t\tswitch chanType := recv.Interface().(type) {\n\t\tcase SignalControl:\n\t\t\t// Our signal was OK, channel is not closed. Let's see what it says:\n\t\t\tswitch chanType(s) {\n\t\t\tcase GracefulRestart:\n\t\t\t\t// We need to gracefully restart\n\t\t\t\t// Trigger cancelling the context\n\t\t\t\t// We copy the value and set it to nil here to avoid having the inner go-routine call cancel a second time\n\t\t\t\ts.mu.Lock()\n\t\t\t\ts.state = StateRestarting\n\t\t\t\tif s.cancelFunc != nil {\n\t\t\t\t\ts.cancelFunc()\n\t\t\t\t\ts.cancelFunc = nil\n\t\t\t\t}\n\t\t\t\ts.mu.Unlock()\n\n\t\t\tcase GracefulStop:\n\t\t\t\t// We need to stop the service\n\t\t\t\trunning = false\n\n\t\t\t\ts.mu.Lock()\n\t\t\t\ts.state = StateDying\n\t\t\t\tif s.cancelFunc != nil {\n\t\t\t\t\ts.cancelFunc()\n\t\t\t\t\ts.cancelFunc = nil\n\t\t\t\t}\n\t\t\t\ts.mu.Unlock()\n\n\t\t\t\t// We're stopping, we need to wait for the goroutine to signal that it completed\n\t\t\t\terr = <-s.waitForIteratorDone\n\t\t\t}\n\t\tcase error:\n\t\t\t// This means our routine completed and is no longer running\n\t\t\trunning = false\n\t\t\ts.setState(StateDying)\n\n\t\t\t// The main service routine ended so we CANNOT wait for the goroutine to signal that it completed as it's already done\n\t\t\t// this also means that the context has already cleaned itself up, so no need to call s.cancelFunc\n\t\t\t// chanType could be nil, meaning no error\n\t\t\terr = chanType\n\n\t\t}\n\t}\n\n\t// Recover goroutine leak, if any\n\ts.cancelSignalers()\n\n\ts.setState(StateDead)\n\n\tclose(s.waitForIteratorDone)\n\n\treturn\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 (t *keepalivedService) InitMachine(node service.Node, client util.SSHClient, sctx *service.ServiceContext, deps service.ServiceDependencies, flags service.ServiceFlags) error {\n\tlog := deps.Logger.With().Str(\"host\", node.Name).Logger()\n\n\t// Setup controlplane on this host?\n\tif !node.IsControlPlane || flags.ControlPlane.APIServerVirtualIP == \"\" {\n\t\tlog.Info().Msg(\"No keepalived on this machine\")\n\t\treturn nil\n\t}\n\n\tcfg, err := t.createConfig(node, client, sctx, deps, flags)\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\n\t// Create & Upload keepalived.conf\n\tlog.Info().Msgf(\"Uploading %s Config\", t.Name())\n\tif err := createConfigFile(client, deps, cfg); err != nil {\n\t\treturn maskAny(err)\n\t}\n\tif err := createAPIServerCheck(client, deps, cfg); err != nil {\n\t\treturn maskAny(err)\n\t}\n\n\t// Restart keepalived\n\tif _, err := client.Run(log, \"sudo systemctl restart \"+serviceName, \"\", true); err != nil {\n\t\tlog.Warn().Err(err).Msg(\"Failed to restart keepalived server\")\n\t}\n\n\treturn nil\n}", "func WaitForClusterToTerminate(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) error {\n\tt.Logf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()}).String(),\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.CoreV1().Pods(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList, err := f.KubeClient.CoreV1().PersistentVolumeClaims(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Logf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitForCRDEstablishment(clientset apiextensionsclient.Interface) error {\n\treturn wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {\n\t\tsparkAppCrd, err := getCRD(clientset)\n\t\tfor _, cond := range sparkAppCrd.Status.Conditions {\n\t\t\tswitch cond.Type {\n\t\t\tcase apiextensionsv1beta1.Established:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\tcase apiextensionsv1beta1.NamesAccepted:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionFalse {\n\t\t\t\t\tfmt.Printf(\"Name conflict: %v\\n\", cond.Reason)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false, err\n\t})\n}", "func (vp *Pinnable) WaitForDiskLoad() {\n\tvp.Loader.Wait()\n}", "func (r clusterReconciler) controlPlaneMachineToCluster(ctx context.Context, o client.Object) []ctrl.Request {\n\tvsphereMachine, ok := o.(*infrav1.VSphereMachine)\n\tif !ok {\n\t\tr.Logger.Error(nil, fmt.Sprintf(\"expected a VSphereMachine but got a %T\", o))\n\t\treturn nil\n\t}\n\tif !infrautilv1.IsControlPlaneMachine(vsphereMachine) {\n\t\treturn nil\n\t}\n\tif len(vsphereMachine.Status.Addresses) == 0 {\n\t\treturn nil\n\t}\n\t// Get the VSphereMachine's preferred IP address.\n\tif _, err := infrautilv1.GetMachinePreferredIPAddress(vsphereMachine); err != nil {\n\t\tif err == infrautilv1.ErrNoMachineIPAddr {\n\t\t\treturn nil\n\t\t}\n\t\tr.Logger.Error(err, \"failed to get preferred IP address for VSphereMachine\",\n\t\t\t\"namespace\", vsphereMachine.Namespace, \"name\", vsphereMachine.Name)\n\t\treturn nil\n\t}\n\n\t// Fetch the CAPI Cluster.\n\tcluster, err := clusterutilv1.GetClusterFromMetadata(ctx, r.Client, vsphereMachine.ObjectMeta)\n\tif err != nil {\n\t\tr.Logger.Error(err, \"VSphereMachine is missing cluster label or cluster does not exist\",\n\t\t\t\"namespace\", vsphereMachine.Namespace, \"name\", vsphereMachine.Name)\n\t\treturn nil\n\t}\n\n\tif conditions.IsTrue(cluster, clusterv1.ControlPlaneInitializedCondition) {\n\t\treturn nil\n\t}\n\n\tif !cluster.Spec.ControlPlaneEndpoint.IsZero() {\n\t\treturn nil\n\t}\n\n\t// Fetch the VSphereCluster\n\tvsphereCluster := &infrav1.VSphereCluster{}\n\tvsphereClusterKey := client.ObjectKey{\n\t\tNamespace: vsphereMachine.Namespace,\n\t\tName: cluster.Spec.InfrastructureRef.Name,\n\t}\n\tif err := r.Client.Get(ctx, vsphereClusterKey, vsphereCluster); err != nil {\n\t\tr.Logger.Error(err, \"failed to get VSphereCluster\",\n\t\t\t\"namespace\", vsphereClusterKey.Namespace, \"name\", vsphereClusterKey.Name)\n\t\treturn nil\n\t}\n\n\tif !vsphereCluster.Spec.ControlPlaneEndpoint.IsZero() {\n\t\treturn nil\n\t}\n\n\treturn []ctrl.Request{{\n\t\tNamespacedName: types.NamespacedName{\n\t\t\tNamespace: vsphereClusterKey.Namespace,\n\t\t\tName: vsphereClusterKey.Name,\n\t\t},\n\t}}\n}", "func (f *Framework) WaitForVMToBeProcessing(vmiName string) error {\n\treturn f.WaitForVMImportConditionInStatus(2*time.Second, time.Minute, vmiName, v2vv1alpha1.Processing, corev1.ConditionTrue)\n}", "func (a *Actuator) Delete(c *clusterv1.Cluster, m *clusterv1.Machine) error {\n\tglog.Infof(\"Deleting machine %s for cluster %s.\", m.Name, c.Name)\n\n\tif a.machineSetupConfigGetter == nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"valid machineSetupConfigGetter is required\"), deleteEventAction)\n\t}\n\n\t// First get provider config\n\tmachineConfig, err := a.machineProviderConfig(m.Spec.ProviderConfig)\n\tif err != nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"Cannot unmarshal machine's providerConfig field: %v\", err), deleteEventAction)\n\t}\n\n\t// Now validate\n\tif err := a.validateMachine(m, machineConfig); err != nil {\n\t\treturn a.handleMachineError(m, err, deleteEventAction)\n\t}\n\n\t// Check if the machine exists (here we mean it is not bootstrapping.)\n\texists, err := a.Exists(c, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\tglog.Infof(\"Machine %s for cluster %s does not exists (maybe it is still bootstrapping), skipping.\", m.Name, c.Name)\n\t\treturn nil\n\t}\n\n\t// The exists case here.\n\tglog.Infof(\"Machine %s for cluster %s exists.\", m.Name, c.Name)\n\n\tconfigParams := &MachineParams{\n\t\tRoles: machineConfig.Roles,\n\t\tVersions: m.Spec.Versions,\n\t}\n\n\tmetadata, err := a.getMetadata(c, m, configParams, machineConfig.SSHConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Metadata retrieved: machine %s for cluster %s\", m.Name, c.Name)\n\n\tprivateKey, passPhrase, err := a.getPrivateKey(c, m.Namespace, machineConfig.SSHConfig.SecretName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Running shutdown script: machine %s for cluster %s...\", m.Name, c.Name)\n\n\tsshClient := ssh.NewSSHProviderClient(privateKey, passPhrase, machineConfig.SSHConfig)\n\n\tif err = sshClient.WriteFile(metadata.ShutdownScript, \"/var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"Error copying shutdown script: %v\", err)\n\t\treturn err\n\t}\n\n\tif err = sshClient.ProcessCMD(\"chmod +x /var/tmp/shutdownscript.sh && bash /var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"running shutdown script error: %v\", err)\n\t\treturn err\n\t}\n\n\ta.eventRecorder.Eventf(m, corev1.EventTypeNormal, \"Deleted\", \"Deleted Machine %v\", m.Name)\n\treturn nil\n}", "func Monitor() {\n\tfor {\n\t\tif container.State(container.Management) == container.Running {\n\t\t\tcommon.RunNRecover(server)\n\t\t} else {\n\t\t\tcommon.RunNRecover(client)\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func (s *EcsService) WaitForEcsInstance(instanceId string, status Status, timeout int) error {\n\tif timeout <= 0 {\n\t\ttimeout = DefaultTimeout\n\t}\n\tfor {\n\t\tinstance, err := s.DescribeInstance(instanceId)\n\t\tif err != nil && !NotFoundError(err) {\n\t\t\treturn err\n\t\t}\n\t\tif instance.Status == string(status) {\n\t\t\t//Sleep one more time for timing issues\n\t\t\ttime.Sleep(DefaultIntervalMedium * time.Second)\n\t\t\tbreak\n\t\t}\n\t\ttimeout = timeout - DefaultIntervalShort\n\t\tif timeout <= 0 {\n\t\t\treturn GetTimeErrorFromString(GetTimeoutMessage(\"ECS Instance\", string(status)))\n\t\t}\n\t\ttime.Sleep(DefaultIntervalShort * time.Second)\n\n\t}\n\treturn nil\n}", "func WaitForService(address string, logger *log.Logger) bool {\n\n\tfor i := 0; i < 12; i++ {\n\t\tconn, err := net.Dial(\"tcp\", address)\n\t\tif err != nil {\n\t\t\tlogger.Println(\"Connection error:\", err)\n\t\t} else {\n\t\t\tconn.Close()\n\t\t\tlogger.Println(fmt.Sprintf(\"Connected to %s\", address))\n\t\t\treturn true\n\t\t}\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\treturn false\n}", "func (vm *VirtualMachine) WaitUntilInState(client SkytapClient, desiredStates []string, requireStateChange bool) (*VirtualMachine, error) {\n\tr, err := WaitUntilInState(client, desiredStates, vm, requireStateChange)\n\tv := r.(*VirtualMachine)\n\treturn v, err\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func machineCommand(actionName string, host *host.Host, errorChan chan<- error) {\n\t// TODO: These actions should have their own type.\n\tcommands := map[string](func() error){\n\t\t\"configureAuth\": host.ConfigureAuth,\n\t\t\"start\": host.Start,\n\t\t\"stop\": host.Stop,\n\t\t\"restart\": host.Restart,\n\t\t\"kill\": host.Kill,\n\t\t\"upgrade\": host.Upgrade,\n\t\t\"ip\": printIP(host),\n\t}\n\n\tlog.Debugf(\"command=%s machine=%s\", actionName, host.Name)\n\n\tif err := commands[actionName](); err != nil {\n\t\terrorChan <- err\n\t\treturn\n\t}\n\n\terrorChan <- nil\n}", "func WaitForDeletion(ctx context.Context, mcpKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {\n\t\tmcp := &machineconfigv1.MachineConfigPool{}\n\t\tif err := testclient.Client.Get(ctx, mcpKey, mcp); apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func (c *Compute) wait(operation *compute.Operation) error {\n\tfor {\n\t\top, err := c.ZoneOperations.Get(c.Project, c.Zone, operation.Name).Do()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get operation: %v\", operation.Name, err)\n\t\t}\n\t\tlog.Printf(\"operation %q status: %s\", operation.Name, op.Status)\n\t\tif op.Status == \"DONE\" {\n\t\t\tif op.Error != nil {\n\t\t\t\treturn fmt.Errorf(\"operation error: %v\", *op.Error.Errors[0])\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn nil\n}", "func deviceSetUp(ctx context.Context, user, pass, p12Path string, key *rsa.PublicKey) (err error) {\n\tconst uiSetupTimeout = 90 * time.Second\n\n\ttesting.ContextLog(ctx, \"Restarting ui job\")\n\tsctx, cancel := context.WithTimeout(ctx, uiSetupTimeout)\n\tdefer cancel()\n\n\tif err = upstart.StopJob(sctx, \"ui\"); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t// In case of error, run EnsureJobRunning with the original\n\t\t// context to recover the job for the following tests.\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\t// Ignore error.\n\t\tupstart.EnsureJobRunning(ctx, \"ui\")\n\t}()\n\tif err = session.ClearDeviceOwnership(sctx); err != nil {\n\t\treturn err\n\t}\n\tif err = cryptohome.CreateVault(sctx, user, pass); err != nil {\n\t\treturn err\n\t}\n\tif err = createOwnerKey(sctx, user, p12Path, key); err != nil {\n\t\treturn err\n\t}\n\terr = upstart.EnsureJobRunning(sctx, \"ui\")\n\treturn\n}", "func (r *Reconciler) update() error {\n\tif err := validateMachine(*r.machine); err != nil {\n\t\treturn fmt.Errorf(\"%v: failed validating machine provider spec: %w\", r.machine.GetName(), err)\n\t}\n\n\tif r.providerStatus.TaskRef != \"\" {\n\t\tmoTask, err := r.session.GetTask(r.Context, r.providerStatus.TaskRef)\n\t\tif err != nil {\n\t\t\tif !isRetrieveMONotFound(r.providerStatus.TaskRef, err) {\n\t\t\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\t\t\tName: r.machine.Name,\n\t\t\t\t\tNamespace: r.machine.Namespace,\n\t\t\t\t\tReason: \"GetTask finished with error\",\n\t\t\t\t})\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif moTask != nil {\n\t\t\tif taskIsFinished, err := taskIsFinished(moTask); err != nil {\n\t\t\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\t\t\tName: r.machine.Name,\n\t\t\t\t\tNamespace: r.machine.Namespace,\n\t\t\t\t\tReason: \"Task finished with error\",\n\t\t\t\t})\n\t\t\t\treturn fmt.Errorf(\"%v task %v finished with error: %w\", moTask.Info.DescriptionId, moTask.Reference().Value, err)\n\t\t\t} else if !taskIsFinished {\n\t\t\t\treturn fmt.Errorf(\"%v task %v has not finished\", moTask.Info.DescriptionId, moTask.Reference().Value)\n\t\t\t}\n\t\t}\n\t}\n\n\tvmRef, err := findVM(r.machineScope)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"FindVM finished with error\",\n\t\t})\n\t\tif !isNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"vm not found on update: %w\", err)\n\t}\n\n\tvm := &virtualMachine{\n\t\tContext: r.machineScope.Context,\n\t\tObj: object.NewVirtualMachine(r.machineScope.session.Client.Client, vmRef),\n\t\tRef: vmRef,\n\t}\n\n\tif err := vm.reconcileTags(r.Context, r.session, r.machine); err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"ReconcileTags finished with error\",\n\t\t})\n\t\treturn fmt.Errorf(\"failed to reconcile tags: %w\", err)\n\t}\n\n\tif err := r.reconcileMachineWithCloudState(vm, r.providerStatus.TaskRef); err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"ReconcileWithCloudState finished with error\",\n\t\t})\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func WaitForZKClusterToTerminate(t *testing.T, k8client client.Client, z *zkapi.ZookeeperCluster) error {\n\tlog.Printf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(z.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitTerm() {\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\t<-signals\n}", "func (avisess *AviSession) CheckControllerStatus() (bool, *http.Response, error) {\n\turl := avisess.prefix + \"/api/cluster/status\"\n\tvar isControllerUp bool\n\tfor round := 0; round < avisess.ctrlStatusCheckRetryCount; round++ {\n\t\tcheckReq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"CheckControllerStatus Error %v while generating http request.\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\t//Getting response from controller's API\n\t\tif stateResp, err := avisess.client.Do(checkReq); err == nil {\n\t\t\tdefer stateResp.Body.Close()\n\t\t\t//Checking controller response\n\t\t\tif stateResp.StatusCode != 503 && stateResp.StatusCode != 502 && stateResp.StatusCode != 500 {\n\t\t\t\tisControllerUp = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tglog.Infof(\"CheckControllerStatus Error while generating http request %d %v\",\n\t\t\t\t\tstateResp.StatusCode, err)\n\t\t\t}\n\t\t} else {\n\t\t\tglog.Errorf(\"CheckControllerStatus Error while generating http request %v %v\", url, err)\n\t\t}\n\t\t// if controller status check interval is not set during client init, use the default SDK\n\t\t// behaviour.\n\t\tif avisess.ctrlStatusCheckRetryInterval == 0 {\n\t\t\ttime.Sleep(getMinTimeDuration((time.Duration(math.Exp(float64(round))*3) * time.Second), (time.Duration(30) * time.Second)))\n\t\t} else {\n\t\t\t// controller status will be polled at intervals specified during client init.\n\t\t\ttime.Sleep(time.Duration(avisess.ctrlStatusCheckRetryInterval) * time.Second)\n\t\t}\n\t\tglog.Errorf(\"CheckControllerStatus Controller %v Retrying. round %v..!\", url, round)\n\t}\n\treturn isControllerUp, &http.Response{Status: \"408 Request Timeout\", StatusCode: 408}, nil\n}", "func waitForCanclation(returnChn, abortWait, cancel chan bool, cmd *exec.Cmd) {\n\tselect {\n\tcase <-cancel:\n\t\tcmd.Process.Kill()\n\t\treturnChn <- true\n\tcase <-abortWait:\n\t}\n}", "func waitRun(contID string) error {\n\treturn daemon.WaitInspectWithArgs(dockerBinary, contID, \"{{.State.Running}}\", \"true\", 5*time.Second)\n}", "func waitForStart(server *Server) {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, _ := reader.ReadString('\\n')\n\tfmt.Println(\"IS start exec :: \", text)\n\tserver.executor.summary.startTime = time.Now().UnixNano()\n\tif text == \"start\\n\" {\n\t\tcmd := pb.ExecutionCommand{\n\t\t\tType: startExec,\n\t\t}\n\t\tfor clinetID := range server.clientStreams {\n\t\t\tserver.sendCommand(clinetID, &cmd)\n\t\t}\n\t}\n}", "func (m *Manager) WaitUntilRunning() {\n\tfor {\n\t\tm.mu.Lock()\n\n\t\tif m.ctx != nil {\n\t\t\tm.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tstarted := m.started\n\t\tm.mu.Unlock()\n\n\t\t// Block until we have been started.\n\t\t<-started\n\t}\n}", "func (monitor *controllerMonitor) Run(stopCh <-chan struct{}) {\n\tklog.Info(\"Starting Antrea Controller Monitor\")\n\tcontrollerCRD := monitor.getControllerCRD()\n\tvar err error = nil\n\tfor {\n\t\tif controllerCRD == nil {\n\t\t\tcontrollerCRD, err = monitor.createControllerCRD()\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to create controller monitoring CRD %v : %v\", controllerCRD, err)\n\t\t\t}\n\t\t} else {\n\t\t\tcontrollerCRD, err = monitor.updateControllerCRD(controllerCRD)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to update controller monitoring CRD %v : %v\", controllerCRD, err)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(60 * time.Second)\n\t}\n\t<-stopCh\n}", "func (s *service) waitForExit(cmd *exec.Cmd) {\n\tif err := cmd.Wait(); err != nil {\n\t\tlogrus.Debugf(\"Envoy terminated: %v\", err.Error())\n\t} else {\n\t\tlogrus.Debug(\"Envoy process exited\")\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tdelete(s.cmdMap, cmd)\n}" ]
[ "0.6205696", "0.59781384", "0.5872165", "0.57533246", "0.55674094", "0.5406494", "0.5349306", "0.53339887", "0.5305528", "0.52262676", "0.5192839", "0.5190781", "0.5143582", "0.51317656", "0.51000625", "0.5088618", "0.5088441", "0.50841904", "0.50794375", "0.5047249", "0.5038419", "0.5022287", "0.50213796", "0.5021335", "0.49914318", "0.4971571", "0.49654624", "0.49598977", "0.49256894", "0.49251145", "0.49142373", "0.49043137", "0.49011794", "0.48972362", "0.48959342", "0.48815775", "0.48780358", "0.48753121", "0.48709854", "0.47951576", "0.478834", "0.4786452", "0.47605163", "0.4760398", "0.47594568", "0.47584164", "0.4749738", "0.47480434", "0.4739915", "0.47296783", "0.47253802", "0.47208923", "0.47125015", "0.47111455", "0.4686496", "0.46852222", "0.46783885", "0.46695852", "0.4660244", "0.46586442", "0.465318", "0.4651734", "0.4646618", "0.4644959", "0.46425438", "0.4642191", "0.46369225", "0.46344405", "0.4616925", "0.46164346", "0.46106884", "0.46068853", "0.4588287", "0.45811284", "0.4574711", "0.45721564", "0.45679966", "0.45665905", "0.4556364", "0.45547473", "0.45413214", "0.4537627", "0.4530127", "0.45296282", "0.452934", "0.45228323", "0.45186418", "0.45185494", "0.4518417", "0.4511832", "0.45113492", "0.4500638", "0.44912755", "0.4490125", "0.44884044", "0.4486715", "0.4482242", "0.4472711", "0.44716763", "0.44629666" ]
0.79245347
0
waitForWebhook waits for machinecontrollerwebhook to become running
waitForWebhook ожидает, пока machinecontrollerwebhook станет запущенным
func waitForWebhook(ctx context.Context, client dynclient.Client) error { condFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{ Namespace: resources.MachineControllerNameSpace, LabelSelector: labels.SelectorFromSet(map[string]string{ appLabelKey: resources.MachineControllerWebhookName, }), }) return fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), "waiting for machine-controller webhook to became ready") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func waitFor(ctx context.Context, eventName string) error {\n\tch := make(chan struct{})\n\tcctx, cancel := context.WithCancel(ctx)\n\tchromedp.ListenTarget(cctx, func(ev interface{}) {\n\t\tswitch e := ev.(type) {\n\t\tcase *page.EventLifecycleEvent:\n\t\t\tif e.Name == eventName {\n\t\t\t\tcancel()\n\t\t\t\tclose(ch)\n\t\t\t}\n\t\t}\n\t})\n\tselect {\n\tcase <-ch:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n}", "func waitForAPI(ctx context.Context, client *gophercloud.ServiceClient) {\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\t// NOTE: Some versions of Ironic inspector returns 404 for /v1/ but 200 for /v1,\n\t// which seems to be the default behavior for Flask. Remove the trailing slash\n\t// from the client endpoint.\n\tendpoint := strings.TrimSuffix(client.Endpoint, \"/\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for API to become available...\")\n\n\t\t\tr, err := httpClient.Get(endpoint)\n\t\t\tif err == nil {\n\t\t\t\tstatusCode := r.StatusCode\n\t\t\t\tr.Body.Close()\n\t\t\t\tif statusCode == http.StatusOK {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func ensureVWHReady(){\n\tMustRunWithTimeout(certsReadyTime, \"kubectl create ns check-webhook\")\n\tMustRun(\"kubectl delete ns check-webhook\")\n}", "func waitWebhookConfigurationReady(f *framework.Framework, namespace string) error {\n\tcmClient := f.VclusterClient.CoreV1().ConfigMaps(namespace + \"-markers\")\n\treturn wait.PollUntilContextTimeout(f.Context, 100*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\tmarker := &corev1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: string(uuid.NewUUID()),\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tuniqueName: \"true\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t_, err := cmClient.Create(ctx, marker, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\t// The always-deny webhook does not provide a reason, so check for the error string we expect\n\t\t\tif strings.Contains(err.Error(), \"denied\") {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\t// best effort cleanup of markers that are no longer needed\n\t\t_ = cmClient.Delete(ctx, marker.GetName(), metav1.DeleteOptions{})\n\t\tf.Log.Infof(\"Waiting for webhook configuration to be ready...\")\n\t\treturn false, nil\n\t})\n}", "func waitForMachineController(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller to became ready\")\n}", "func (mod *Module)WaitTillStartupDone(){\n\tfor mod.hasRunStartup == false{//wait for startup to stop running\n\t\ttime.Sleep(time.Millisecond*10)\n\t}\n}", "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func Run(ctx context.Context, mgr manager.Manager, handlerMap map[string]admission.Handler) error {\n\tif err := mgr.AddReadyzCheck(\"webhook-ready\", health.Checker); err != nil {\n\t\treturn fmt.Errorf(\"unable to add readyz check\")\n\t}\n\n\tc, err := webhookcontroller.New(mgr.GetConfig(), handlerMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tc.Start(ctx)\n\t}()\n\n\ttimer := time.NewTimer(time.Second * 20)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-webhookcontroller.Inited():\n\t\treturn waitReady()\n\tcase <-timer.C:\n\t\treturn fmt.Errorf(\"failed to start webhook controller for waiting more than 5s\")\n\t}\n\n\tserver := mgr.GetWebhookServer()\n\tserver.Host = \"0.0.0.0\"\n\tserver.Port = webhookutil.GetPort()\n\tserver.CertDir = webhookutil.GetCertDir()\n\treturn nil\n}", "func (bot *Bot) startWebhook() (err error) {\n\terr = bot.createServer()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"startWebhook: %w\", err)\n\t}\n\n\tbot.err = make(chan error)\n\n\tgo func() {\n\t\tbot.err <- bot.webhook.Start()\n\t}()\n\n\terr = bot.DeleteWebhook()\n\tif err != nil {\n\t\tlog.Println(\"startWebhook:\", err.Error())\n\t}\n\n\terr = bot.setWebhook()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"startWebhook: %w\", err)\n\t}\n\n\treturn <-bot.err\n}", "func (wh *Webhook) Run(stop <-chan struct{}) error {\n\tlogger := wh.Logger\n\tctx := logging.WithLogger(context.Background(), logger)\n\n\tdrainer := &handlers.Drainer{\n\t\tInner: wh,\n\t\tQuietPeriod: wh.Options.GracePeriod,\n\t}\n\n\tserver := &http.Server{\n\t\tErrorLog: log.New(&zapWrapper{logger}, \"\", 0),\n\t\tHandler: drainer,\n\t\tAddr: fmt.Sprint(\":\", wh.Options.Port),\n\t\tTLSConfig: wh.tlsConfig,\n\t\tReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6\n\t}\n\n\tvar serve = server.ListenAndServe\n\n\tif server.TLSConfig != nil && wh.testListener != nil {\n\t\tserve = func() error {\n\t\t\treturn server.ServeTLS(wh.testListener, \"\", \"\")\n\t\t}\n\t} else if server.TLSConfig != nil {\n\t\tserve = func() error {\n\t\t\treturn server.ListenAndServeTLS(\"\", \"\")\n\t\t}\n\t} else if wh.testListener != nil {\n\t\tserve = func() error {\n\t\t\treturn server.Serve(wh.testListener)\n\t\t}\n\t}\n\n\teg, ctx := errgroup.WithContext(ctx)\n\teg.Go(func() error {\n\t\tif err := serve(); err != nil && !errors.Is(err, http.ErrServerClosed) {\n\t\t\tlogger.Errorw(\"ListenAndServe for admission webhook returned error\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\n\tselect {\n\tcase <-stop:\n\t\teg.Go(func() error {\n\t\t\t// As we start to shutdown, disable keep-alives to avoid clients hanging onto connections.\n\t\t\tserver.SetKeepAlivesEnabled(false)\n\n\t\t\t// Start failing readiness probes immediately.\n\t\t\tlogger.Info(\"Starting to fail readiness probes...\")\n\t\t\tdrainer.Drain()\n\n\t\t\treturn server.Shutdown(context.Background())\n\t\t})\n\n\t\t// Wait for all outstanding go routined to terminate, including our new one.\n\t\treturn eg.Wait()\n\n\tcase <-ctx.Done():\n\t\treturn fmt.Errorf(\"webhook server bootstrap failed %w\", ctx.Err())\n\t}\n}", "func waitForEvent(t *testing.T, wsc *client.WSClient, eventid string, dieOnTimeout bool, f func(), check func(string, interface{}) error) {\n\t// go routine to wait for webscoket msg\n\tgoodCh := make(chan interface{})\n\terrCh := make(chan error)\n\n\t// Read message\n\tgo func() {\n\t\tvar err error\n\tLOOP:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase r := <-wsc.ResultsCh:\n\t\t\t\tresult := new(ctypes.TMResult)\n\t\t\t\twire.ReadJSONPtr(result, r, &err)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrCh <- err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\t\t\t\tevent, ok := (*result).(*ctypes.ResultEvent)\n\t\t\t\tif ok && event.Name == eventid {\n\t\t\t\t\tgoodCh <- event.Data\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\t\t\tcase err := <-wsc.ErrorsCh:\n\t\t\t\terrCh <- err\n\t\t\t\tbreak LOOP\n\t\t\tcase <-wsc.Quit:\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t}\n\t}()\n\n\t// do stuff (transactions)\n\tf()\n\n\t// wait for an event or timeout\n\ttimeout := time.NewTimer(10 * time.Second)\n\tselect {\n\tcase <-timeout.C:\n\t\tif dieOnTimeout {\n\t\t\twsc.Stop()\n\t\t\tpanic(Fmt(\"%s event was not received in time\", eventid))\n\t\t}\n\t\t// else that's great, we didn't hear the event\n\t\t// and we shouldn't have\n\tcase eventData := <-goodCh:\n\t\tif dieOnTimeout {\n\t\t\t// message was received and expected\n\t\t\t// run the check\n\t\t\tif err := check(eventid, eventData); err != nil {\n\t\t\t\tpanic(err) // Show the stack trace.\n\t\t\t}\n\t\t} else {\n\t\t\twsc.Stop()\n\t\t\tpanic(Fmt(\"%s event was not expected\", eventid))\n\t\t}\n\tcase err := <-errCh:\n\t\tpanic(err) // Show the stack trace.\n\n\t}\n}", "func (c *Config) waitForFlannelFile(newLogger micrologger.Logger) error {\n\t// wait for file creation\n\tfor count := 0; ; count++ {\n\t\t// don't wait forever, if file is not created within retry limit, exit with failure\n\t\tif count > MaxRetry {\n\t\t\treturn microerror.Maskf(invalidFlannelFileError, \"After 100sec flannel file is not created. Exiting\")\n\t\t}\n\t\t// check if file exists\n\t\tif _, err := os.Stat(c.Flag.Service.FlannelFile); !os.IsNotExist(err) {\n\t\t\tbreak\n\t\t}\n\t\t_ = newLogger.Log(\"debug\", fmt.Sprintf(\"Waiting for file '%s' to be created.\", c.Flag.Service.FlannelFile))\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\t// all good\n\treturn nil\n}", "func waitForMachineState(api *cloudapi.Client, id, state string, timeout time.Duration) error {\n\treturn waitFor(\n\t\tfunc() (bool, error) {\n\t\t\tcurrentState, err := readMachineState(api, id)\n\t\t\treturn currentState == state, err\n\t\t},\n\t\tmachineStateChangeCheckInterval,\n\t\tmachineStateChangeTimeout,\n\t)\n}", "func waitForHelmRunning(ctx context.Context, configPath string) error {\n\tfor {\n\t\tcmd := exec.Command(\"helm\", \"ls\", \"--kubeconfig\", configPath)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stderr = &out\n\t\tcmd.Run()\n\t\tif out.String() == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.Wrap(ctx.Err(), \"timed out waiting for helm to become ready\")\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t}\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 triggerOnChaosHTTPProbe(probe v1alpha1.ProbeAttributes, clients clients.ClientSets, chaosresult *types.ResultDetails, chaosDetails *types.ChaosDetails) {\n\n\tvar isExperimentFailed bool\n\tduration := chaosDetails.ChaosDuration\n\t// waiting for initial delay\n\tif probe.RunProperties.InitialDelaySeconds != 0 {\n\t\tlog.Infof(\"[Wait]: Waiting for %vs before probe execution\", probe.RunProperties.InitialDelaySeconds)\n\t\ttime.Sleep(time.Duration(probe.RunProperties.InitialDelaySeconds) * time.Second)\n\t\tduration = math.Maximum(0, duration-probe.RunProperties.InitialDelaySeconds)\n\t}\n\n\tvar endTime <-chan time.Time\n\ttimeDelay := time.Duration(duration) * time.Second\n\n\t// it trigger the http probe for the entire duration of chaos and it fails, if any error encounter\n\t// it marked the error for the probes, if any\nloop:\n\tfor {\n\t\tendTime = time.After(timeDelay)\n\t\tselect {\n\t\tcase <-endTime:\n\t\t\tlog.Infof(\"[Chaos]: Time is up for the %v probe\", probe.Name)\n\t\t\tendTime = nil\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\terr = triggerHTTPProbe(probe, chaosresult)\n\t\t\t// record the error inside the probeDetails, we are maintaining a dedicated variable for the err, inside probeDetails\n\t\t\tif err != nil {\n\t\t\t\tfor index := range chaosresult.ProbeDetails {\n\t\t\t\t\tif chaosresult.ProbeDetails[index].Name == probe.Name {\n\t\t\t\t\t\tchaosresult.ProbeDetails[index].IsProbeFailedWithError = err\n\t\t\t\t\t\tisExperimentFailed = true\n\t\t\t\t\t\tbreak loop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// waiting for the probe polling interval\n\t\t\ttime.Sleep(time.Duration(probe.RunProperties.ProbePollingInterval) * time.Second)\n\t\t}\n\t}\n\t// if experiment fails and stopOnfailure is provided as true then it will patch the chaosengine for abort\n\t// if experiment fails but stopOnfailure is provided as false then it will continue the execution\n\t// and failed the experiment in the end\n\tif isExperimentFailed && probe.RunProperties.StopOnFailure {\n\t\tif err := stopChaosEngine(probe, clients, chaosresult, chaosDetails); err != nil {\n\t\t\tlog.Errorf(\"unable to patch chaosengine to stop, err: %v\", err)\n\t\t}\n\t}\n}", "func (st *AKSAddonPreflightStep) Execute(_ context.Context, _ []string, log logr.Logger) {\n\tconst (\n\t\tnamespace = \"kube-system\"\n\t\tname = \"preflight\"\n\t)\n\tvar err error\n\n\tlog.Info(\"start\")\n\n\tst.update(v1.StateRunning, \"check api-server connection\")\n\n\t// Remove possible leftover probe pod.\n\ts, _ := st.Kubectl.PodState(st.KCPath, namespace, name)\n\tif s != \"\" {\n\t\t// Pod already present, delete it\n\t\terr = st.Kubectl.PodDelete(st.KCPath, namespace, name)\n\t\tif err != nil {\n\t\t\tst.error2(err, \"delete pod\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Run probe.\n\t// TODO parameterize image (consider using envop config for this)\n\terr = st.Kubectl.PodRun(st.KCPath, namespace, name, \"docker.io/curlimages/curl:7.72.0\",\n\t\t\"until curl -ksS --max-time 2 https://kubernetes.default | grep Status ; do date -Iseconds; sleep 5 ; done\")\n\tif err != nil {\n\t\tst.error2(err, \"run pod\")\n\t\treturn\n\t}\n\t// Check for completion.\n\ts = \"\"\n\tend := time.Now().Add(time.Minute)\n\tfor exp := backoff.NewExponential(10 * time.Second); !time.Now().After(end); exp.Sleep() {\n\t\ts, err = st.Kubectl.PodState(st.KCPath, namespace, name)\n\t\t// err is included in Msg below\n\t\tif s == \"PodCompleted\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif s != \"PodCompleted\" {\n\t\t// Return with state Running so this step gets picked up again.\n\t\tvar errMsg string\n\t\tif err != nil {\n\t\t\terrMsg = fmt.Sprintf(\": %s\", err.Error())\n\t\t} else {\n\t\t\terrMsg = fmt.Sprintf(\": %s\", s)\n\t\t}\n\t\tst.update(v1.StateRunning, fmt.Sprintf(\"waiting for %s pod completion%s\", name, errMsg))\n\t\treturn\n\t}\n\n\tst.update(v1.StateReady, fmt.Sprintf(\"%s completed\", name))\n}", "func main() {\n\tc, err := client.Dial(client.Options{\n\t\tHostPort: client.DefaultHostPort,\n\t})\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to create client\", err)\n\t}\n\tdefer c.Close()\n\n\tworkflowOptions := client.StartWorkflowOptions{\n\t\tID: updatabletimer.WorkflowID,\n\t\tTaskQueue: updatabletimer.TaskQueue,\n\t}\n\n\twakeUpTime := time.Now().Add(30 * time.Second)\n\twe, err := c.ExecuteWorkflow(context.Background(), workflowOptions, updatabletimer.Workflow, wakeUpTime)\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to start workflow\", err)\n\t}\n\tlog.Println(\"Started workflow that is going to block on an updatable timer\",\n\t\t\"WorkflowID\", we.GetID(), \"RunID\", we.GetRunID(), \"WakeUpTime\", wakeUpTime)\n}", "func waitForDeployment(getDeploymentFunc func() (*appsv1.Deployment, error), interval, timeout time.Duration) error {\n\treturn wait.PollImmediate(interval, timeout, func() (bool, error) {\n\t\tdeployment, err := getDeploymentFunc()\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\tframework.Logf(\"deployment not found, continue waiting: %s\", err)\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tframework.Logf(\"error while deploying, error %s\", err)\n\t\t\treturn false, err\n\t\t}\n\t\tframework.Logf(\"deployment status %s\", &deployment.Status)\n\t\treturn util.DeploymentComplete(deployment, &deployment.Status), nil\n\t})\n}", "func waitForDeployToProcess(currentVersion time.Time, name, ip string) bool {\n\tebo := backoff.NewExponentialBackOff()\n\tebo.MaxElapsedTime = 10 * time.Second\n\tdeployError := backoff.Retry(safe.OperationWithRecover(func() error {\n\t\t// Configuration should have deployed successfully, confirm version match.\n\t\tnewVersion, exists, newErr := getDeployedVersion(ip)\n\t\tif newErr != nil {\n\t\t\treturn fmt.Errorf(\"could not get newly deployed configuration version: %v\", newErr)\n\t\t}\n\t\tif exists {\n\t\t\tif currentVersion.Equal(newVersion) {\n\t\t\t\t// The version we are trying to deploy is confirmed.\n\t\t\t\t// Return nil, to break out of the ebo.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"deployment was not successful\")\n\t}), ebo)\n\n\tif deployError == nil {\n\t\t// The version we are trying to deploy is confirmed.\n\t\t// Return true, so that it will be removed from the deploy queue.\n\t\tlog.Debugf(\"Successfully deployed version for pod %s: %s\", name, currentVersion)\n\t\treturn true\n\t}\n\treturn false\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n\tlog.Printf(\"[TEST] thats all folks\")\n}", "func main() {\n\tvar parameters WhSvrParameters\n\n\t// get command line parameters\n\tflag.IntVar(&parameters.port, \"port\", 8443, \"Webhook server port.\")\n\tflag.StringVar(&parameters.certFile, \"tlsCertFile\", \"/etc/admissioner/certs/cert.pem\", \"File containing the x509 Certificate for HTTPS.\")\n\tflag.StringVar(&parameters.keyFile, \"tlsKeyFile\", \"/etc/admissioner/certs/key.pem\", \"File containing the x509 private key to --tlsCertFile.\")\n\tflag.Parse()\n\n\tpair, err := tls.LoadX509KeyPair(parameters.certFile, parameters.keyFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcert, err := x509.ParseCertificate(pair.Certificate[0])\n\tctx := context.WithValue(context.Background(), CtxCert, cert)\n\n\twhsvr := &WebhookServer{\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%v\", parameters.port),\n\t\t\tTLSConfig: &tls.Config{Certificates: []tls.Certificate{pair}},\n\t\t\tBaseContext: func(listener net.Listener) context.Context {\n\t\t\t\treturn ctx\n\t\t\t},\n\t\t},\n\t}\n\n\t// define http server and server handler\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/mutate\", whsvr.serve)\n\twhsvr.server.Handler = mux\n\n\t// start webhook server in new routine\n\tgo func() {\n\t\tif err := whsvr.server.ListenAndServeTLS(\"\", \"\"); err != nil {\n\t\t\tglog.Errorf(\"Failed to listen and serve webhook server: %v\", err)\n\t\t}\n\t}()\n\n\tglog.Info(\"Server started\")\n\n\t// listening OS shutdown singal\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)\n\t<-signalChan\n\n\tglog.Infof(\"Got OS shutdown signal, shutting down webhook server gracefully...\")\n\twhsvr.server.Shutdown(context.Background())\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func WaitForStopEvent(bc BackgroundContext, w WaitForStopEventConfiguration) {\n\tfor {\n\t\tselect {\n\t\tcase stopEvent := <-bc.Stop:\n\t\t\thandleStopEvent(stopEvent, bc, w)\n\t\t\treturn\n\t\tdefault:\n\t\t\tw.OnWait(bc, w)\n\t\t}\n\t\ttime.Sleep(w.WaitTime)\n\t}\n}", "func (m *Manager) WaitUntilRunning() {\n\tfor {\n\t\tm.mu.Lock()\n\n\t\tif m.ctx != nil {\n\t\t\tm.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tstarted := m.started\n\t\tm.mu.Unlock()\n\n\t\t// Block until we have been started.\n\t\t<-started\n\t}\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.Queue.ShutDown()\n\tlog.Debug(\"pgcluster Contoller: received stop signal, worker queue told to shutdown\")\n}", "func TestRequestStopFromMovingUp(t *testing.T) {\n\t// setup\n\tdwController := setup(t, 2, Up, []common.PiPin{common.OpenerStop})\n\n\t// test\n\tdwController.SetStopRequested() // send the stop request\n\twaitForStatus(t, 2, 2, Stopped, dwController, 3*time.Second) // verify that the dumbwaiter is now stopped\n}", "func (s *SourceControl) WaitForStopTestingOnly(dummy *string, reply *bool) error {\n\tfor s.isSourceActive {\n\t\ts.handlePossibleStoppedSource()\n\t\ttime.Sleep(1 * time.Millisecond)\n\t}\n\treturn nil\n}", "func Wait(dev *model.Dev, okStatusList []config.UpState) error {\n\toktetoLog.Spinner(\"Activating your development container...\")\n\toktetoLog.StartSpinner()\n\tdefer oktetoLog.StopSpinner()\n\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\texit := make(chan error, 1)\n\n\tgo func() {\n\n\t\tticker := time.NewTicker(500 * time.Millisecond)\n\t\tfor {\n\t\t\tstatus, err := config.GetState(dev.Name, dev.Namespace)\n\t\t\tif err != nil {\n\t\t\t\texit <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif status == config.Failed {\n\t\t\t\texit <- fmt.Errorf(\"your development container has failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, okStatus := range okStatusList {\n\t\t\t\tif status == okStatus {\n\t\t\t\t\texit <- nil\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\toktetoLog.Infof(\"CTRL+C received, starting shutdown sequence\")\n\t\toktetoLog.StopSpinner()\n\t\treturn oktetoErrors.ErrIntSig\n\tcase err := <-exit:\n\t\tif err != nil {\n\t\t\toktetoLog.Infof(\"exit signal received due to error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func waitForWatchListener(ctx context.Context, t *testing.T, xdsC *fakeclient.Client, wantTarget string) {\n\tt.Helper()\n\n\tgotTarget, err := xdsC.WaitForWatchListener(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchService failed with error: %v\", err)\n\t}\n\tif gotTarget != wantTarget {\n\t\tt.Fatalf(\"xdsClient.WatchService() called with target: %v, want %v\", gotTarget, wantTarget)\n\t}\n}", "func (s *service) serviceResponseCheckLoop() {\n\tgo func() {\n\t\tfor {\n\n\t\t\tfor s.connection == nil || !s.connected {\n\t\t\t\ttime.Sleep(5 * 1E9) // We have time for the feedback loop, let's just wait\n\t\t\t}\n\n\t\t\t// Check service response for returned errors\n\t\t\tvar status uint8\n\t\t\tvar identifier uint32\n\t\t\tif s.queue.Env != Test {\n\t\t\t\tstatus, identifier = checkServiceResponse(s.connection)\n\t\t\t} else {\n\t\t\t\t// For testing purposes\n\t\t\t\tstatus, identifier = checkServiceResponse(bytes.NewBuffer([]byte{}))\n\t\t\t}\n\n\t\t\ts.handleServiceError(status, identifier)\n\t\t}\n\t}()\n}", "func waitForGlusterContainer() error {\n\n\t//Check if docker gluster container is up and running\n\tfor {\n\t\tglusterServerContainerVal, err := helpers.GetSystemDockerNode(\"gluster-server\")\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error in checking docker gluster container for status \", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tif len(glusterServerContainerVal) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\trwolog.Debug(\"Sleeping for 10 seconds to get gluster docker container up\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func waitForShutdown(ctx context.Context, srv *http.Server,\n\tlog *zap.SugaredLogger) {\n\tinterruptChan := make(chan os.Signal, 1)\n\tsignal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n\t// Block until we receive our signal.\n\tsig := <-interruptChan\n\tlog.Debugw(\"Termination signal received\", \"signal\", sig)\n\n\t// Create a deadline to wait for.\n\tctx, cancel := context.WithTimeout(ctx, time.Second*10)\n\tdefer cancel()\n\tsrv.Shutdown(ctx)\n\n\tlog.Infof(\"Shutting down\")\n}", "func WaitForChromeVoxStopSpeaking(ctx context.Context, chromeVoxConn *chrome.Conn) error {\n\tif err := testing.Poll(ctx, func(ctx context.Context) error {\n\t\tvar isSpeaking bool\n\t\tif err := chromeVoxConn.Eval(ctx, \"cvox.ChromeVox.tts.isSpeaking()\", &isSpeaking); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif isSpeaking {\n\t\t\treturn errors.New(\"ChromeVox is speaking\")\n\t\t}\n\t\treturn nil\n\t}, &testing.PollOptions{Timeout: 30 * time.Second}); err != nil {\n\t\treturn errors.Wrap(err, \"timed out waiting for ChromeVox to finish speaking\")\n\t}\n\treturn nil\n}", "func WaitForNotify() {\n\tcount++\n\t<-done\n}", "func (d *conntrackInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func (b *Bot) WaitForHalt() {\n\tb.msgDispatchers.Wait()\n\tb.dispatcher.WaitForCompletion()\n\tb.serversProtect.RLock()\n\tfor _, srv := range b.servers {\n\t\tsrv.dispatcher.WaitForCompletion()\n\t}\n\tb.serversProtect.RUnlock()\n}", "func (p Plugin) Webhook() error {\n\treadyToListen := false\n\tbot, err := p.Bot()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tmux := p.Handler(bot)\n\n\tif p.Config.Tunnel {\n\t\tif p.Config.Debug {\n\t\t\tgotunnelme.Debug = true\n\t\t}\n\n\t\tdomain, err := p.getTunnelDomain()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\ttunnel := gotunnelme.NewTunnel()\n\t\turl, err := tunnel.GetUrl(domain)\n\t\tif err != nil {\n\t\t\tpanic(\"Could not get localtunnel.me URL. \" + err.Error())\n\t\t}\n\t\tgo func() {\n\t\t\tfor !readyToListen {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\t\t\tc := color.New(color.FgYellow)\n\t\t\tc.Println(\"Tunnel URL:\", url)\n\t\t\terr := tunnel.CreateTunnel(p.Config.Port)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"Could not create tunnel. \" + err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\treadyToListen = true\n\tif p.Config.Port != 443 && !p.Config.AutoTLS {\n\t\tlog.Println(\"Line Webhook Server Listin on \" + strconv.Itoa(p.Config.Port) + \" port\")\n\t\tif err := http.ListenAndServe(\":\"+strconv.Itoa(p.Config.Port), mux); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tif p.Config.AutoTLS && len(p.Config.Host) != 0 {\n\t\tlog.Println(\"Line Webhook Server Listin on 443 port, hostname: \" + strings.Join(p.Config.Host, \", \"))\n\t\treturn http.Serve(autocert.NewListener(p.Config.Host...), mux)\n\t}\n\n\treturn nil\n}", "func waitForRunning(s drmaa.Session, jobId string, hostCh chan string) {\n\t// Wait for running job\n\td, _ := time.ParseDuration(\"500ms\")\n\tps, _ := s.JobPs(jobId)\n\tfor ps != drmaa.PsRunning {\n\t\ttime.Sleep(d)\n\t\tps, _ = s.JobPs(jobId)\n\t}\n\n\t// Get hostname\n\tjobStatus, err := gestatus.GetJobStatus(&s, jobId)\n\tif err != nil {\n\t\tfmt.Printf(\"Error in getting hostname for job %s: %s\\n\", jobId, err.Error())\n\t\thostCh <- \"\"\n\t\treturn\n\t}\n\thostname := jobStatus.DestinationHostList()\n\thostCh <- strings.Join(hostname, \"\")\n}", "func (tfcm *TestFCM) wait(count int) {\n\ttime.Sleep(time.Duration(count) * tfcm.timeout)\n}", "func waitForShutdown() {\n\tsigint := make(chan os.Signal, 1)\n\t// syscall.SIGTERM is not pressent on all plattforms. Since the autoupdate\n\t// service is only run on linux, this is ok. If other plattforms should be\n\t// supported, os.Interrupt should be used instead.\n\tsignal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigint\n\tgo func() {\n\t\t<-sigint\n\t\tos.Exit(1)\n\t}()\n}", "func waitForShutdown() {\n\tsigint := make(chan os.Signal, 1)\n\t// syscall.SIGTERM is not pressent on all plattforms. Since the autoupdate\n\t// service is only run on linux, this is ok. If other plattforms should be\n\t// supported, os.Interrupt should be used instead.\n\tsignal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigint\n\tgo func() {\n\t\t<-sigint\n\t\tos.Exit(1)\n\t}()\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func (c *Client) doWaitForStatus(eniID string, checkNum, checkInterval int, finalStatus string) error {\n\tfor i := 0; i < checkNum; i++ {\n\t\ttime.Sleep(time.Second * time.Duration(checkInterval))\n\t\tenis, err := c.queryENI(eniID, \"\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, eni := range enis {\n\t\t\tif *eni.NetworkInterfaceId == eniID {\n\t\t\t\tswitch *eni.State {\n\t\t\t\tcase ENI_STATUS_AVAILABLE:\n\t\t\t\t\tswitch finalStatus {\n\t\t\t\t\tcase ENI_STATUS_ATTACHED:\n\t\t\t\t\t\tif eni.Attachment != nil && eni.Attachment.InstanceId != nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is attached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not attached\", eniID)\n\t\t\t\t\tcase ENI_STATUS_DETACHED:\n\t\t\t\t\t\tif eni.Attachment == nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is detached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not detached\", eniID)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tblog.Infof(\"eni %s is %s now\", eniID, *eni.State)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase ENI_STATUS_PENDING, ENI_STATUS_ATTACHING, ENI_STATUS_DETACHING, ENI_STATUS_DELETING:\n\t\t\t\t\tblog.Infof(\"eni %s is %s\", eniID, *eni.State)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tblog.Errorf(\"timeout when wait for eni %s\", eniID)\n\treturn fmt.Errorf(\"timeout when wait for eni %s\", eniID)\n}", "func (app *Application) runAndWaitForShutdownEvent() {\n\tapp.logger.Info(\"Everything is ready. Begin running and processing data.\")\n\n\t// Plug SIGTERM signal into a channel.\n\tsignalsChannel := make(chan os.Signal, 1)\n\tsignal.Notify(signalsChannel, os.Interrupt, syscall.SIGTERM)\n\n\t// set the channel to stop testing.\n\tapp.stopTestChan = make(chan struct{})\n\t// notify tests that it is ready.\n\tclose(app.readyChan)\n\n\tselect {\n\tcase err := <-app.asyncErrorChannel:\n\t\tapp.logger.Error(\"Asynchronous error received, terminating process\", zap.Error(err))\n\tcase s := <-signalsChannel:\n\t\tapp.logger.Info(\"Received signal from OS\", zap.String(\"signal\", s.String()))\n\tcase <-app.stopTestChan:\n\t\tapp.logger.Info(\"Received stop test request\")\n\t}\n}", "func main() {\n\trand.Seed(time.Now().UnixNano())\n\n\tvar conf DaemonConf\n\tconf = DaemonConf{\n\t\tHttpport: \"8080\",\n\t\tAuthToken: randomString(8),\n\t}\n\terr := cfgp.Parse(&conf)\n\tif err != nil {\n\t\tlog.Fatalln(\"parsing conf\", err)\n\t}\n\n\tbadExitCode := false\n\tSetupLoggers(os.Stdout, os.Stderr)\n\n\tif conf.NewRelicToken != \"\" && conf.NewRelicAppID != \"\" {\n\t\tgo FetchNewRelic(conf.NewRelicToken, conf.NewRelicAppID)\n\t}\n\n\tapi := slack.New(conf.SlackToken)\n\trtm := api.NewRTM()\n\tif conf.SlackToken != \"\" {\n\t\tgo rtm.ManageConnection()\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t// TODO try a last message sending to Slack via REST\n\t\t\t\t\t// user PostMessage\n\t\t\t\t\tErrorLogger.Println(r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tServeRTM(rtm)\n\t\t}()\n\t}\n\n\thttp.HandleFunc(\"/status\", StatusHandlerFunc)\n\thttp.HandleFunc(\n\t\t\"/gh-webhooks\",\n\t\tGHWebhooksHandlerFunc(rtm.IncomingEvents),\n\t)\n\thttp.HandleFunc(\n\t\t\"/message\",\n\t\tMustAuth(\n\t\t\tconf.AuthToken,\n\t\t\tGenericMessageHandler(rtm.IncomingEvents),\n\t\t),\n\t)\n\thttp.HandleFunc(\n\t\t\"/new-relic\",\n\t\tNewRelicHandler(rtm.IncomingEvents),\n\t)\n\taddrString := fmt.Sprintf(\"%s:%s\", conf.Httpaddress, conf.Httpport)\n\tInfoLogger.Println(\"start listening on:\", addrString)\n\tif err := http.ListenAndServe(addrString, nil); err != nil {\n\t\tErrorLogger.Println(err)\n\t\tbadExitCode = true\n\t}\n\n\twg.Wait()\n\t// FIXME send a message to RTM goroutine or deadlock\n\tif badExitCode {\n\t\tos.Exit(1)\n\t}\n}", "func webhookHandler(w http.ResponseWriter, r *http.Request) {\n\t// parse request body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tfmt.Println(string(body))\n\t// decoder := json.NewDecoder(r.Body)\n\t// Get student public URL\n\t// run Webdriver IO test against the URL and get its result\n\t// Store result and SHA\n\t// publish status to Github\n\tfmt.Println(\"Hello\")\n}", "func main() {\n\n\tcfg := webhook.LoadConfiguration(\"./config/\")\n\tqueue := webhook.NewMessagingQueue(cfg.QueueURI, cfg.ExchangeName, cfg.PoolConfig)\n\thook := webhook.NewWebHook(queue)\n\n\tiris.Post(\"/\" + cfg.EndpointName, hook.Process)\n\tgo cleanup(queue)\n\n\tiris.Listen(fmt.Sprintf(\":%d\", cfg.WebServerPort))\n\n}", "func triggerContinuousHTTPProbe(probe v1alpha1.ProbeAttributes, clients clients.ClientSets, chaosresult *types.ResultDetails, chaosDetails *types.ChaosDetails) {\n\tvar isExperimentFailed bool\n\t// waiting for initial delay\n\tif probe.RunProperties.InitialDelaySeconds != 0 {\n\t\tlog.Infof(\"[Wait]: Waiting for %vs before probe execution\", probe.RunProperties.InitialDelaySeconds)\n\t\ttime.Sleep(time.Duration(probe.RunProperties.InitialDelaySeconds) * time.Second)\n\t}\n\n\t// it trigger the http probe for the entire duration of chaos and it fails, if any error encounter\n\t// it marked the error for the probes, if any\nloop:\n\tfor {\n\t\terr = triggerHTTPProbe(probe, chaosresult)\n\t\t// record the error inside the probeDetails, we are maintaining a dedicated variable for the err, inside probeDetails\n\t\tif err != nil {\n\t\t\tfor index := range chaosresult.ProbeDetails {\n\t\t\t\tif chaosresult.ProbeDetails[index].Name == probe.Name {\n\t\t\t\t\tchaosresult.ProbeDetails[index].IsProbeFailedWithError = err\n\t\t\t\t\tlog.Errorf(\"The %v http probe has been Failed, err: %v\", probe.Name, err)\n\t\t\t\t\tisExperimentFailed = true\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// waiting for the probe polling interval\n\t\ttime.Sleep(time.Duration(probe.RunProperties.ProbePollingInterval) * time.Second)\n\t}\n\t// if experiment fails and stopOnfailure is provided as true then it will patch the chaosengine for abort\n\t// if experiment fails but stopOnfailure is provided as false then it will continue the execution\n\t// and failed the experiment in the end\n\tif isExperimentFailed && probe.RunProperties.StopOnFailure {\n\t\tif err := stopChaosEngine(probe, clients, chaosresult, chaosDetails); err != nil {\n\t\t\tlog.Errorf(\"unable to patch chaosengine to stop, err: %v\", err)\n\t\t}\n\t}\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func WaitForRun(ctx context.Context, actions WorkflowRuns, owner, repo, path string, runID int64) (string, error) {\n\tticker := time.NewTicker(1 * time.Minute)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\trun, _, err := actions.GetWorkflowRunByID(ctx, owner, repo, runID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", trace.Wrap(err, \"Failed polling run\")\n\t\t\t}\n\n\t\t\tlog.Printf(\"Workflow status: %s\", run.GetStatus())\n\n\t\t\tif run.GetStatus() == \"completed\" {\n\t\t\t\treturn run.GetConclusion(), nil\n\t\t\t}\n\n\t\tcase <-ctx.Done():\n\t\t\treturn \"\", ctx.Err()\n\t\t}\n\t}\n}", "func (m *Manager) Wait(ctx context.Context, uuid string) error {\n\t// Find the workflow.\n\trw, err := m.runningWorkflow(uuid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Just wait for it.\n\tselect {\n\tcase <-rw.done:\n\t\tbreak\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\treturn nil\n}", "func TestWaitUntilRunning(t *testing.T) {\n\tts := memorytopo.NewServer(\"cell1\")\n\tm := NewManager(ts)\n\n\t// Start it 3 times i.e. restart it 2 times.\n\tfor i := 1; i <= 3; i++ {\n\t\t// Run the manager in the background.\n\t\twg, _, cancel := StartManager(m)\n\n\t\t// Shut it down and wait for the shutdown to complete.\n\t\tcancel()\n\t\twg.Wait()\n\t}\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.workqueue.ShutDown()\n\tlog.Debug(\"Namespace Contoller: received stop signal, worker queue told to shutdown\")\n}", "func (f *FakeCmdRunner) Wait() error {\n\treturn f.Err\n}", "func waitForPromise() {\n\tfor {\n\t\t<-waitPromisChan\n\t\twaiting = true\n\t\ttime.Sleep(2 * time.Second)\n\t\twaiting = false\n\t\tcheckPromises()\n\t}\n}", "func (m *wsNotificationManager) WaitForShutdown() {\n\tm.wg.Wait()\n}", "func waitForShutdown(srv *http.Server) {\n\tinterruptChan := make(chan os.Signal, 1)\n\tsignal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n\t// Block until we receive our signal.\n\t<-interruptChan\n\n\t// Create a deadline to wait for.\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\tsrv.Shutdown(ctx)\n\n\tlog.Println(\"Shutting down\")\n\tos.Exit(0)\n}", "func waitRun(contID string) error {\n\treturn daemon.WaitInspectWithArgs(dockerBinary, contID, \"{{.State.Running}}\", \"true\", 5*time.Second)\n}", "func initAndRun(exitCode int) {\n\tinitTestingEnv()\n\tif blockingCtx := waitForEnvoy(); blockingCtx != nil {\n\t\t<-blockingCtx.Done()\n\t\terr := blockingCtx.Err()\n\t\tif err == nil || errors.Is(err, context.Canceled) {\n\t\t\tlog(\"Blocking finished, Envoy has started\")\n\t\t} else if errors.Is(err, context.DeadlineExceeded) {\n\t\t\tpanic(errors.New(\"timeout reached while waiting for Envoy to start\"))\n\t\t} else {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\tif exitCode >= 0 {\n\t\tkill(exitCode)\n\t}\n}", "func waitForEvent(t *testing.T, con *websocket.Conn, eventid string, dieOnTimeout bool, f func(), check func(string, []byte) error) {\n\t// go routine to wait for webscoket msg\n\tgoodCh := make(chan []byte)\n\terrCh := make(chan error)\n\tquitCh := make(chan struct{})\n\tdefer close(quitCh)\n\n\t// Read message\n\tgo func() {\n\t\tfor {\n\t\t\t_, p, err := con.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\t// if the event id isnt what we're waiting on\n\t\t\t\t// ignore it\n\t\t\t\tvar response ctypes.Response\n\t\t\t\tvar err error\n\t\t\t\twire.ReadJSON(&response, p, &err)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrCh <- err\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tevent, ok := response.Result.(*ctypes.ResultEvent)\n\t\t\t\tif ok && event.Event == eventid {\n\t\t\t\t\tgoodCh <- p\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t// do stuff (transactions)\n\tf()\n\n\t// wait for an event or timeout\n\ttimeout := time.NewTimer(10 * time.Second)\n\tselect {\n\tcase <-timeout.C:\n\t\tif dieOnTimeout {\n\t\t\tcon.Close()\n\t\t\tt.Fatalf(\"%s event was not received in time\", eventid)\n\t\t}\n\t\t// else that's great, we didn't hear the event\n\t\t// and we shouldn't have\n\tcase p := <-goodCh:\n\t\tif dieOnTimeout {\n\t\t\t// message was received and expected\n\t\t\t// run the check\n\t\t\terr := check(eventid, p)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t\tpanic(err) // Show the stack trace.\n\t\t\t}\n\t\t} else {\n\t\t\tcon.Close()\n\t\t\tt.Fatalf(\"%s event was not expected\", eventid)\n\t\t}\n\tcase err := <-errCh:\n\t\tt.Fatal(err)\n\t\tpanic(err) // Show the stack trace.\n\t}\n}", "func (d *vimInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func waitForGuestbookResponse(ctx context.Context, c clientset.Interface, cmd, arg, expectedResponse string, timeout time.Duration, ns string) bool {\n\tfor start := time.Now(); time.Since(start) < timeout && ctx.Err() == nil; time.Sleep(5 * time.Second) {\n\t\tres, err := makeRequestToGuestbook(ctx, c, cmd, arg, ns)\n\t\tif err == nil && res == expectedResponse {\n\t\t\treturn true\n\t\t}\n\t\tframework.Logf(\"Failed to get response from guestbook. err: %v, response: %s\", err, res)\n\t}\n\treturn false\n}", "func waitForURL(c *C, url string) error {\n\tclient := http.DefaultClient\n\tretries := 100\n\tfor retries > 0 {\n\t\tretries--\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tresp, err := client.Get(url)\n\t\tif err != nil {\n\t\t\tc.Logf(\"Got error, retries left: %d (error: %v)\", retries, err)\n\t\t\tcontinue\n\t\t}\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tc.Logf(\"Body is: %s\", body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode == 200 {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}", "func (api *API) ProcessWebhook(c echo.Context) error {\n\tdata, err := ioutil.ReadAll(c.Request().Body)\n\tif err != nil {\n\t\tresponse := &MessageResponse{Status: enums.StatusError, Message: err.Error()}\n\t\treturn c.JSON(http.StatusBadRequest, response)\n\t}\n\tdefer func() { _ = c.Request().Body.Close() }()\n\tp, err := api.services.WebhookDispatcher.GetWebhookProcessor(c.Request().Context(), c.Request().Header, data)\n\tif err != nil {\n\t\tresponse := &MessageResponse{Status: enums.StatusError, Message: err.Error()}\n\t\treturn c.JSON(http.StatusBadRequest, response)\n\t}\n\n\tgo func() {\n\t\tif err := p.Process(c.Request().Context(), c.Request().Header, data); err != nil {\n\t\t\tlogger := logging.FromContext(c.Request().Context())\n\t\t\tlogger.WithField(\"error\", err).Warn(\"could not process webhook\")\n\t\t}\n\t}()\n\treturn c.JSON(http.StatusOK, &MessageResponse{Message: \"ok\"})\n}", "func (target *WebhookTarget) initWebhook() error {\n\targs := target.args\n\ttransport := target.transport\n\n\tif args.ClientCert != \"\" && args.ClientKey != \"\" {\n\t\tmanager, err := certs.NewManager(context.Background(), args.ClientCert, args.ClientKey, tls.LoadX509KeyPair)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmanager.ReloadOnSignal(syscall.SIGHUP) // allow reloads upon SIGHUP\n\t\ttransport.TLSClientConfig.GetClientCertificate = manager.GetClientCertificate\n\t}\n\ttarget.httpClient = &http.Client{Transport: transport}\n\n\tyes, err := target.isActive()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !yes {\n\t\treturn errNotConnected\n\t}\n\n\treturn nil\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 waitForCRDEstablishment(clientset apiextensionsclient.Interface) error {\n\treturn wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {\n\t\tsparkAppCrd, err := getCRD(clientset)\n\t\tfor _, cond := range sparkAppCrd.Status.Conditions {\n\t\t\tswitch cond.Type {\n\t\t\tcase apiextensionsv1beta1.Established:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\tcase apiextensionsv1beta1.NamesAccepted:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionFalse {\n\t\t\t\t\tfmt.Printf(\"Name conflict: %v\\n\", cond.Reason)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false, err\n\t})\n}", "func (a *app) waitShutdown() {\n\t<-a.completeChan\n}", "func waitAndRouteNFTApprovedEvent(timeout time.Duration, asyncRes queue.TaskResult, tokenID *big.Int, confirmations chan<- *watchTokenMinted) {\n\t_, err := asyncRes.Get(timeout)\n\tconfirmations <- &watchTokenMinted{tokenID, err}\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 WaitUntil(c *check.C, f CheckFunc) {\n\tc.Log(\"wait start\")\n\tfor i := 0; i < waitMaxRetry; i++ {\n\t\tif f(c) {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(waitRetrySleep)\n\t}\n\tc.Fatal(\"wait timeout\")\n}", "func metadataWait() {\n\tfor {\n\t\treq, err := http.NewRequest(\"GET\", \"http://metadata.google.internal/computeMetadata/v1/instance/attributes/pushrev?wait_for_change=true\", nil)\n\t\tif err != nil {\n\t\t\tsklog.Errorf(\"Failed to create request: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\treq.Header.Set(\"Metadata-Flavor\", \"Google\")\n\t\t// We use the default client which should never timeout.\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err != nil || resp.StatusCode != 200 {\n\t\t\tsklog.Errorf(\"wait_for_change failed: %s\", err)\n\t\t\tif resp != nil {\n\t\t\t\tsklog.Errorf(\"Response: %+v\", *resp)\n\t\t\t}\n\t\t\ttime.Sleep(time.Minute)\n\t\t\tcontinue\n\t\t}\n\t\tmetadataTriggerCh <- true\n\t\tsklog.Infof(\"Pull triggered via metadata.\")\n\t}\n}", "func (node *VincTriggerNode) WaitForEvent(nodeEventStream chan model.ReactorEvent) {\n\tnode.SetReactorRunning(true)\n\ttimeout := time.Second * time.Duration(node.config.Timeout)\n\tvar timer *time.Timer\n\tif timeout == 0 {\n\t\ttimer = time.NewTimer(time.Hour * 24)\n\t\ttimer.Stop()\n\t}else {\n\t\ttimer = time.NewTimer(timeout)\n\t}\n\tdefer func() {\n\t\tnode.SetReactorRunning(false)\n\t\tnode.GetLog().Debug(\"Msg processed by the node \")\n\t\ttimer.Stop()\n\t}()\n\tfor {\n\t\tif timeout > 0 {\n\t\t\ttimer.Reset(timeout)\n\t\t}\n\t\tselect {\n\t\tcase newMsg := <-node.msgInStream:\n\t\t\tvar eventValue string\n\t\t\tif newMsg.Payload.Type == \"cmd.pd7.request\" {\n\t\t\t\trequest := primefimp.Request{}\n\t\t\t\terr := newMsg.Payload.GetObjectValue(&request)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif request.Component == \"shortcut\" && request.Cmd == \"set\" {\n\t\t\t\t\tnode.GetLog().Info(\"shortcut\")\n\t\t\t\t\tif node.config.EventType == \"shortcut\" {\n\t\t\t\t\t\teventValue = fmt.Sprintf(\"%.0f\",request.Id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else if newMsg.Payload.Type == \"evt.pd7.notify\" {\n\t\t\t\tnotify := primefimp.Notify{}\n\t\t\t\terr := newMsg.Payload.GetObjectValue(&notify)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif notify.Component == \"hub\" && notify.Cmd == \"set\" {\n\t\t\t\t\tif node.config.EventType == \"mode\" {\n\t\t\t\t\t\thub := notify.GetModeChange()\n\t\t\t\t\t\tif hub != nil {\n\t\t\t\t\t\t\teventValue = hub.Current\n\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\tnode.GetLog().Info(\"ERROR 2\")\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\tif eventValue != \"\" {\n\t\t\t\tnode.GetLog().Infof(\"Home event = %s\",eventValue)\n\t\t\t\tif !node.config.IsValueFilterEnabled || ((eventValue == node.config.ValueFilter) && node.config.IsValueFilterEnabled) {\n\t\t\t\t\tnode.GetLog().Debug(\"Starting flow\")\n\t\t\t\t\trMsg := model.Message{Payload: fimpgo.FimpMessage{Value: eventValue, ValueType: fimpgo.VTypeString}}\n\t\t\t\t\tnewEvent := model.ReactorEvent{Msg: rMsg, TransitionNodeId: node.Meta().SuccessTransition}\n\t\t\t\t\t// Flow is executed within flow runner goroutine\n\t\t\t\t\tnode.FlowRunner()(newEvent)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase <-timer.C:\n\t\t\tnode.GetLog().Debug(\"Timeout \")\n\t\t\tnewEvent := model.ReactorEvent{TransitionNodeId: node.Meta().TimeoutTransition}\n\t\t\tnode.GetLog().Debug(\"Starting new flow (timeout)\")\n\t\t\tnode.FlowRunner()(newEvent)\n\t\t\tnode.GetLog().Debug(\"Flow started (timeout) \")\n\t\tcase signal := <-node.FlowOpCtx().TriggerControlSignalChannel:\n\t\t\tnode.GetLog().Debug(\"Control signal \")\n\t\t\tif signal == model.SIGNAL_STOP {\n\t\t\t\tnode.GetLog().Info(\"VincTrigger stopped by SIGNAL_STOP \")\n\t\t\t\treturn\n\t\t\t}else {\n\t\t\t\ttime.Sleep(50*time.Millisecond)\n\t\t\t}\n\t\t}\n\n\t}\n}", "func TestWebHook(t *testing.T) {\n\tg := gomega.NewGomegaWithT(t)\n\tg.Expect(createCertificates(t)).NotTo(gomega.HaveOccurred())\n\n\t// create manager\n\tmgr, err := manager.New(cfg, manager.Options{\n\t\tMetricsBindAddress: \"0\",\n\t})\n\tg.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tc = mgr.GetClient()\n\n\t// add webhook to manager\n\tAdd(mgr)\n\n\t// start manager\n\tstopMgr, mgrStopped := StartTestManager(mgr, g)\n\tdefer func() {\n\t\tclose(stopMgr)\n\t\tmgrStopped.Wait()\n\t}()\n\n\tg.Expect(c.Create(context.TODO(), fnConfig)).NotTo(gomega.HaveOccurred())\n\n\ttestInvalidFunc(t)\n\ttestHandleDefaults(t)\n}", "func WaitForService(org string, waitService string, waitTimeout int, pattern string) {\n\n\tconst UpdateThreshold = 5 // How many service check iterations before updating the user with a msg on the console.\n\tconst ServiceUpThreshold = 5 // How many service check iterations before deciding that the service is up.\n\n\t// get message printer\n\tmsgPrinter := i18n.GetMessagePrinter()\n\n\t// Verify that the input makes sense.\n\tif waitTimeout < 0 {\n\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, msgPrinter.Sprintf(\"--timeout must be a positive integer.\"))\n\t}\n\n\t// 1. Wait for the /service API to return a service with url that matches the input\n\t// 2. While waiting, report when at least 1 agreement is formed\n\n\tmsgPrinter.Printf(\"Waiting for up to %v seconds for service %v/%v to start...\", waitTimeout, org, waitService)\n\tmsgPrinter.Println()\n\n\t// Save the most recent set of services here.\n\tservices := api.AllServices{}\n\n\t// Start monitoring the agent's /service API, looking for the presence of the input waitService.\n\tupdateCounter := UpdateThreshold\n\tserviceUp := 0\n\tserviceFailed := false\n\tnow := uint64(time.Now().Unix())\n\tfor (uint64(time.Now().Unix())-now < uint64(waitTimeout) || serviceUp > 0) && !serviceFailed {\n\t\ttime.Sleep(time.Duration(3) * time.Second)\n\t\tif _, err := cliutils.HorizonGet(\"service\", []int{200}, &services, true); err != nil {\n\t\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, err.Error())\n\t\t}\n\n\t\t// Active services are services that have at least been started. When the execution time becomes non-zero\n\t\t// it means the service container is started. The container could still fail quickly after it is started.\n\t\tinstances := services.Instances[\"active\"]\n\t\tfor _, serviceInstance := range instances {\n\n\t\t\tif !(serviceInstance.SpecRef == waitService && serviceInstance.Org == org) {\n\t\t\t\t// Skip elements for other services\n\t\t\t\tcontinue\n\n\t\t\t} else if serviceInstance.ExecutionStartTime != 0 {\n\t\t\t\t// The target service is started. If stays up then declare victory and return.\n\t\t\t\tif serviceUp >= ServiceUpThreshold {\n\t\t\t\t\tmsgPrinter.Printf(\"Service %v/%v is started.\", org, waitService)\n\t\t\t\t\tmsgPrinter.Println()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// The service could fail quickly if we happened to catch it just as it was starting, so make sure\n\t\t\t\t// the service stays up.\n\t\t\t\tserviceUp += 1\n\n\t\t\t} else if serviceUp > 0 {\n\t\t\t\t// The service has been up for at least 1 iteration, so it's absence means that it failed.\n\t\t\t\tserviceUp = 0\n\t\t\t\tmsgPrinter.Printf(\"The service %v/%v has failed.\", org, waitService)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t\tserviceFailed = true\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\t// Service is not there yet. Update the user on progress, and wait for a bit.\n\t\tupdateCounter = updateCounter - 1\n\t\tif updateCounter <= 0 && !serviceFailed {\n\t\t\tupdateCounter = UpdateThreshold\n\t\t\tmsgPrinter.Printf(\"Waiting for service %v/%v to start executing.\", org, waitService)\n\t\t\tmsgPrinter.Println()\n\t\t}\n\t}\n\n\t// If we got to this point, then there is a problem.\n\tmsgPrinter.Printf(\"Timeout waiting for service %v/%v to successfully start. Analyzing possible reasons for the timeout...\", org, waitService)\n\tmsgPrinter.Println()\n\n\t// Let's see if we can provide the user with some help figuring out what's going on.\n\tfound := false\n\tfor _, serviceInstance := range services.Instances[\"active\"] {\n\n\t\t// 1. Maybe the service is there but just hasnt started yet.\n\t\tif serviceInstance.SpecRef == waitService && serviceInstance.Org == org {\n\t\t\tmsgPrinter.Printf(\"Service %v/%v is deployed to the node, but not executing yet.\", org, waitService)\n\t\t\tmsgPrinter.Println()\n\t\t\tfound = true\n\n\t\t\t// 2. Maybe the service has encountered an error.\n\t\t\tif serviceInstance.ExecutionStartTime == 0 && serviceInstance.ExecutionFailureCode != 0 {\n\t\t\t\tmsgPrinter.Printf(\"Service %v/%v execution failed: %v.\", org, waitService, serviceInstance.ExecutionFailureDesc)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t\tserviceFailed = true\n\t\t\t} else {\n\t\t\t\tmsgPrinter.Printf(\"Service %v/%v might need more time to start executing, continuing analysis.\", org, waitService)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t}\n\t\t\tbreak\n\n\t\t}\n\t}\n\n\t// 3. The service might not even be there at all.\n\tif !found {\n\t\tmsgPrinter.Printf(\"Service %v/%v is not deployed to the node, continuing analysis.\", org, waitService)\n\t\tmsgPrinter.Println()\n\t}\n\n\t// 4. Are there any agreements being made? Check for only non-archived agreements. Skip this if we know the service failed\n\t// because we know there are agreements.\n\tif !serviceFailed {\n\t\tmsgPrinter.Println()\n\t\tags := agreement.GetAgreements(false)\n\t\tif len(ags) != 0 {\n\t\t\tmsgPrinter.Printf(\"Currently, there are %v active agreements on this node. Use `hzn agreement list' to see the agreements that have been formed so far.\", len(ags))\n\t\t\tmsgPrinter.Println()\n\t\t} else {\n\t\t\tmsgPrinter.Printf(\"Currently, there are no active agreements on this node.\")\n\t\t\tmsgPrinter.Println()\n\t\t}\n\t}\n\n\t// 5. Scan the event log for errors related to this service. This should always be done if the service did not come up\n\t// successfully.\n\teLogs := make([]persistence.EventLogRaw, 0)\n\tcliutils.HorizonGet(\"eventlog?severity=error\", []int{200}, &eLogs, true)\n\tmsgPrinter.Println()\n\tif len(eLogs) == 0 {\n\t\tmsgPrinter.Printf(\"Currently, there are no errors recorded in the node's event log.\")\n\t\tmsgPrinter.Println()\n\t\tif pattern == \"\" {\n\t\t\tmsgPrinter.Printf(\"Use the 'hzn deploycheck all -b' or 'hzn deploycheck all -B' command to verify that node, service configuration and deployment policy is compatible.\")\n\t\t} else {\n\t\t\tmsgPrinter.Printf(\"Use the 'hzn deploycheck all -p' command to verify that node, service configuration and pattern is compatible.\")\n\t\t}\n\t\tmsgPrinter.Println()\n\t} else {\n\t\tmsgPrinter.Printf(\"The following errors were found in the node's event log and are related to %v/%v. Use 'hzn eventlog list -s severity=error -l' to see the full detail of the errors.\", org, waitService)\n\t\tmsgPrinter.Println()\n\n\t\t// Scan the log for events related to the service we're waiting for.\n\t\tsel := persistence.Selector{\n\t\t\tOp: \"=\",\n\t\t\tMatchValue: waitService,\n\t\t}\n\t\tmatch := make(map[string][]persistence.Selector)\n\t\tmatch[\"service_url\"] = []persistence.Selector{sel}\n\n\t\tfor _, el := range eLogs {\n\t\t\tt := time.Unix(int64(el.Timestamp), 0)\n\t\t\tprintLog := false\n\t\t\tif strings.Contains(el.Message, waitService) {\n\t\t\t\tprintLog = true\n\t\t\t} else if es, err := persistence.GetRealEventSource(el.SourceType, el.Source); err != nil {\n\t\t\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, \"unable to convert eventlog source, error: %v\", err)\n\t\t\t} else if (*es).Matches(match) {\n\t\t\t\tprintLog = true\n\t\t\t}\n\n\t\t\t// Put relevant events on the console.\n\t\t\tif printLog {\n\t\t\t\tmsgPrinter.Printf(\"%v: %v\", t.Format(\"2006-01-02 15:04:05\"), el.Message)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t}\n\t\t}\n\t}\n\n\t// Done analyzing\n\tmsgPrinter.Printf(\"Analysis complete.\")\n\tmsgPrinter.Println()\n\n\treturn\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func (tt *Tester) Catchup() {\n\ttt.waitStartup()\n\ttt.waitForClients()\n}", "func (wh *Webhooks) Run(ctx context.Context) {\n\twh.workersNum.Inc()\n\tdefer wh.workersNum.Dec()\n\tfor {\n\t\tenqueuedItem, err := wh.queue.Pop(ctx)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\twh.queuedNum.Dec()\n\t\ttmpFile, err := wh.openStoredRequestFile(enqueuedItem)\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to process\", enqueuedItem.RequestFile, \"-\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\twh.processRequestAsync(ctx, enqueuedItem.Manifest, tmpFile)\n\t\t_ = tmpFile.Close()\n\t\t_ = os.RemoveAll(tmpFile.Name())\n\t}\n}", "func (trello *Trello) EnsureHook(callbackURL string) {\n /* Check if we have a hook already */\n var data []webhookInfo\n GenGET(trello, \"/token/\" + trello.Token + \"/webhooks/\", &data)\n found := false\n\n for _, v := range data {\n /* Check if we have a hook for our own URL at same model */\n if v.Model == trello.BoardId {\n if v.URL == callbackURL {\n log.Print(\"Hook found, nothing to do here.\")\n found = true\n break\n }\n }\n }\n\n /* If not, install one */\n if !found {\n /* TODO: save hook reference and uninstall maybe? */\n GenPOSTForm(trello, \"/webhooks/\", nil, url.Values{\n \"name\": { \"trellohub for \" + trello.BoardId },\n \"idModel\": { trello.BoardId },\n \"callbackURL\": { callbackURL } })\n\n log.Print(\"Webhook installed.\")\n } else {\n log.Print(\"Reusing existing webhook.\")\n }\n}", "func (n *Netlify) WaitUntilDeployLive(ctx context.Context, d *models.Deploy) (*models.Deploy, error) {\n\treturn n.waitForState(ctx, d, \"ready\")\n}", "func WaitReady(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\ts.Logger.Infoln(\"Waiting for machine-controller to come up...\")\n\n\tif err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForWebhook(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForMachineController(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\treturn waitForCRDs(s)\n}", "func (p *Pebble) WaitReady(t *testing.T) {\n\tif p.pebbleCMD.Process == nil {\n\t\tt.Fatal(\"Pebble not started\")\n\t}\n\turl := p.DirectoryURL()\n\tRetry(t, 10, 10*time.Millisecond, func() error {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\t\tdefer cancel()\n\n\t\tt.Log(\"Checking pebble readiness\")\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := p.httpClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp.Body.Close()\n\t\treturn nil\n\t})\n}", "func (t *ElapsedTimeout) Wait(context.Context) error { return nil }", "func waitForStatus(t *testing.T, path string, statusCode int) <-chan error {\n\t// give our process 2 seconds to respond with the correct status\n\t// this should be ample.\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\n\tsig := make(chan error, 1)\n\tgo func() {\n\t\tvar res *http.Response\n\t\tdefer cancel() // ensure we cancel the context to stop memory leaks\n\t\tdefer func() { close(sig) }() // ensure the channel is closed too.\n\n\t\t// while we have no response or the status code doesnt match\n\t\tfor res == nil || res.StatusCode != statusCode {\n\t\t\t// continue to perform HTTP requests against our local server\n\t\t\t// until we either receive a HTTP OK or a context timeout.\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tsig <- ctx.Err()\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\treq := newRequest(t, path)\n\t\t\t\tres, _ = http.DefaultClient.Do(req.WithContext(ctx))\n\t\t\t}\n\t\t}\n\n\t\tsig <- nil\n\t}()\n\n\treturn sig\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func waitFotPayloadDeath(c *client.Client, payloadAnchor string) (recov interface{}) {\n\t// defer func() { // catch panics caused by unexpected death of the server hosting the payload\n\t// \trecov = recover()\n\t// }()\n\tt := c.Walk(client.Split(payloadAnchor)) // Access the process anchor of the currently-running payload of the virus.\n\tt.Get().(client.Proc).Wait() // Wait until the payload process exits.\n\tt.Scrub() // scrub payload anchor from old process element\n\ttime.Sleep(2*time.Second) // Wait a touch to slow down the spin\n\treturn\n}", "func (webhook *Webhook) Run(ctx context.Context, listen string) error {\n\tif !webhook.isSetup {\n\t\tif err := webhook.Setup(ctx); err != nil {\n\t\t\treturn fmt.Errorf(\"setup webhook: %v\", err)\n\t\t}\n\t}\n\n\tserver := &http.Server{\n\t\tAddr: listen,\n\t\tHandler: webhook,\n\t}\n\n\tgo func() {\n\t\t<-ctx.Done()\n\n\t\twebhook.log(\"shutdown server...\")\n\n\t\tcloseCtx, close := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tdefer close()\n\n\t\tif err := server.Shutdown(closeCtx); err != nil {\n\t\t\twebhook.log(\"server shutdown error: %v\", err)\n\t\t}\n\t}()\n\n\twebhook.log(\"starting webhook server on %s\", listen)\n\n\tif err := server.ListenAndServe(); err != http.ErrServerClosed {\n\t\treturn fmt.Errorf(\"server error: %v\", err)\n\t}\n\n\treturn nil\n}", "func (c *wsClient) WaitForShutdown() {\n\tc.wg.Wait()\n}", "func (e *EvtFailureDetector) Start() {\n\te.timeoutSignal = time.NewTicker(e.delay)\n\tgo func() {\n\t\tfor {\n\t\t\te.testingHook() // DO NOT REMOVE THIS LINE. A no-op when not testing.\n\t\t\tselect {\n\t\t\tcase incHB := <-e.hbIn: //heartbeath comming in\n\t\t\t\t// TODO(student): Handle incoming heartbeat\n\t\t\t\tif incHB.Request && incHB.To == e.id {\n\t\t\t\t\t//If heartbeat is actual meant for us and it is a request, send reply back to sender\n\t\t\t\t\thbReply := Heartbeat{To: incHB.From, From: e.id, Request: false}\n\t\t\t\t\t//fmt.Printf(\"\\nfd.go recived incoming HB and creates reply: {To: %d From: %d Request: %v}\\n\", incHB.From, e.id, false)\n\t\t\t\t\te.ReplyHeartbeat(hbReply)\n\t\t\t\t} else if incHB.Request == false && incHB.To == e.id {\n\t\t\t\t\t//incHB is a reply (incHB.Request == false)\n\t\t\t\t\t//incHB is addressed to us (incHB.To == e.id)\n\t\t\t\t\t//Set incHB.From to alive\n\t\t\t\t\te.alive[incHB.From] = true\n\t\t\t\t}\n\t\t\tcase <-e.timeoutSignal.C:\n\t\t\t\te.timeout()\n\t\t\tcase <-e.stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (w Waiter) Wait() error {\n\tw.logger.Debug(waiterLogTag, \"Waiting for instance to reach running state\")\n\tw.logger.Debug(waiterLogTag, \"Using schedule %v\", w.watchSchedule)\n\n\tfor _, timeGap := range w.watchSchedule {\n\t\tw.logger.Debug(waiterLogTag, \"Sleeping for %v\", timeGap)\n\t\tw.sleepFunc(timeGap)\n\n\t\tstate, err := w.agentClient.GetState()\n\t\tif err != nil {\n\t\t\treturn bosherr.WrapError(err, \"Sending get_state\")\n\t\t}\n\n\t\t// todo stopped state\n\t\tif state.JobState == \"running\" {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn ErrNotRunning\n}", "func (TelegramBotApp *TelegramBotApp) setupWebhook() (tgbotapi.UpdatesChannel, error) {\n\t_, err := TelegramBotApp.bot.SetWebhook(tgbotapi.NewWebhook(TelegramBotApp.conf.WebhookURL + \"/\" + TelegramBotApp.bot.Token))\n\tif err != nil {\n\t\tlog.Fatal(\"[!] Webhook problem: \", err)\n\t\t//return nil, err\n\t}\n\tupdates := TelegramBotApp.bot.ListenForWebhook(\"/\" + TelegramBotApp.bot.Token)\n\tgo http.ListenAndServe(\":\"+TelegramBotApp.conf.Port, nil)\n\n\tfmt.Println(\"[+] Webhook method selected\")\n\n\treturn updates, nil\n\n}", "func waitUntilPodStatus(provider *vkAWS.FargateProvider, podName string, desiredStatus v1.PodPhase) error {\n\tctx := context.Background()\n\tcontext.WithTimeout(ctx, time.Duration(time.Second*60))\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t\tstatus, err := provider.GetPodStatus(\"default\", podName)\n\t\t\tif err != nil {\n\t\t\t\tif strings.Contains(err.Error(), \"is not found\") {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif status.Phase == desiredStatus {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}\n\t}\n}", "func (c *Compute) wait(operation *compute.Operation) error {\n\tfor {\n\t\top, err := c.ZoneOperations.Get(c.Project, c.Zone, operation.Name).Do()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get operation: %v\", operation.Name, err)\n\t\t}\n\t\tlog.Printf(\"operation %q status: %s\", operation.Name, op.Status)\n\t\tif op.Status == \"DONE\" {\n\t\t\tif op.Error != nil {\n\t\t\t\treturn fmt.Errorf(\"operation error: %v\", *op.Error.Errors[0])\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn nil\n}", "func (rest *Restful) WaitShutdown() {\n\n\tif rest == nil {\n\t\treturn\n\t}\n\n\tirqSig := make(chan os.Signal, 1)\n\tsignal.Notify(irqSig, syscall.SIGINT, syscall.SIGTERM)\n\n\tselect {\n\t// interrupt handler sig term to shutdown\n\tcase sig := <-irqSig:\n\t\tglog.Infof(\"Shutdown request from a signal %v\", sig)\n\t// shutdown request\n\tcase sig := <-rest.shutdownRequest:\n\t\tglog.Infof(\"Shutdown request (/shutdownGrpc %v)\", sig)\n\t}\n\n\tatomic.StoreInt32(&rest.healthy, 0)\n\tglog.Infof(\"sending shutdown command to rest server ...\")\n\n\t//Create shutdownGrpc context with 10 second timeout\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\terr := rest.restServer.Shutdown(ctx)\n\tif err != nil {\n\t\tglog.Infof(\"Shutdown request error: %v\", err)\n\t}\n}", "func (c *Crawler) WaitForCompletion() {\n\tc.wg.Wait()\n}", "func (d *Scheduler) Run() {\n\tgo d.webhookSched.Run()\n\tlog.Println(\"Starting scheduler...\")\n\tif err := d.updateChecks(); err != nil {\n\t\tpanic(err)\n\t}\n\tnow := time.Now().UTC()\n\td.running = true\n\tvar checkTime time.Time\n\tfor {\n\t\tsort.Sort(byTime(d.checks))\n\t\tif d.checks == nil {\n\t\t\td.updateChecks()\n\t\t}\n\t\tif d.checks != nil && len(d.checks) == 0 {\n\t\t\t// Sleep for 5 years until the config change\n\t\t\tcheckTime = now.AddDate(5, 0, 0)\n\t\t} else {\n\t\t\tcheckTime = d.checks[0].Next\n\t\t}\n\t\tselect {\n\t\tcase now = <-time.After(checkTime.Sub(now)):\n\t\t\tfor _, check := range d.checks {\n\t\t\t\tif now.Sub(check.Next) < 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif !check.Next.IsZero() {\n\t\t\t\t\tcheck.Prev = check.Next\n\t\t\t\t}\n\t\t\t\tgo func(check *Check) {\n\t\t\t\t\toldStatus := check.Up\n\t\t\t\t\tLeaderCheck(d.raft, check)\n\t\t\t\t\tif !check.Next.IsZero() {\n\t\t\t\t\t\tcheck.LastCheck = check.Next.Unix()\n\t\t\t\t\t}\n\t\t\t\t\t// Re-compute the uptime percentage\n\t\t\t\t\tif check.TimeDown > 0 {\n\t\t\t\t\t\ttotal := check.Interval * check.Pings\n\t\t\t\t\t\tcheck.Uptime = float32(int64(total)-check.TimeDown) / float32(total)\n\t\t\t\t\t\tlog.Printf(\"uptime:%+v\", check)\n\t\t\t\t\t}\n\t\t\t\t\tif check.Up != oldStatus {\n\t\t\t\t\t\tlog.Printf(\"Check %v status changed from %v to %v\", check.ID, oldStatus, check.Up)\n\t\t\t\t\t\tvar wg sync.WaitGroup\n\t\t\t\t\t\twg.Add(3)\n\t\t\t\t\t\tgo func(check *Check) {\n\t\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t\t\tif d.raft.Producer == nil {\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjs, err := json.Marshal(check)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif err := d.raft.Producer.Publish(\"neverdown\", js); err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(check)\n\t\t\t\t\t\tgo func(check *Check) {\n\t\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t\t\tif err := NotifyEmails(check); err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(check)\n\t\t\t\t\t\tgo func(check *Check) {\n\t\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t\t\tif err := ExecuteWebhooks(d.raft, d.webhookSched, check); err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(check)\n\t\t\t\t\t\twg.Wait()\n\t\t\t\t\t}\n\t\t\t\t\tif err := d.raft.ExecCommand(check.ToPostCmd()); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}(check)\n\t\t\t\tcheck.ComputeNext(now)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase <-d.stop:\n\t\t\td.running = false\n\t\t\treturn\n\t\tcase <-d.Reloadch:\n\t\t\td.updateChecks()\n\t\t}\n\t}\n}" ]
[ "0.5618916", "0.5599623", "0.5432932", "0.54272896", "0.5426101", "0.54169494", "0.5409126", "0.54035944", "0.5363949", "0.527401", "0.5210134", "0.52003247", "0.51873827", "0.5170767", "0.5069141", "0.50672245", "0.50620365", "0.50183946", "0.49992928", "0.49969497", "0.49778023", "0.496999", "0.4888483", "0.48504257", "0.4845085", "0.4839114", "0.4830706", "0.48160857", "0.48133752", "0.48124412", "0.4803358", "0.48008236", "0.4799799", "0.4770499", "0.47629687", "0.47618487", "0.47602043", "0.47599518", "0.47580105", "0.47533765", "0.47503945", "0.474931", "0.47342688", "0.47329265", "0.47329265", "0.47018346", "0.4700666", "0.4695227", "0.46941465", "0.4693167", "0.46920648", "0.46895605", "0.4688183", "0.4683382", "0.4680622", "0.46727717", "0.46714687", "0.46685308", "0.46675727", "0.4660781", "0.46507967", "0.46500924", "0.4642966", "0.4640279", "0.4638939", "0.46316776", "0.46306103", "0.4627456", "0.46256787", "0.46194065", "0.46188343", "0.4617556", "0.46170422", "0.4616899", "0.46167544", "0.46130544", "0.46106446", "0.4609445", "0.46085274", "0.4605413", "0.46041542", "0.46031883", "0.4595507", "0.45875573", "0.45807275", "0.457972", "0.45779213", "0.45693925", "0.45687068", "0.45577043", "0.4557321", "0.45562536", "0.45543084", "0.45522678", "0.4550274", "0.4527794", "0.45273313", "0.4522969", "0.4517023", "0.45130283" ]
0.78812975
0
DefaultKeymap returns a copy of the default Keymap Useful if inspection/customization is needed.
DefaultKeymap возвращает копию стандартной Keymap, полезную при необходимости проверки/настройки.
func DefaultKeymap() Keymap { return Keymap{ ansi.NEWLINE: (*Core).Enter, ansi.CARRIAGE_RETURN: (*Core).Enter, ansi.CTRL_C: (*Core).Interrupt, ansi.CTRL_D: (*Core).DeleteOrEOF, ansi.CTRL_H: (*Core).Backspace, ansi.BACKSPACE: (*Core).Backspace, ansi.CTRL_L: (*Core).Clear, ansi.CTRL_T: (*Core).SwapChars, ansi.CTRL_B: (*Core).MoveLeft, ansi.CTRL_F: (*Core).MoveRight, ansi.CTRL_P: (*Core).HistoryBack, ansi.CTRL_N: (*Core).HistoryForward, ansi.CTRL_U: (*Core).CutLineLeft, ansi.CTRL_K: (*Core).CutLineRight, ansi.CTRL_A: (*Core).MoveBeginning, ansi.CTRL_E: (*Core).MoveEnd, ansi.CTRL_W: (*Core).CutPrevWord, ansi.CTRL_Y: (*Core).Paste, // Escape sequences ansi.START_ESCAPE_SEQ: nil, ansi.META_B: (*Core).MoveWordLeft, ansi.META_LEFT: (*Core).MoveWordLeft, ansi.META_F: (*Core).MoveWordRight, ansi.META_RIGHT: (*Core).MoveWordRight, ansi.LEFT: (*Core).MoveLeft, ansi.RIGHT: (*Core).MoveRight, ansi.UP: (*Core).HistoryBack, ansi.DOWN: (*Core).HistoryForward, // Extended escape ansi.START_EXTENDED_ESCAPE_SEQ: nil, ansi.START_EXTENDED_ESCAPE_SEQ_3: nil, ansi.DELETE: (*Core).Delete, // Delete key } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDefaultKeyMap() *KeyMap {\n\treturn &KeyMap{\n\t\tYes: []string{\"y\", \"Y\"},\n\t\tNo: []string{\"n\", \"N\"},\n\t\tSelectYes: []string{\"left\"},\n\t\tSelectNo: []string{\"right\"},\n\t\tToggle: []string{\"tab\"},\n\t\tSubmit: []string{\"enter\"},\n\t\tAbort: []string{\"ctrl+c\"},\n\t}\n}", "func DefaultFuncMap() template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"go\": ToGo,\n\t\t\"goPrivate\": ToGoPrivate,\n\t\t\"lcFirst\": LcFirst,\n\t\t\"ucFirst\": UcFirst,\n\t}\n}", "func NewDefaultMap[K comparable, V any](f func(K) V) DefaultMap[K, V] {\n\treturn DefaultMap[K, V]{map[K]V{}, f}\n}", "func DefaultClusterMap() *ClusterMap {\n\treturn &ClusterMap{\n\t\tMap: make(map[string]*Cluster),\n\t}\n}", "func (e *Env) DefineDefaultMap(k string) (interface{}, error) {\n\tv := make(map[interface{}]interface{})\n\treturn v, e.Define(k, v)\n}", "func (manager *KeysManager) DefaultKey() *jose.JSONWebKey {\n\tif len(manager.KeyList) > 0 {\n\t\treturn manager.KeyList[0]\n\t} else {\n\t\treturn nil\n\t}\n}", "func DefaultMapper() *MapConvert {\n\tonce.Do(func() {\n\t\tv := viper.New()\n\t\tv.SetConfigType(\"yaml\")\n\t\tv.ReadConfig(defaultMappings())\n\t\tdefaultMap = &MapConvert{}\n\t\tif v.IsSet(\"gc_types\") {\n\t\t\tdefaultMap.GCTypes = gcTypes(v, make([]string, 0))\n\t\t}\n\t\tif v.IsSet(\"memory_bytes\") {\n\t\t\tdefaultMap.MemoryTypes = memoryTypes(v, make(map[string]string))\n\t\t}\n\t})\n\treturn defaultMap\n}", "func NewDefaultIDSetMap() *DefaultIDSetMap {\n\treturn &DefaultIDSetMap{}\n}", "func (i GinJwtSignAlgorithm) KeyMap() map[GinJwtSignAlgorithm]string {\n\treturn _GinJwtSignAlgorithmValueToKeyMap\n}", "func NewMapEngineDefault() *MapEngine {\n\tindex := NewS2Storage(17, 35)\n\treturn &MapEngine{\n\t\tedges: make(map[int64]map[int64]*Edge),\n\t\tvertices: make(map[int64]*Vertex),\n\t\ts2Storage: index,\n\t}\n}", "func DefaultsToMap() common.StringMap {\n\tcurrentDefaults = Defaults()\n\tif currentDefaults.ShellPath == \"\" {\n\t\ttempPath, err := common.GetBashPath(\"\")\n\t\tif err == nil {\n\t\t\tcurrentDefaults.ShellPath = tempPath\n\t\t} else {\n\t\t\tcurrentDefaults.ShellPath = globals.ShellPathValue\n\t\t}\n\t}\n\treturn common.StringMap{\n\t\t\"Version\": currentDefaults.Version,\n\t\t\"version\": currentDefaults.Version,\n\t\t\"SandboxHome\": currentDefaults.SandboxHome,\n\t\t\"sandbox-home\": currentDefaults.SandboxHome,\n\t\t\"SandboxBinary\": currentDefaults.SandboxBinary,\n\t\t\"sandbox-binary\": currentDefaults.SandboxBinary,\n\t\t\"UseSandboxCatalog\": currentDefaults.UseSandboxCatalog,\n\t\t\"use-sandbox-catalog\": currentDefaults.UseSandboxCatalog,\n\t\t\"LogSBOperations\": currentDefaults.LogSBOperations,\n\t\t\"log-sb-operations\": currentDefaults.LogSBOperations,\n\t\t\"LogDirectory\": currentDefaults.LogDirectory,\n\t\t\"log-directory\": currentDefaults.LogDirectory,\n\t\t\"ShellPath\": currentDefaults.ShellPath,\n\t\t\"shell-path\": currentDefaults.ShellPath,\n\t\t\"CookbookDirectory\": currentDefaults.CookbookDirectory,\n\t\t\"cookbook-directory\": currentDefaults.CookbookDirectory,\n\t\t\"MasterSlaveBasePort\": currentDefaults.MasterSlaveBasePort,\n\t\t\"master-slave-base-port\": currentDefaults.MasterSlaveBasePort,\n\t\t\"GroupReplicationBasePort\": currentDefaults.GroupReplicationBasePort,\n\t\t\"group-replication-base-port\": currentDefaults.GroupReplicationBasePort,\n\t\t\"GroupReplicationSpBasePort\": currentDefaults.GroupReplicationSpBasePort,\n\t\t\"group-replication-sp-base-port\": currentDefaults.GroupReplicationSpBasePort,\n\t\t\"FanInReplicationBasePort\": currentDefaults.FanInReplicationBasePort,\n\t\t\"fan-in-replication-base-port\": currentDefaults.FanInReplicationBasePort,\n\t\t\"AllMastersReplicationBasePort\": currentDefaults.AllMastersReplicationBasePort,\n\t\t\"all-masters-replication-base-port\": currentDefaults.AllMastersReplicationBasePort,\n\t\t\"MultipleBasePort\": currentDefaults.MultipleBasePort,\n\t\t\"multiple-base-port\": currentDefaults.MultipleBasePort,\n\t\t\"PxcBasePort\": currentDefaults.PxcBasePort,\n\t\t\"pxc-base-port\": currentDefaults.PxcBasePort,\n\t\t\"NdbBasePort\": currentDefaults.NdbBasePort,\n\t\t\"ndb-base-port\": currentDefaults.NdbBasePort,\n\t\t\"NdbClusterPort\": currentDefaults.NdbClusterPort,\n\t\t\"ndb-cluster-port\": currentDefaults.NdbClusterPort,\n\t\t\"GroupPortDelta\": currentDefaults.GroupPortDelta,\n\t\t\"group-port-delta\": currentDefaults.GroupPortDelta,\n\t\t\"MysqlXPortDelta\": currentDefaults.MysqlXPortDelta,\n\t\t\"mysqlx-port-delta\": currentDefaults.MysqlXPortDelta,\n\t\t\"AdminPortDelta\": currentDefaults.AdminPortDelta,\n\t\t\"admin-port-delta\": currentDefaults.AdminPortDelta,\n\t\t\"MasterName\": currentDefaults.MasterName,\n\t\t\"master-name\": currentDefaults.MasterName,\n\t\t\"MasterAbbr\": currentDefaults.MasterAbbr,\n\t\t\"master-abbr\": currentDefaults.MasterAbbr,\n\t\t\"NodePrefix\": currentDefaults.NodePrefix,\n\t\t\"node-prefix\": currentDefaults.NodePrefix,\n\t\t\"SlavePrefix\": currentDefaults.SlavePrefix,\n\t\t\"slave-prefix\": currentDefaults.SlavePrefix,\n\t\t\"SlaveAbbr\": currentDefaults.SlaveAbbr,\n\t\t\"slave-abbr\": currentDefaults.SlaveAbbr,\n\t\t\"SandboxPrefix\": currentDefaults.SandboxPrefix,\n\t\t\"sandbox-prefix\": currentDefaults.SandboxPrefix,\n\t\t\"ImportedSandboxPrefix\": currentDefaults.ImportedSandboxPrefix,\n\t\t\"imported-sandbox-prefix\": currentDefaults.ImportedSandboxPrefix,\n\t\t\"MasterSlavePrefix\": currentDefaults.MasterSlavePrefix,\n\t\t\"master-slave-prefix\": currentDefaults.MasterSlavePrefix,\n\t\t\"GroupPrefix\": currentDefaults.GroupPrefix,\n\t\t\"group-prefix\": currentDefaults.GroupPrefix,\n\t\t\"GroupSpPrefix\": currentDefaults.GroupSpPrefix,\n\t\t\"group-sp-prefix\": currentDefaults.GroupSpPrefix,\n\t\t\"MultiplePrefix\": currentDefaults.MultiplePrefix,\n\t\t\"multiple-prefix\": currentDefaults.MultiplePrefix,\n\t\t\"FanInPrefix\": currentDefaults.FanInPrefix,\n\t\t\"fan-in-prefix\": currentDefaults.FanInPrefix,\n\t\t\"AllMastersPrefix\": currentDefaults.AllMastersPrefix,\n\t\t\"all-masters-prefix\": currentDefaults.AllMastersPrefix,\n\t\t\"ReservedPorts\": currentDefaults.ReservedPorts,\n\t\t\"reserved-ports\": currentDefaults.ReservedPorts,\n\t\t\"RemoteRepository\": currentDefaults.RemoteRepository,\n\t\t\"remote-repository\": currentDefaults.RemoteRepository,\n\t\t\"RemoteIndexFile\": currentDefaults.RemoteIndexFile,\n\t\t\"remote-index-file\": currentDefaults.RemoteIndexFile,\n\t\t\"RemoteCompletionUrl\": currentDefaults.RemoteCompletionUrl,\n\t\t\"remote-completion-url\": currentDefaults.RemoteCompletionUrl,\n\t\t\"RemoteTarballUrl\": currentDefaults.RemoteTarballUrl,\n\t\t\"remote-tarball-url\": currentDefaults.RemoteTarballUrl,\n\t\t\"remote-tarballs\": currentDefaults.RemoteTarballUrl,\n\t\t\"remote-github\": currentDefaults.RemoteTarballUrl,\n\t\t\"PxcPrefix\": currentDefaults.PxcPrefix,\n\t\t\"pxc-prefix\": currentDefaults.PxcPrefix,\n\t\t\"NdbPrefix\": currentDefaults.NdbPrefix,\n\t\t\"ndb-prefix\": currentDefaults.NdbPrefix,\n\t\t\"DefaultSandboxExecutable\": currentDefaults.DefaultSandboxExecutable,\n\t\t\"default-sandbox-executable\": currentDefaults.DefaultSandboxExecutable,\n\t\t\"download-url\": currentDefaults.DownloadUrl,\n\t\t\"DownloadUrl\": currentDefaults.DownloadUrl,\n\t\t\"download-name-macos\": currentDefaults.DownloadNameMacOs,\n\t\t\"DownloadNameMacOs\": currentDefaults.DownloadNameMacOs,\n\t\t\"download-name-linux\": currentDefaults.DownloadNameLinux,\n\t\t\"DownloadNameLinux\": currentDefaults.DownloadNameLinux,\n\t\t\"Timestamp\": currentDefaults.Timestamp,\n\t\t\"timestamp\": currentDefaults.Timestamp,\n\t}\n}", "func DefaultMetadataMap(objType string, hasPrivileges bool, hasOwner bool, hasComment bool, hasSecurityLabel bool) backup.MetadataMap {\n\treturn backup.MetadataMap{\n\t\tbackup.UniqueID{ClassID: ClassIDFromObjectName(objType), Oid: 1}: DefaultMetadata(objType, hasPrivileges, hasOwner, hasComment, hasSecurityLabel),\n\t}\n}", "func DefaultKeyGetter(c *gin.Context) (string, bool) {\n\treturn c.ClientIP(), true\n}", "func KeyToDefaultPath(key Key) (string, error) {\n\treturn key.defaultPath()\n}", "func (i SNSProtocol) KeyMap() map[SNSProtocol]string {\n\treturn _SNSProtocolValueToKeyMap\n}", "func (me XsdGoPkgHasElems_Key) KeyDefault() TstyleStateEnumType { return TstyleStateEnumType(\"normal\") }", "func IsDefaultKey(key string) bool {\n\tfor _, k := range defaultKeys {\n\t\tif k == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func DefaultConfigMapName(controllerName string) string {\n\treturn fmt.Sprintf(\"%s-configmap\", controllerName)\n}", "func DefaultConfigMapName(controllerName string) string {\n\treturn fmt.Sprintf(\"%s-configmap\", controllerName)\n}", "func NewMap(store map[string]*rsa.PrivateKey) *KeyStore {\n\treturn &KeyStore{\n\t\tstore: store,\n\t}\n}", "func (i GinBindType) KeyMap() map[GinBindType]string {\n\treturn _GinBindTypeValueToKeyMap\n}", "func (me XsdGoPkgHasElem_Key) KeyDefault() TstyleStateEnumType { return TstyleStateEnumType(\"normal\") }", "func getDefaultKey(keystore string) (string, error) {\n\n\tfiles, err := ioutil.ReadDir(keystore)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar monikers []string\n\n\tfor _, file := range files {\n\t\tif filepath.Ext(file.Name()) == \".json\" {\n\t\t\tmonikers = append(monikers, strings.TrimSuffix(\n\t\t\t\tfile.Name(),\n\t\t\t\tfilepath.Ext(file.Name()),\n\t\t\t))\n\t\t}\n\t}\n\n\tif len(monikers) == 0 {\n\t\treturn \"\", errors.New(\"No keys found. Use 'monet keys new' to generate keys \")\n\t}\n\n\tif len(monikers) == 1 {\n\t\treturn monikers[0], nil\n\t}\n\n\tcommon.ErrorMessage(\"You have multiple available keys. Specify one using the --key parameter.\")\n\tcommon.InfoMessage(monikers)\n\n\treturn \"\", errors.New(\"key to use is ambiguous\")\n\n}", "func (w *Wallet) defaultScopeManagers() (\n\tmap[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager, er.R) {\n\n\tscopedMgrs := make(map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager)\n\tfor _, scope := range waddrmgr.DefaultKeyScopes {\n\t\tscopedMgr, err := w.Manager.FetchScopedKeyManager(scope)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tscopedMgrs[scope] = scopedMgr\n\t}\n\n\treturn scopedMgrs, nil\n}", "func (o BucketEncryptionOutput) DefaultKmsKeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketEncryption) *string { return v.DefaultKmsKeyName }).(pulumi.StringPtrOutput)\n}", "func (o *UserDisco) SetDefaultKeyId(v string) {\n\to.DefaultKeyId = &v\n}", "func (ini INI) DefaultSectionGetKey(k string) (string, error) {\n\treturn ini.SectionGetKey(defaultSection, k)\n}", "func (m Map) HasDefault() bool {\n\treturn true\n}", "func GetAuthDefaultSettingsConfigMap() *corev1.ConfigMap {\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: SettingsAuthConfigMapName,\n\t\t\tNamespace: SettingsAuthConfigMapNamespace,\n\t\t},\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: ConfigMapKindName,\n\t\t\tAPIVersion: ConfigMapAPIVersion,\n\t\t},\n\t\tData: GetAuthDefaultSettings().GetData(),\n\t}\n}", "func (info Terminfo) KeyMap() map[string]string {\n\tr := make(map[string]string, maxKeys)\n\tr[\"F1\"] = info.Keys[KeyF1]\n\tr[\"F2\"] = info.Keys[KeyF2]\n\tr[\"F3\"] = info.Keys[KeyF3]\n\tr[\"F4\"] = info.Keys[KeyF4]\n\tr[\"F5\"] = info.Keys[KeyF5]\n\tr[\"F6\"] = info.Keys[KeyF6]\n\tr[\"F7\"] = info.Keys[KeyF7]\n\tr[\"F8\"] = info.Keys[KeyF8]\n\tr[\"F9\"] = info.Keys[KeyF9]\n\tr[\"F10\"] = info.Keys[KeyF10]\n\tr[\"F11\"] = info.Keys[KeyF11]\n\tr[\"F12\"] = info.Keys[KeyF12]\n\tr[\"Insert\"] = info.Keys[KeyInsert]\n\tr[\"Delete\"] = info.Keys[KeyDelete]\n\tr[\"Home\"] = info.Keys[KeyHome]\n\tr[\"End\"] = info.Keys[KeyEnd]\n\tr[\"PageUp\"] = info.Keys[KeyPageUp]\n\tr[\"PageDown\"] = info.Keys[KeyPageDown]\n\tr[\"Up\"] = info.Keys[KeyUp]\n\tr[\"Down\"] = info.Keys[KeyDown]\n\tr[\"Left\"] = info.Keys[KeyLeft]\n\tr[\"Right\"] = info.Keys[KeyRight]\n\treturn r\n}", "func UseDefaultKey(value bool) Option {\n\treturn option.New(optkeyDefault, value)\n}", "func (o SparseDependencyMapsList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (j *DSRocketchat) UseDefaultMapping(ctx *Ctx, raw bool) bool {\n\treturn true\n}", "func GetDefaultKeyFilePath() string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn windowsServerKeyPath\n\t}\n\treturn nixServerKeyPath\n}", "func (i SNSPlatformApplicationAttribute) KeyMap() map[SNSPlatformApplicationAttribute]string {\n\treturn _SNSPlatformApplicationAttributeValueToKeyMap\n}", "func (o BucketEncryptionPtrOutput) DefaultKmsKeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketEncryption) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DefaultKmsKeyName\n\t}).(pulumi.StringPtrOutput)\n}", "func (j *DSGit) UseDefaultMapping(ctx *Ctx, raw bool) bool {\n\treturn raw\n}", "func (o BucketEncryptionPtrOutput) DefaultKmsKeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketEncryption) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.DefaultKmsKeyName\n\t}).(pulumi.StringPtrOutput)\n}", "func GetMapKey(UsernameHashed, PasswordHashed string) []byte {\r\n\treturn []byte(path.Join(keyPrefix4SubTree, UsernameHashed, PasswordHashed))\r\n}", "func WithDefaultKeyFile(keyFile string, isPublic bool) string {\n\tvar err error\n\n\tif keyFile != \"\" {\n\t\treturn VerifySigningKeyInput(keyFile, isPublic)\n\t}\n\t// get default file names if input is empty\n\tif keyFile, err = GetDefaultSigningKeyFile(isPublic); err != nil {\n\t\tFatal(CLI_GENERAL_ERROR, err.Error())\n\t\t// convert to absolute path\n\t} else if keyFile, err = filepath.Abs(keyFile); err != nil {\n\t\tFatal(CLI_GENERAL_ERROR, i18n.GetMessagePrinter().Sprintf(\"Failed to get absolute path for file %v. %v\", keyFile, err))\n\t\t// check file exist\n\t} else if _, err := os.Stat(keyFile); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn \"\"\n\t\t} else {\n\t\t\tFatal(CLI_GENERAL_ERROR, i18n.GetMessagePrinter().Sprintf(\"Error checking absolute path for file %v. %v\", keyFile, err))\n\t\t}\n\t}\n\treturn keyFile\n}", "func (DummyStore) GetMap(key string) (map[string]interface{}, error) {\n\treturn nil, nil\n}", "func (o BucketEncryptionOutput) DefaultKmsKeyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketEncryption) string { return v.DefaultKmsKeyName }).(pulumi.StringOutput)\n}", "func (o DependencyMapsList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func GetKeys(data map[string]string) []string {\n\tkeys := defaultKeys\n\tif data != nil && len(data) > len(defaultKeys) {\n\t\tfor name := range data {\n\t\t\tif !IsDefaultKey(name) {\n\t\t\t\tkeys = append(keys, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn keys\n}", "func Map() map[string]interface{} {\n\treturn DefaultConfig.Map()\n}", "func (o *DependencyMap) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (e EnvironmentImageMapV0) WithDefaults() interface{} {\n\tcpu := CPUImage\n\tgpu := GPUImage\n\tif e.RawCPU != nil {\n\t\tcpu = *e.RawCPU\n\t}\n\tif e.RawGPU != nil {\n\t\tgpu = *e.RawGPU\n\t}\n\treturn EnvironmentImageMapV0{RawCPU: &cpu, RawGPU: &gpu}\n}", "func DefaultQueueKeysFunc(_ runtime.Object) []string {\n\treturn []string{DefaultQueueKey}\n}", "func NewGetKeyPairsDefault(code int) *GetKeyPairsDefault {\n\treturn &GetKeyPairsDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (svc *ServiceDefinition) ProvisionDefaultOverrides() map[string]interface{} {\n\treturn viper.GetStringMap(svc.ProvisionDefaultOverrideProperty())\n}", "func SetDefaultAttributes(attrOriginal map[string]string) (map[string]string, error) {\n\tattr := make(map[string]string)\n\tfor k, v := range attrOriginal {\n\t\tattr[k] = v\n\t}\n\n\tsetDefaultIfEmpty(attr, csiapi.IssuerKindKey, cmapi.IssuerKind)\n\tsetDefaultIfEmpty(attr, csiapi.IssuerGroupKey, certmanager.GroupName)\n\n\tsetDefaultIfEmpty(attr, csiapi.IsCAKey, \"false\")\n\tsetDefaultIfEmpty(attr, csiapi.DurationKey, cmapi.DefaultCertificateDuration.String())\n\n\tsetDefaultIfEmpty(attr, csiapi.CAFileKey, \"ca.crt\")\n\tsetDefaultIfEmpty(attr, csiapi.CertFileKey, \"tls.crt\")\n\tsetDefaultIfEmpty(attr, csiapi.KeyFileKey, \"tls.key\")\n\n\tsetDefaultIfEmpty(attr, csiapi.KeyUsagesKey, strings.Join([]string{string(cmapi.UsageDigitalSignature), string(cmapi.UsageKeyEncipherment)}, \",\"))\n\n\treturn attr, nil\n}", "func (j *DSGitHub) UseDefaultMapping(ctx *Ctx, raw bool) bool {\n\treturn raw\n}", "func New() Hashmap {\n\treturn Hashmap{make([]node, defaultSize), defaultSize, 0}\n}", "func (o SparseOAUTHKeysList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func New() *OMap {\n\treturn &OMap{\n\t\tkeys: make([]string, 0),\n\t\tbaseMap: make(map[string]interface{}, 0),\n\t}\n}", "func (i SNSSubscribeAttribute) KeyMap() map[SNSSubscribeAttribute]string {\n\treturn _SNSSubscribeAttributeValueToKeyMap\n}", "func DefaultClient() *Client {\n\treturn &Client{Key}\n}", "func NewAccessKeyWithDefaults() *AccessKey {\n\tthis := AccessKey{}\n\treturn &this\n}", "func DefaultRedisConfiguration() map[string]string {\n\treturn map[string]string{\"redis.conf\": redisConfContent}\n}", "func GetDefaultSigningKeyFile(isPublic bool) (string, error) {\n\t// we have to use $HOME for now because os/user is not implemented on some plateforms\n\thome_dir := os.Getenv(\"HOME\")\n\tif home_dir == \"\" {\n\t\thome_dir = \"/tmp/keys\"\n\t}\n\n\tif isPublic {\n\t\treturn filepath.Join(home_dir, DEFAULT_PUBLIC_KEY_FILE), nil\n\t} else {\n\t\treturn filepath.Join(home_dir, DEFAULT_PRIVATE_KEY_FILE), nil\n\t}\n}", "func (ss SectionSlice) Defaults() DefaultMap {\n\tvar dm = make(DefaultMap)\n\tfor _, s := range ss {\n\t\tfor _, g := range s.Groups {\n\t\t\tfor _, f := range g.Fields {\n\t\t\t\tdm[ScopeKey(Path(s.ID, g.ID, f.ID))] = f.Default\n\t\t\t}\n\t\t}\n\t}\n\treturn dm\n}", "func DefaultJWKS() []byte {\n\t// Create a temporary file containing the JSON web key set:\n\tbigE := big.NewInt(int64(jwtPublicKey.E))\n\tbigN := jwtPublicKey.N\n\treturn []byte(fmt.Sprintf(\n\t\t`{\n\t\t\t\"keys\": [{\n\t\t\t\t\"kid\": \"123\",\n\t\t\t\t\"kty\": \"RSA\",\n\t\t\t\t\"alg\": \"RS256\",\n\t\t\t\t\"e\": \"%s\",\n\t\t\t\t\"n\": \"%s\"\n\t\t\t}]\n\t\t}`,\n\t\tbase64.RawURLEncoding.EncodeToString(bigE.Bytes()),\n\t\tbase64.RawURLEncoding.EncodeToString(bigN.Bytes()),\n\t))\n}", "func (ini INI) DefaultSectionGet() (map[string]string, error) {\n\treturn ini.SectionGet(defaultSection)\n}", "func testAccAwsEbsDefaultKmsKeyAwsManagedDefaultKey() (*arn.ARN, error) {\n\tconn := testAccProvider.Meta().(*AWSClient).kmsconn\n\n\talias, err := findKmsAliasByName(conn, \"alias/aws/ebs\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taliasARN, err := arn.Parse(aws.StringValue(alias.AliasArn))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tarn := arn.ARN{\n\t\tPartition: aliasARN.Partition,\n\t\tService: aliasARN.Service,\n\t\tRegion: aliasARN.Region,\n\t\tAccountID: aliasARN.AccountID,\n\t\tResource: fmt.Sprintf(\"key/%s\", aws.StringValue(alias.TargetKeyId)),\n\t}\n\n\treturn &arn, nil\n}", "func NewGameMap() GameMap {\n\t//Return a new game map of a single level for now\n\tl := NewLevel()\n\tlevels := make([]Level, 0)\n\tlevels = append(levels, l)\n\td := Dungeon{Name: \"default\", Levels: levels}\n\tdungeons := make([]Dungeon, 0)\n\tdungeons = append(dungeons, d)\n\tgm := GameMap{Dungeons: dungeons, CurrentLevel: l}\n\treturn gm\n\n}", "func GetKeyTagMap(src map[string]interface{}) map[string]interface{} {\n\tres := NewEmptyTagMap()\n\tres[\"inname\"] = \"key\"\n\tres[\"exname\"] = \"key\"\n\tres[\"type\"] = src[\"keytype\"]\n\tres[\"length\"] = src[\"keylength\"]\n\tres[\"scale\"] = src[\"keyscale\"]\n\tres[\"precision\"] = src[\"keyprecision\"]\n\tres[\"fieldid\"] = src[\"keyfieldid\"]\n\treturn res\n}", "func DefaultTables() IPTables {\n\treturn IPTables{\n\t\tTables: map[string]Table{\n\t\t\ttablenameNat: Table{\n\t\t\t\tBuiltinChains: map[Hook]Chain{\n\t\t\t\t\tPrerouting: unconditionalAcceptChain(chainNamePrerouting),\n\t\t\t\t\tInput: unconditionalAcceptChain(chainNameInput),\n\t\t\t\t\tOutput: unconditionalAcceptChain(chainNameOutput),\n\t\t\t\t\tPostrouting: unconditionalAcceptChain(chainNamePostrouting),\n\t\t\t\t},\n\t\t\t\tDefaultTargets: map[Hook]Target{\n\t\t\t\t\tPrerouting: UnconditionalAcceptTarget{},\n\t\t\t\t\tInput: UnconditionalAcceptTarget{},\n\t\t\t\t\tOutput: UnconditionalAcceptTarget{},\n\t\t\t\t\tPostrouting: UnconditionalAcceptTarget{},\n\t\t\t\t},\n\t\t\t\tUserChains: map[string]Chain{},\n\t\t\t},\n\t\t\ttablenameMangle: Table{\n\t\t\t\tBuiltinChains: map[Hook]Chain{\n\t\t\t\t\tPrerouting: unconditionalAcceptChain(chainNamePrerouting),\n\t\t\t\t\tOutput: unconditionalAcceptChain(chainNameOutput),\n\t\t\t\t},\n\t\t\t\tDefaultTargets: map[Hook]Target{\n\t\t\t\t\tPrerouting: UnconditionalAcceptTarget{},\n\t\t\t\t\tOutput: UnconditionalAcceptTarget{},\n\t\t\t\t},\n\t\t\t\tUserChains: map[string]Chain{},\n\t\t\t},\n\t\t},\n\t\tPriorities: map[Hook][]string{\n\t\t\tPrerouting: []string{tablenameMangle, tablenameNat},\n\t\t\tOutput: []string{tablenameMangle, tablenameNat},\n\t\t},\n\t}\n}", "func DefaultIDSetMapWith(m map[int]*IDSet) *DefaultIDSetMap {\n\treturn &DefaultIDSetMap{m: m}\n}", "func New() hctx.Map {\n\treturn hctx.Map{\n\t\tPathForKey: PathFor,\n\t}\n}", "func (config *wrapper) GetPrefixedMap(section string, prefix string) map[string]string {\n\tvals := config.cfg.Section(section).KeysHash()\n\tvar output = make(map[string]string)\n\tfor key, val := range vals {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\toutput[strings.Replace(key, prefix+\".\", \"\", 1)] = val\n\t\t}\n\t}\n\treturn output\n}", "func New() Map {\n\treturn empty\n}", "func (_Votes *VotesCallerSession) LogKeyDefault() (string, error) {\n\treturn _Votes.Contract.LogKeyDefault(&_Votes.CallOpts)\n}", "func DefaultParams() *Params {\n\tp := Params{\n\t\tKeyLength: 512,\n\t\tInternalSaltLength: 256,\n\t\tExternalSaltLength: 256,\n\t\tArgon2Memory: 64 * 1024,\n\t\tArgon2Iterations: 3,\n\t\tArgon2Parallelism: 4}\n\treturn &p\n}", "func (_Votes *VotesSession) LogKeyDefault() (string, error) {\n\treturn _Votes.Contract.LogKeyDefault(&_Votes.CallOpts)\n}", "func (o IopingSpecVolumeVolumeSourceConfigMapOutput) DefaultMode() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceConfigMap) *int { return v.DefaultMode }).(pulumi.IntPtrOutput)\n}", "func flattenUrlMapDefaultRouteActionRequestMirrorPolicyMap(c *Client, i interface{}) map[string]UrlMapDefaultRouteActionRequestMirrorPolicy {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapDefaultRouteActionRequestMirrorPolicy{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapDefaultRouteActionRequestMirrorPolicy{}\n\t}\n\n\titems := make(map[string]UrlMapDefaultRouteActionRequestMirrorPolicy)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapDefaultRouteActionRequestMirrorPolicy(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}", "func (a KeyAlgorithm) DefaultSize() int {\n\tswitch a {\n\tcase ECDSAKey:\n\t\treturn 256\n\tcase RSAKey:\n\t\treturn 4096\n\t}\n\treturn 0\n}", "func (_Votes *VotesCaller) LogKeyDefault(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Votes.contract.Call(opts, out, \"logKeyDefault\")\n\treturn *ret0, err\n}", "func KeyToDefaultDeletePath(key Key) (string, error) {\n\treturn key.defaultDeletePath()\n}", "func DefaultMainKubeClient(metricStorage *metric_storage.MetricStorage, metricLabels map[string]string) klient.Client {\n\tclient := klient.New()\n\tclient.WithContextName(app.KubeContext)\n\tclient.WithConfigPath(app.KubeConfig)\n\tclient.WithRateLimiterSettings(app.KubeClientQps, app.KubeClientBurst)\n\tclient.WithMetricStorage(metricStorage)\n\tclient.WithMetricLabels(DefaultIfEmpty(metricLabels, DefaultMainKubeClientMetricLabels))\n\treturn client\n}", "func (o BucketEncryptionResponseOutput) DefaultKmsKeyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketEncryptionResponse) string { return v.DefaultKmsKeyName }).(pulumi.StringOutput)\n}", "func (o *OAUTHKey) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (o OAUTHKeysList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (r *KeystoneAPI) Default() {\n\tkeystoneapilog.Info(\"default\", \"name\", r.Name)\n\n\tr.Spec.Default()\n}", "func DefaultSignerOptions() SignerOptions {\n\treturn SignerOptions{\n\t\tConfigMapNamespace: api.NamespacePublic,\n\t\tConfigMapName: bootstrapapi.ConfigMapClusterInfo,\n\t\tTokenSecretNamespace: api.NamespaceSystem,\n\t}\n}", "func flattenUrlMapDefaultRouteActionMap(c *Client, i interface{}) map[string]UrlMapDefaultRouteAction {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapDefaultRouteAction{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapDefaultRouteAction{}\n\t}\n\n\titems := make(map[string]UrlMapDefaultRouteAction)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapDefaultRouteAction(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}", "func (r *K3sControlPlaneTemplate) Default() {\n\tinfrabootstrapv1.DefaultK3sConfigSpec(&r.Spec.Template.Spec.K3sConfigSpec)\n\n\tr.Spec.Template.Spec.RolloutStrategy = defaultRolloutStrategy(r.Spec.Template.Spec.RolloutStrategy)\n}", "func Default(key string, value interface{}) {\n\tviper.SetDefault(key, value)\n}", "func flattenUrlMapDefaultUrlRedirectMap(c *Client, i interface{}) map[string]UrlMapDefaultUrlRedirect {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapDefaultUrlRedirect{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapDefaultUrlRedirect{}\n\t}\n\n\titems := make(map[string]UrlMapDefaultUrlRedirect)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapDefaultUrlRedirect(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}", "func newMap() map[interface{}]interface{} {\n\treturn map[interface{}]interface{}{}\n}", "func NewApiKeyWithDefaults() *ApiKey {\n\tthis := ApiKey{}\n\treturn &this\n}", "func getDefaultVariables() (defaultVariables map[string]string, err error) {\n\tdefaultVariables = make(map[string]string)\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn defaultVariables, err\n\t}\n\tdefaultVariables[\"workdir\"] = dir\n\n\tdefaultVariables[\"date\"] = time.Now().Format(\"2006-01-02\")\n\n\treturn defaultVariables, nil\n}", "func NewDeleteAPIKeyDefault(code int) *DeleteAPIKeyDefault {\n\treturn &DeleteAPIKeyDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (p *stdinParser) defineKeyMap(key prompt.Key, remapped []byte) {\n\tp.keyMap[key] = remapped\n}", "func NewMap() Map {\n\treturn &sortedMap{}\n}", "func (c *ConfigPolicyNode) Defaults() map[string]ctypes.ConfigValue {\n\tdefaults := map[string]ctypes.ConfigValue{}\n\tfor name, rule := range c.rules {\n\t\tif def := rule.Default(); def != nil {\n\t\t\tdefaults[name] = def\n\t\t}\n\t}\n\treturn defaults\n}", "func (ini INI) DefaultSectionSetKey(k, v string) {\n\tini.SectionSetKey(defaultSection, k, v)\n}", "func NewDefaultCommand() *cobra.Command {\n\tcmd := cobra.Command{\n\t\tUse: path.Base(os.Args[0]),\n\t\tShort: \"kwir\",\n\t\tLong: \"Kube Webhook Image Rewriter (kwir) is a mutating admission webhook manager that rewrites container's images based on config rules\",\n\t\tSilenceUsage: true,\n\t}\n\n\tviper.SetEnvPrefix(\"KWIR\")\n\tviper.AutomaticEnv()\n\n\tcmd.AddCommand(newVersionCommand())\n\tcmd.AddCommand(newKwirCommand())\n\n\treturn &cmd\n}", "func (o FioSpecVolumeVolumeSourceConfigMapOutput) DefaultMode() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceConfigMap) *int { return v.DefaultMode }).(pulumi.IntPtrOutput)\n}", "func NewDefaultDialedKlient() (*Klient, error) {\n\treturn NewDialedKlient(NewKlientOptions())\n}" ]
[ "0.74792606", "0.6471782", "0.6430026", "0.6413645", "0.6204454", "0.6148289", "0.611857", "0.5991836", "0.5914652", "0.5903464", "0.5883921", "0.5832911", "0.5769057", "0.56442523", "0.5629255", "0.5577586", "0.5549471", "0.54746073", "0.54746073", "0.5446178", "0.5425417", "0.5406213", "0.534115", "0.5318725", "0.53133285", "0.52719474", "0.5269875", "0.5261475", "0.5217889", "0.5213057", "0.5203952", "0.52035445", "0.51935315", "0.5191167", "0.51782024", "0.5156804", "0.514897", "0.5141691", "0.5138247", "0.51291996", "0.51004213", "0.50958604", "0.5088658", "0.5086607", "0.5081069", "0.50724053", "0.5069452", "0.5065091", "0.50628906", "0.50572604", "0.50545615", "0.504717", "0.50462055", "0.50005025", "0.49968633", "0.49833518", "0.4976506", "0.49658534", "0.49532133", "0.4951803", "0.49498254", "0.4947625", "0.49408066", "0.49400422", "0.4936101", "0.491658", "0.49161804", "0.49071544", "0.4896566", "0.4896158", "0.4882244", "0.48786098", "0.48753935", "0.48707289", "0.485968", "0.48514432", "0.48445648", "0.48437673", "0.48400757", "0.4837579", "0.48264623", "0.48240608", "0.48115796", "0.4804841", "0.4801652", "0.47947064", "0.47924456", "0.47923145", "0.47904825", "0.47898263", "0.47849193", "0.47823483", "0.47818667", "0.4774752", "0.4769102", "0.47655874", "0.47623134", "0.47618613", "0.47589937", "0.47382155" ]
0.75022745
0
CreateFileSystem invokes the dfs.CreateFileSystem API synchronously
CreateFileSystem вызывает API dfs.CreateFileSystem синхронно
func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) { response = CreateCreateFileSystemResponse() err = client.DoAction(request, response) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func MakeFsOnDisk() FileSystem { return filesys.MakeFsOnDisk() }", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func (storage *B2Storage) CreateDirectory(threadIndex int, dir string) (err error) {\n return nil\n}", "func (fs *VolatileFileSystem) CreateFile(name string, data []byte) error {\n\tvar flags C.int = C.SQLITE_OPEN_EXCLUSIVE | C.SQLITE_OPEN_CREATE\n\n\tiFd, rc := fs.vfs.Open(name, flags)\n\tif rc != C.SQLITE_OK {\n\t\treturn Error{\n\t\t\tCode: ErrIoErr,\n\t\t\tExtendedCode: ErrNoExtended(rc),\n\t\t}\n\t}\n\n\tfile, _ := fs.vfs.FileByFD(iFd)\n\tfile.mu.Lock()\n\tfile.data = data\n\tfile.mu.Unlock()\n\n\treturn nil\n}", "func (fs osFS) Create(path string) (io.WriteCloser, error) {\n\tf, err := os.Create(fs.resolve(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Open: %s is a directory\", path)\n\t}\n\n\treturn f, nil\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func (fsi *fsIOPool) Create(path string) (wlk *lock.LockedFile, err error) {\n\tif err = checkPathLength(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates parent if missing.\n\tif err = mkdirAll(pathutil.Dir(path), 0777); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attempt to create the file.\n\twlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsPermission(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tcase isSysErrIsDir(err):\n\t\t\treturn nil, errIsNotRegular\n\t\tcase isSysErrPathNotFound(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Success.\n\treturn wlk, nil\n}", "func (fs *bundleFs) Create(name string) (afero.File, error) {\n\treturn nil, ErrReadOnly\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func (s *storager) Create(ctx context.Context, location string, mode os.FileMode, reader io.Reader, isDir bool, options ...storage.Option) error {\n\troot := s.Root\n\tif isDir {\n\t\t_, err := root.Folder(location, mode)\n\t\treturn err\n\t}\n\treturn s.Upload(ctx, location, mode, reader)\n}", "func (fs *dsFileSys) Create(name string) (fsi.File, error) {\n\n\t// WriteFile & Create\n\tdir, bname := fs.SplitX(name)\n\n\tf := DsFile{}\n\tf.fSys = fs\n\tf.BName = common.Filify(bname)\n\tf.Dir = dir\n\tf.MModTime = time.Now()\n\tf.MMode = 0644\n\n\t// let all the properties by set by fs.saveFileByPath\n\terr := f.Sync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return &f, nil\n\tff := fsi.File(&f)\n\treturn ff, err\n\n}", "func (s Storage) Create(path string) (io.ReadWriteCloser, error) {\n\tloc, err := s.fullPath(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir, _ := filepath.Split(loc)\n\t_, err = os.Stat(dir)\n\n\tif err != nil && os.IsNotExist(err) {\n\t\terr = os.MkdirAll(dir, 0766)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.OpenFile(loc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0766)\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func (fs *Fs) Create(name string) (*os.File, error) {\n\treturn os.Create(name) // #nosec G304\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (fsys *gcsFS) Create(name string) (WriterFile, error) {\n\tf, err := fsys.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*GCSFile), nil\n}", "func (fs osFsEval) Create(path string) (*os.File, error) {\n\treturn os.Create(path)\n}", "func (fs *FileSystem) Create(name string) (absfs.File, error) {\n\treturn fs.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0777)\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func NewFileSystem(fs http.FileSystem, name string) FileSystem {\n\treturn Trace(&fileSystem{fs}, name)\n}", "func (z *zfsctl) MountFileSystem(ctx context.Context, name, options, opts string, all bool) *execute {\n\targs := []string{\"mount\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif len(opts) > 0 {\n\t\targs = append(args, opts)\n\t}\n\tif all {\n\t\targs = append(args, \"-a\")\n\t} else {\n\t\targs = append(args, name)\n\t}\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (linux *Linux) FileCreate(filePath string) error {\n\tif !linux.FileExists(filePath) {\n\t\tfile, err := os.Create(linux.applyChroot(filePath))\n\t\tdefer file.Close()\n\t\treturn err\n\t}\n\treturn os.ErrExist\n}", "func (c *Client) Create(path gfs.Path) error {\n\tvar reply gfs.CreateFileReply\n\terr := util.Call(c.master, \"Master.RPCCreateFile\", gfs.CreateFileArg{path}, &reply)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func createDirectories() error {\n\n\tvar brickPath = glusterBrickPath + \"/\" + glusterVolumeName\n\tvar mountPath = glusterMountPath + \"/\" + glusterVolumeName\n\tvar volumePath = glusterDockerVolumePath\n\n\tdirPath := []string{brickPath, mountPath, volumePath}\n\n\tfor i := 0; i < len(dirPath); i++ {\n\t\tif helpers.Exists(dirPath[i]) == false {\n\t\t\terr := helpers.CreateDir(dirPath[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateFilesystem(path string) error {\n\treturn nil\n}", "func (cs *ControllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {\n\tname := req.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume name must be provided\")\n\t}\n\tif err := cs.validateVolumeCapabilities(req.GetVolumeCapabilities()); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\treqCapacity := req.GetCapacityRange().GetRequiredBytes()\n\tnfsVol, err := cs.newNFSVolume(name, reqCapacity, req.GetParameters())\n\tif err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tvar volCap *csi.VolumeCapability\n\tif len(req.GetVolumeCapabilities()) > 0 {\n\t\tvolCap = req.GetVolumeCapabilities()[0]\n\t} // 执行挂载 命令\n\t// Mount nfs base share so we can create a subdirectory\n\tif err = cs.internalMount(ctx, nfsVol, volCap); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to mount nfs server: %v\", err.Error())\n\t}\n\tdefer func() {\n\t\tif err = cs.internalUnmount(ctx, nfsVol); err != nil {\n\t\t\tklog.Warningf(\"failed to unmount nfs server: %v\", err.Error())\n\t\t}\n\t}()\n\n\t// Create subdirectory under base-dir\n\t// TODO: revisit permissions\n\tinternalVolumePath := cs.getInternalVolumePath(nfsVol)\n\tif err = os.Mkdir(internalVolumePath, 0777); err != nil && !os.IsExist(err) {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to make subdirectory: %v\", err.Error())\n\t}\n\t// Remove capacity setting when provisioner 1.4.0 is available with fix for\n\t// https://github.com/kubernetes-csi/external-provisioner/pull/271\n\treturn &csi.CreateVolumeResponse{Volume: cs.nfsVolToCSI(nfsVol, reqCapacity)}, nil\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func createFormatFS(fsPath string) error {\n\tfsFormatPath := pathJoin(fsPath, minioMetaBucket, formatConfigFile)\n\n\t// Attempt a write lock on formatConfigFile `format.json`\n\t// file stored in minioMetaBucket(.minio.sys) directory.\n\tlk, err := lock.TryLockedOpenFile((fsFormatPath), os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn traceError(err)\n\t}\n\t// Close the locked file upon return.\n\tdefer lk.Close()\n\n\t// Load format on disk, checks if we are unformatted\n\t// writes the new format.json\n\tvar format = &formatConfigV1{}\n\terr = format.LoadFormat(lk)\n\tif errorCause(err) == errUnformattedDisk {\n\t\t_, err = newFSFormat().WriteTo(lk)\n\t\treturn err\n\t}\n\treturn err\n}", "func (self *File_Client) CreateDir(path interface{}, name interface{}) error {\n\n\trqst := &filepb.CreateDirRequest{\n\t\tPath: Utility.ToString(path),\n\t\tName: Utility.ToString(name),\n\t}\n\n\t_, err := self.c.CreateDir(context.Background(), rqst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fs *EmbedFs) Create(path string) (file, error) {\n\treturn nil, ErrNotAvail\n}", "func NewFileSystem() FileSystem {\r\n\treturn &osFileSystem{}\r\n}", "func (c *fileSystemClient) CreateVolumeForWrite(ctx context.Context, in *fs.CreateVolumeForWriteRequest, opts ...grpc.CallOption) (*fs.CreateVolumeForWriteResponse, error) {\n\treturn c.c.CreateVolumeForWrite(ctx, in, opts...)\n}", "func NewFileSystem() FileSystem {\n\treturn &fs{\n\t\trunner: NewCommandRunner(),\n\t}\n}", "func (f *Fs) mkdir(ctx context.Context, dirPath string) (err error) {\n\t// defer log.Trace(dirPath, \"\")(\"err=%v\", &err)\n\terr = f._mkdir(ctx, dirPath)\n\tif apiErr, ok := err.(*api.Error); ok {\n\t\t// parent does not exist so create it first then try again\n\t\tif apiErr.StatusCode == http.StatusConflict {\n\t\t\terr = f.mkParentDir(ctx, dirPath)\n\t\t\tif err == nil {\n\t\t\t\terr = f._mkdir(ctx, dirPath)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (fs *Mysqlfs) Create(filename string) (billy.File, error) {\n\treturn fs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)\n}", "func Create(name string) (*os.File, error)", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func Create(path string, data []byte) error {\n\tif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(path, data, 0755)\n}", "func (d *Definition) Create() error {\n\terrChan := make(chan error)\n\ttree := d.ResourceTree\n\n\t// Check definition context exists\n\tif _, err := os.Stat(tree.Root().ID()); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t`Definition Create: Expected context: \"%s\" to exist.`,\n\t\t\ttree.Root().Name(),\n\t\t)\n\t}\n\n\tgo func() {\n\t\tdefer close(errChan)\n\t\ttree.Traverse(func(r Resource) {\n\t\t\terrChan <- r.Create(d.Options)\n\t\t})\n\t}()\n\n\tfor err := range errChan {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Definition Create: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewFileSystemClient() (FileSystemClient, error) {\n\taddress := os.Getenv(constants.EnvFileSystemAddress)\n\tif address == \"\" {\n\t\treturn nil, fmt.Errorf(\"Environment variable '%s' not set\", constants.EnvFileSystemAddress)\n\t}\n\n\t// Create a connection\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a client\n\tc := fs.NewFileSystemClient(conn)\n\n\treturn &fileSystemClient{c: c, conn: conn}, nil\n}", "func (obj *ocsCephFilesystems) ensureCreated(r *StorageClusterReconciler, instance *ocsv1.StorageCluster) (reconcile.Result, error) {\n\treconcileStrategy := ReconcileStrategy(instance.Spec.ManagedResources.CephFilesystems.ReconcileStrategy)\n\tif reconcileStrategy == ReconcileStrategyIgnore {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\tcephFilesystems, err := r.newCephFilesystemInstances(instance)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\tfor _, cephFilesystem := range cephFilesystems {\n\t\texisting := cephv1.CephFilesystem{}\n\t\terr = r.Client.Get(context.TODO(), types.NamespacedName{Name: cephFilesystem.Name, Namespace: cephFilesystem.Namespace}, &existing)\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tif reconcileStrategy == ReconcileStrategyInit {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\t\t\tif existing.DeletionTimestamp != nil {\n\t\t\t\tr.Log.Info(\"Unable to restore CephFileSystem because it is marked for deletion.\", \"CephFileSystem\", klog.KRef(existing.Namespace, existing.Name))\n\t\t\t\treturn reconcile.Result{}, fmt.Errorf(\"failed to restore initialization object %s because it is marked for deletion\", existing.Name)\n\t\t\t}\n\n\t\t\tr.Log.Info(\"Restoring original CephFilesystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\texisting.ObjectMeta.OwnerReferences = cephFilesystem.ObjectMeta.OwnerReferences\n\t\t\texisting.Spec = cephFilesystem.Spec\n\t\t\terr = r.Client.Update(context.TODO(), &existing)\n\t\t\tif err != nil {\n\t\t\t\tr.Log.Error(err, \"Unable to update CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\tcase errors.IsNotFound(err):\n\t\t\tr.Log.Info(\"Creating CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\terr = r.Client.Create(context.TODO(), cephFilesystem)\n\t\t\tif err != nil {\n\t\t\t\tr.Log.Error(err, \"Unable to create CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn reconcile.Result{}, nil\n}", "func (fb *FileBase) Create(ID string) (io.WriteCloser, error) {\n\treturn fb.fs.Create(filepath.Join(fb.root, ID))\n}", "func (ts *TaskService) Create(ctx context.Context, req *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\tlogger := log.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"bundle\": req.Bundle})\n\tlogger.Info(\"create\")\n\n\textraData, err := unmarshalExtraData(req.Options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbundleDir := bundle.Dir(filepath.Join(containerRootDir, req.ID))\n\terr = bundleDir.Create()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = bundleDir.OCIConfig().Write(extraData.JsonSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO replace with proper drive mounting once that PR is merged. Right now, all containers in\n\t// this VM start up with the same rootfs image no matter their configuration\n\terr = bundleDir.MountRootfs(\"/dev/vdb\", \"ext4\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a runc shim to manage this task\n\t// TODO if we update to the v2 runc implementation in containerd, we can use a single\n\t// runc service instance to manage all tasks instead of creating a new one for each\n\truncService, err := runc.New(ctx, req.ID, ts.eventExchange)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Override the incoming stdio FIFOs, which have paths from the host that we can't use\n\tfifoSet, err := cio.NewFIFOSetInDir(bundleDir.RootPath(), req.ID, req.Terminal)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"failed opening stdio FIFOs\")\n\t\treturn nil, err\n\t}\n\n\t// Don't try to connect any io streams that weren't requested by the client\n\tif req.Stdin == \"\" {\n\t\tfifoSet.Stdin = \"\"\n\t}\n\n\tif req.Stdout == \"\" {\n\t\tfifoSet.Stdout = \"\"\n\t}\n\n\tif req.Stderr == \"\" {\n\t\tfifoSet.Stderr = \"\"\n\t}\n\n\ttask, err := ts.taskManager.AddTask(ctx, req.ID, runcService, bundleDir, extraData, fifoSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Debug(\"calling runc create\")\n\n\t// Override some of the incoming paths, which were set on the Host and thus not valid here in the Guest\n\treq.Bundle = bundleDir.RootPath()\n\treq.Rootfs = nil\n\treq.Stdin = fifoSet.Stdin\n\treq.Stdout = fifoSet.Stdout\n\treq.Stderr = fifoSet.Stderr\n\n\t// Just provide runc the options it knows about, not our wrapper\n\treq.Options = task.ExtraData().GetRuncOptions()\n\n\t// Start the io proxy and wait for initialization to complete before starting\n\t// the task to ensure we capture all task output\n\terr = <-task.StartStdioProxy(ctx, vm.VSockToFIFO, acceptVSock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := task.Create(ctx, req)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"error creating container\")\n\t\treturn nil, err\n\t}\n\n\tlogger.WithField(\"pid\", resp.Pid).Debugf(\"create succeeded\")\n\treturn resp, nil\n}", "func (p *Path) create() error {\n\tif _, err := fs.Stat(p.name); os.IsNotExist(err) {\n\t\terr := fs.MkdirAll(p.name, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"Created missing directory:\", p.name)\n\t}\n\treturn nil\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func (m *FileSystem) Create(file string) (io.Writer, error) {\n\tret := m.ctrl.Call(m, \"Create\", file)\n\tret0, _ := ret[0].(io.Writer)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (a *FileStorageApiService) CreateDirectoryExecute(r ApiCreateDirectoryRequest) (SingleNode, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SingleNode\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.Ctx, \"FileStorageApiService.CreateDirectory\")\n\tif localBasePath == \"/\" {\n\t localBasePath = \"\"\n\t}\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v2/file_storage/buckets/{bucket_id}/create_directory\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucket_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_bucketId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.P_nodeRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"nodeRequest is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\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\t// body params\n\tlocalVarPostBody = r.P_nodeRequest\n\treq, err := a.client.prepareRequest(r.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(req)\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 CreateRecursive(ctx context.Context, conn *ZkConn, zkPath string, value []byte, flags int32, aclv []zk.ACL, maxCreationDepth int) (string, error) {\n\tpathCreated, err := conn.Create(ctx, zkPath, value, flags, aclv)\n\tif err == zk.ErrNoNode {\n\t\tif maxCreationDepth == 0 {\n\t\t\treturn \"\", zk.ErrNoNode\n\t\t}\n\n\t\t// Make sure that nodes are either \"file\" or\n\t\t// \"directory\" to mirror file system semantics.\n\t\tdirAclv := make([]zk.ACL, len(aclv))\n\t\tfor i, acl := range aclv {\n\t\t\tdirAclv[i] = acl\n\t\t\tdirAclv[i].Perms = PermDirectory\n\t\t}\n\t\tparentPath := path.Dir(zkPath)\n\t\t_, err = CreateRecursive(ctx, conn, parentPath, nil, 0, dirAclv, maxCreationDepth-1)\n\t\tif err != nil && err != zk.ErrNodeExists {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpathCreated, err = conn.Create(ctx, zkPath, value, flags, aclv)\n\t}\n\treturn pathCreated, err\n}", "func (ts *TaskService) Create(requestCtx context.Context, req *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\ttaskID := req.ID\n\texecID := \"\" // the exec ID of the initial process in a task is an empty string by containerd convention\n\n\tlogger := log.G(requestCtx).WithField(\"TaskID\", taskID).WithField(\"ExecID\", execID)\n\tlogger.Info(\"create\")\n\n\textraData, err := unmarshalExtraData(req.Options)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal extra data\")\n\t}\n\n\t// Just provide runc the options it knows about, not our wrapper\n\treq.Options = extraData.RuncOptions\n\n\t// Override the bundle dir and rootfs paths, which were set on the Host and thus not valid here in the Guest\n\tbundleDir := bundle.Dir(filepath.Join(containerRootDir, taskID))\n\terr = bundleDir.Create()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create bundle dir\")\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tremoveErr := os.RemoveAll(bundleDir.RootPath())\n\t\t\tif removeErr != nil {\n\t\t\t\tlogger.WithError(removeErr).Error(\"failed to cleanup bundle dir\")\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = bundleDir.OCIConfig().Write(extraData.JsonSpec)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to write oci config file\")\n\t}\n\n\tdriveID := strings.TrimSpace(extraData.DriveID)\n\tdrive, ok := ts.driveHandler.GetDrive(driveID)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Drive %q could not be found\", driveID)\n\t}\n\n\tconst (\n\t\tmaxRetries = 100\n\t\tretryDelay = 10 * time.Millisecond\n\t)\n\n\t// We retry here due to guest kernel needing some time to populate the guest\n\t// drive.\n\t// https://github.com/firecracker-microvm/firecracker/issues/1159\n\tfor i := 0; i < maxRetries; i++ {\n\t\tif err = bundleDir.MountRootfs(drive.Path(), \"ext4\", nil); isRetryableMountError(err) {\n\t\t\tlogger.WithError(err).Warnf(\"retrying to mount rootfs %q\", drive.Path())\n\n\t\t\ttime.Sleep(retryDelay)\n\t\t\tcontinue\n\t\t}\n\n\t\tbreak\n\t}\n\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to mount rootfs %q\", drive.Path())\n\t}\n\n\treq.Bundle = bundleDir.RootPath()\n\treq.Rootfs = nil\n\n\tvar ioConnectorSet vm.IOProxy\n\n\tif vm.IsAgentOnlyIO(req.Stdout, logger) {\n\t\tioConnectorSet = vm.NewNullIOProxy()\n\t} else {\n\t\t// Override the incoming stdio FIFOs, which have paths from the host that we can't use\n\t\tfifoSet, err := cio.NewFIFOSetInDir(bundleDir.RootPath(), fifoName(taskID, execID), req.Terminal)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"failed opening stdio FIFOs\")\n\t\t\treturn nil, errors.Wrap(err, \"failed to open stdio FIFOs\")\n\t\t}\n\n\t\tvar stdinConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdin != \"\" {\n\t\t\treq.Stdin = fifoSet.Stdin\n\t\t\tstdinConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.VSockAcceptConnector(extraData.StdinPort),\n\t\t\t\tWriteConnector: vm.FIFOConnector(fifoSet.Stdin),\n\t\t\t}\n\t\t}\n\n\t\tvar stdoutConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdout != \"\" {\n\t\t\treq.Stdout = fifoSet.Stdout\n\t\t\tstdoutConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stdout),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StdoutPort),\n\t\t\t}\n\t\t}\n\n\t\tvar stderrConnectorPair *vm.IOConnectorPair\n\t\tif req.Stderr != \"\" {\n\t\t\treq.Stderr = fifoSet.Stderr\n\t\t\tstderrConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stderr),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StderrPort),\n\t\t\t}\n\t\t}\n\n\t\tioConnectorSet = vm.NewIOConnectorProxy(stdinConnectorPair, stdoutConnectorPair, stderrConnectorPair)\n\t}\n\n\tresp, err := ts.taskManager.CreateTask(requestCtx, req, ts.runcService, ioConnectorSet)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create runc shim for task\")\n\t}\n\n\tlogger.WithField(\"pid\", resp.Pid).Debugf(\"create succeeded\")\n\treturn resp, nil\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func (f *Fs) Create(name string) (afero.File, error) {\n\treturn f.AferoFs.Create(name)\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func CreateFiles(fS *FileCollection, ts int64, filelock chan int64) {\n\tvar lt time.Time\n\tvar err error\n\n\tselect {\n\tcase <- time.After(5 * time.Second):\n\t\t//If 5 seconds pass without getting the proper lock, abort\n\t\tlog.Printf(\"partdisk.CreateFiles(): timeout waiting for lock\\n\")\n\t\treturn\n\tcase chts := <- filelock:\n\t\tif chts == ts { //Got the lock and it matches the timestamp received\n\t\t\t//Proceed\n\t\t\tfS.flid = ts\n\t\t\tdefer func(){\n\t\t\t\tfilelock <- 0 //Release lock\n\t\t\t}()\n\t\t\tlt = time.Now() //Start counting how long does the parts creation take\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, timestamps match: %d\\n\",ts)\n\t\t} else {\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, but timestamps missmatch: %d - %d\\n\", ts,chts)\n\t\t\tfilelock <- chts\n\t\t\treturn\n\t\t}\n\t}\n\t//Lock obtained proper, create/delete the files\n\terr = adrefiles(fS)\n\tif err != nil {\n\t\tlog.Printf(\"CreateFiles(): Error creating file: %s\\n\",err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"CreateFiles(): Request %d completed in %d seconds\\n\",ts,int64(time.Since(lt).Seconds()))\n}", "func (p *Tmpfs) Create(ctx driver.Context, id types.VolumeID) (*types.Volume, error) {\n\tctx.Log.Debugf(\"Tmpfs create volume: %s\", id.Name)\n\n\t// parse the mount path\n\tmountPath := path.Join(dataDir, id.Name)\n\n\treturn types.NewVolumeFromID(mountPath, \"\", id), nil\n}", "func MakeFileSystem(idp string, typef byte) {\n\tvar flgfound bool = false\n\tmpartition := Mounted{}\n\tfor _, mp := range sliceMP {\n\t\tidm := \"vd\" + string(mp.Letter) + strconv.FormatInt(mp.Number, 10)\n\t\tif idp == idm {\n\t\t\tflgfound = true\n\t\t\tmpartition = mp\n\t\t\tbreak\n\t\t}\n\t}\n\tif flgfound {\n\t\tvar bname [16]byte\n\t\tpartition := mpartition.Part\n\t\t// Se realiza el formateo de la partición\n\t\tif typef == 'u' {\n\t\t\twriteByteArray(mpartition.Path, partition.PartStart, partition.PartSize)\n\t\t}\n\t\t// Current Position Disk Partition\n\t\tvar cpd int64\n\t\t// Se obtiene el tamaño de las estructuras y la cantidad (#Estructuras)\n\t\tsStrc, cStrc := GetNumberOfStructures(partition.PartSize)\n\t\t// Se creará el Super Boot\n\t\tnewSB := SuperBoot{}\n\t\t// Nombre HD\n\t\tcopy(bname[:], mpartition.Name)\n\t\tnewSB.NombreHd = bname\n\t\tnewSB.FechaCreacion = getCurrentTime()\n\t\tnewSB.FechaUltimoMontaje = mpartition.TMount\n\t\tnewSB.ConteoMontajes = 1\n\t\t// Cantidad de estructuras creadas\n\t\tnewSB.CantArbolVirtual = 1\n\t\tnewSB.CantDetalleDirectorio = 1\n\t\tnewSB.CantidadInodos = 1\n\t\tnewSB.CantidadBloques = 2\n\t\t// Cantidad de estructuras ocupadas...\n\t\tnewSB.ArbolesVirtualesLibres = cStrc - 1\n\t\tnewSB.DetallesDirectorioLibres = cStrc - 1\n\t\tnewSB.InodosLibres = (cStrc * 5) - 1\n\t\tnewSB.BloquesLibres = (cStrc * 20) - 2 // Por los dos bloques del archivo user.txt\n\t\t// Inicio BMap AVD = Inicio_Particion + SizeSB\n\t\tcpd = partition.PartStart + sStrc.sizeSB\n\t\tnewSB.AptBmapArbolDirectorio = cpd\n\t\t// Inicio AVD = Inicio BitMap AVD + #Estructuras\n\t\tcpd = cpd + cStrc\n\t\tnewSB.AptArbolDirectorio = cpd\n\t\t// Inicio BMap DDir = Inicio AVD + (sizeAVD*#Estructuras)\n\t\tcpd = cpd + (sStrc.sizeAV * cStrc)\n\t\tnewSB.AptBmapDetalleDirectorio = cpd\n\t\t// Inicio DDir = Inicio BMap DDir + #Estructuras\n\t\tcpd = cpd + cStrc\n\t\tnewSB.AptDetalleDirectorio = cpd\n\t\t// Inicio BMap Inodo = Inicio DDir + (sizeDDir * #Estructuras)\n\t\tcpd = cpd + (sStrc.sizeDDir * cStrc)\n\t\tnewSB.AptBmapTablaInodo = cpd\n\t\t// Inicio Inodos = Inicio BMap Inodo + (5 * sizeInodo)\n\t\tcpd = cpd + (5 * cStrc)\n\t\tnewSB.AptTablaInodo = cpd\n\t\t// Inicio BMap Bloque = Inicio Inodos + (5 * sizeInodo * #Estructuras)\n\t\tcpd = cpd + (5 * sStrc.sizeInodo * cStrc)\n\t\tnewSB.AptBmapBloques = cpd\n\t\t// Inicio Bloque = Inicio Inodo + (20 * #Estructuras)\n\t\tcpd = cpd + (20 * cStrc)\n\t\tnewSB.AptBloques = cpd\n\t\t// Inicio Bitacora (Log) = Inicio Bloque + (20 * sizeBloque * #Estructuras)\n\t\tcpd = cpd + (20 * sStrc.sizeBD * cStrc)\n\t\tnewSB.AptLog = cpd\n\t\t// Inicio Copia SB = Inicio Bitacora + (sizeLog * #Estructuras)\n\t\tcpd = cpd + (sStrc.sizeLog * cStrc)\n\t\t//--- Se guarda el tamaño de las estructuras ------------------------------------\n\t\tnewSB.TamStrcArbolDirectorio = sStrc.sizeAV\n\t\tnewSB.TamStrcDetalleDirectorio = sStrc.sizeDDir\n\t\tnewSB.TamStrcInodo = sStrc.sizeInodo\n\t\tnewSB.TamStrcBloque = sStrc.sizeBD\n\t\t//--- Se guarda el primer bit vacio del bitmap de cada estructura ---------------\n\t\tnewSB.PrimerBitLibreArbolDir = 2\n\t\tnewSB.PrimerBitLibreDetalleDir = 2\n\t\tnewSB.PrimerBitLibreTablaInodo = 2\n\t\tnewSB.PrimerBitLibreBloques = 3\n\t\t//--- Numero Magico -------------------------------------------------------------\n\t\tnewSB.NumeroMagico = 201503442\n\t\t//--- Escribir SB en Disco ------------------------------------------------------\n\t\tWriteSuperBoot(mpartition.Path, newSB, partition.PartStart)\n\t\t//--- Escritura de la Copia de SB -----------------------------------------------\n\t\tWriteSuperBoot(mpartition.Path, newSB, cpd)\n\t\t//--- (1) Crear un AVD : root \"/\" -----------------------------------------------\n\t\tavdRoot := ArbolVirtualDir{}\n\t\tavdRoot.FechaCreacion = getCurrentTime()\n\t\tcopy(avdRoot.NombreDirectorio[:], \"/\")\n\t\tcopy(avdRoot.AvdPropietario[:], \"root\")\n\t\tcopy(avdRoot.AvdGID[:], \"root\")\n\t\tavdRoot.AvdPermisos = 777\n\t\tavdRoot.AptDetalleDirectorio = 1\n\t\tWriteAVD(mpartition.Path, avdRoot, newSB.AptArbolDirectorio)\n\t\t//--- (2) Crear un Detalle de Directorio ----------------------------------------\n\t\tdetalleDir := DetalleDirectorio{}\n\t\tarchivoInf := InfoArchivo{}\n\t\tarchivoInf.FechaCreacion = getCurrentTime()\n\t\tarchivoInf.FechaModifiacion = getCurrentTime()\n\t\tcopy(archivoInf.FileName[:], \"user.txt\")\n\t\tarchivoInf.ApInodo = 1\n\t\tdetalleDir.InfoFile[0] = archivoInf\n\t\tWriteDetalleDir(mpartition.Path, detalleDir, newSB.AptDetalleDirectorio)\n\t\t//--- (3) Crear una Tabla de Inodo ----------------------------------------------\n\t\tstrAux := \"1,G,root\\n1,U,root,201503442\\n\"\n\t\ttbInodo := TablaInodo{}\n\t\ttbInodo.NumeroInodo = 1 // Primer Inodo creado\n\t\ttbInodo.SizeArchivo = int64(len(strAux))\n\t\ttbInodo.CantBloquesAsignados = 2\n\t\ttbInodo.AptBloques[0] = int64(1)\n\t\ttbInodo.AptBloques[1] = int64(2)\n\t\tcopy(tbInodo.IDPropietario[:], \"root\")\n\t\tcopy(tbInodo.IDUGrupo[:], \"root\")\n\t\ttbInodo.IPermisos = 777\n\t\tWriteTInodo(mpartition.Path, tbInodo, newSB.AptTablaInodo)\n\t\t//--- (4) Creación de los Bloques de datos --------------------------------------\n\t\tbloque1 := BloqueDeDatos{}\n\t\tcopy(bloque1.Data[:], strAux[0:25])\n\t\tWriteBloqueD(mpartition.Path, bloque1, newSB.AptBloques)\n\t\tbloque2 := BloqueDeDatos{}\n\t\tcopy(bloque2.Data[:], strAux[25:len(strAux)])\n\t\tWriteBloqueD(mpartition.Path, bloque2, newSB.AptBloques+newSB.TamStrcBloque)\n\t\t//--- (5) Escribir en BitMap ----------------------------------------------------\n\t\tauxBytes := []byte{1}\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapArbolDirectorio)\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapDetalleDirectorio)\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapTablaInodo)\n\t\tauxBytes = append(auxBytes, 1)\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapBloques)\n\t} else {\n\t\tfmt.Println(\"[!] La particion\", idp, \" no se encuentra montada...\")\n\t}\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\t// fmt.Printf(\"creating file in dir with inode %d\\n\", d.inodeNum)\n\t// fmt.Println(\"name of file to be created is: \" + req.Name)\n\tdirTable, err := getTable(d.inode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileExists := dirTable.Table[req.Name] != 0\n\tvar inode *Inode\n\tvar inodeNum uint64\n\tif !fileExists {\n\t\t// fmt.Println(\"file does not yet exist in Create\")\n\t\tvar isDir int8 = 0\n\t\tinode = createInode(isDir)\n\t\tinodeNum = d.inodeStream.next()\n\t\tinode.init(d.inodeNum, inodeNum)\n\t\td.addFile(req.Name, inodeNum)\n\t} else {\n\t\t// fmt.Println(\"file already exists in Create\")\n\t\tinodeNum = dirTable.Table[req.Name]\n\t\tinode, err = getInode(inodeNum)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tchild := &File{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t\tinodeStream: d.inodeStream,\n\t}\n\thandle := &FileHandle{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t}\n\t// can any errors happen here?\n\treturn child, handle, nil\n}", "func NewFileSystem(t mockConstructorTestingTNewFileSystem) *FileSystem {\n\tmock := &FileSystem{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (client StorageGatewayClient) connectFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems/{fileSystemName}/actions/connect\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ConnectFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func NewFileSystem(ctrl *gomock.Controller) *FileSystem {\n\tmock := &FileSystem{ctrl: ctrl}\n\tmock.recorder = &FileSystemMockRecorder{mock}\n\treturn mock\n}", "func (a DBFSAPI) Create(path string, overwrite bool, data string) (err error) {\n\tbyteArr, err := base64.StdEncoding.DecodeString(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbyteChunks := split(byteArr, 1e6)\n\thandle, err := a.createHandle(path, overwrite)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\terr = a.closeHandle(handle)\n\t}()\n\tfor _, byteChunk := range byteChunks {\n\t\tb64Data := base64.StdEncoding.EncodeToString(byteChunk)\n\t\terr := a.addBlock(b64Data, handle)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func NewFS(basedir string) (kvs *FS, err error) {\n\treturn newFileSystem(basedir, os.MkdirAll)\n}", "func (d Dir) Create(name string) (*os.File, error) {\n\tif d.env == \"\" {\n\t\treturn nil, errors.New(\"xdgdir: Create on zero Dir\")\n\t}\n\tp := d.Path()\n\tif p == \"\" {\n\t\treturn nil, fmt.Errorf(\"xdgdir: create %s: %s is invalid or not set\", name, d.env)\n\t}\n\tfp := filepath.Join(p, name)\n\tif err := os.MkdirAll(filepath.Dir(fp), 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.Create(fp)\n}", "func (client StorageGatewayClient) ConnectFileSystem(ctx context.Context, request ConnectFileSystemRequest) (response ConnectFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.connectFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ConnectFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ConnectFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ConnectFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ConnectFileSystemResponse\")\n\t}\n\treturn\n}", "func setupFilesystem(ctx context.Context, path string, forETL bool) (res fileservice.FileService, readPath string, err error) {\n\treturn setupFileservice(ctx, &pathConfig{\n\t\tisS3: false,\n\t\tforETL: forETL,\n\t\tfilesystemConfig: filesystemConfig{path: path},\n\t})\n}", "func (tfs *TierFS) Create(namespace string) (StoredFile, error) {\n\tif err := validateNamespace(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid args: %w\", err)\n\t}\n\n\tif err := tfs.createNSWorkspaceDir(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"create namespace dir: %w\", err)\n\t}\n\n\ttempPath := tfs.workspaceTempFilePath(namespace)\n\tfh, err := os.Create(tempPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating file: %w\", err)\n\t}\n\n\treturn &WRFile{\n\t\tFile: fh,\n\t\tstore: func(filename string) error {\n\t\t\treturn tfs.store(namespace, tempPath, filename)\n\t\t},\n\t}, nil\n}", "func TestMountCreat(t *testing.T) {\n\tconst concurrency = 2\n\tconst repeat = 2\n\n\tdir := test_helpers.InitFS(t)\n\tmnt := dir + \".mnt\"\n\n\tfor j := 0; j < repeat; j++ {\n\t\ttest_helpers.MountOrFatal(t, dir, mnt, \"-extpass=echo test\")\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(concurrency)\n\t\tfor i := 0; i < concurrency; i++ {\n\t\t\tgo func(i int) {\n\t\t\t\tpath := fmt.Sprintf(\"%s/%d\", mnt, i)\n\t\t\t\tfd, err := syscall.Open(path, syscall.O_CREAT|syscall.O_WRONLY|syscall.O_TRUNC, 0600)\n\t\t\t\tsyscall.Close(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Creat %q: %v\", path, err)\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(i)\n\t\t}\n\t\twg.Wait()\n\t\ttest_helpers.UnmountPanic(mnt)\n\t}\n}", "func (b *Bundler) Create(name string) (afero.File, error) {\n\terr := b.fs.MkdirAll(filepath.Dir(name), fileMode)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating file: %w\", err)\n\t}\n\n\tfile, err := b.fs.Create(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating file: %w\", err)\n\t}\n\n\treturn file, nil\n}", "func OpenFileSystem(filename string) FileSystem {\n\treturn nil\n}", "func (c *fileSystemClient) CreateVolumeForRead(ctx context.Context, in *fs.CreateVolumeForReadRequest, opts ...grpc.CallOption) (*fs.CreateVolumeForReadResponse, error) {\n\treturn c.c.CreateVolumeForRead(ctx, in, opts...)\n}", "func (z *ZkPlus) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tz.forPath(path).Log(logkey.ZkMethod, \"Create\")\n\tp, err := z.blockOnConn().Create(z.realPath(path), data, flags, acl)\n\tif strings.HasPrefix(p, z.pathPrefix) && z.pathPrefix != \"\" {\n\t\tp = p[len(z.pathPrefix)+1:]\n\t}\n\treturn p, errors.Annotatef(err, \"cannot create zk path %s\", path)\n}", "func (d ImagefsDriver) Create(r *volume.CreateRequest) error {\n\tfmt.Printf(\"-> Create %+v\\n\", r)\n\tsource, ok := r.Options[\"source\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"no source volume specified\")\n\t}\n\n\t// pull the image\n\t/*readCloser, err := d.cli.ImagePull(context.Background(), source, types.ImagePullOptions{\n\t\t// HACK assume the registry ignores the auth header\n\t\tRegistryAuth: \"null\",\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error: %s\", err)\n\t}\n\tscanner := bufio.NewScanner(readCloser)\n\tfor scanner.Scan() {\n\t}*/\n\n\tcontainerConfig := &container.Config{\n\t\tImage: source,\n\t\tEntrypoint: []string{\"/runtime/loop\"},\n\t\tLabels: map[string]string{\n\t\t\t\"com.docker.imagefs.version\": version,\n\t\t},\n\t\tNetworkDisabled: true,\n\t}\n\n\tif target, ok := r.Options[\"target\"]; ok {\n\t\tcontainerConfig.Labels[\"com.docker.imagefs.target\"] = target\n\t}\n\t// TODO handle error\n\thostConfig := &container.HostConfig{\n\t\tBinds: []string{\"/tmp/runtime:/runtime\"},\n\t\t//AutoRemove: true,\n\t}\n\n\tvar platform *specs.Platform\n\tif platformStr, ok := r.Options[\"platform\"]; ok {\n\t\tif versions.GreaterThanOrEqualTo(d.cli.ClientVersion(), \"1.41\") {\n\t\t\tp, err := platforms.Parse(platformStr)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error parsing specified platform\")\n\t\t\t}\n\t\t\tplatform = &p\n\t\t}\n\t}\n\n\tnetworkConfig := &network.NetworkingConfig{}\n\tcont, err := d.cli.ContainerCreate(\n\t\tcontext.Background(),\n\t\tcontainerConfig,\n\t\thostConfig,\n\t\tnetworkConfig,\n\t\tplatform,\n\t\t// TODO(rabrams) namespace\n\t\tr.Name,\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error: %s\", err)\n\t}\n\tfmt.Printf(\"Temp container ID: %s\", cont.ID)\n\td.cli.ContainerStart(\n\t\tcontext.Background(),\n\t\tcont.ID,\n\t\ttypes.ContainerStartOptions{},\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error: %s\", err)\n\t}\n\treturn nil\n}", "func (tfs *TierFS) Create(namespace string) (*File, error) {\n\tif err := validateNamespace(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid args: %w\", err)\n\t}\n\n\tif err := tfs.createNSWorkspaceDir(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"create namespace dir: %w\", err)\n\t}\n\n\ttempPath := tfs.workspaceTempFilePath(namespace)\n\tfh, err := os.Create(tempPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating file: %w\", err)\n\t}\n\n\treturn &File{\n\t\tfh: fh,\n\t\tstore: func(filename string) error {\n\t\t\treturn tfs.store(namespace, tempPath, filename)\n\t\t},\n\t}, nil\n}", "func getFileSystem(frame *rtda.Frame) {\n\tthread := frame.Thread\n\tunixFsClass := frame.GetClassLoader().LoadClass(\"java/io/UnixFileSystem\")\n\tif unixFsClass.InitializationNotStarted() {\n\t\tframe.NextPC = thread.PC // undo getFileSystem\n\t\tthread.InitClass(unixFsClass)\n\t\treturn\n\t}\n\n\tunixFsObj := unixFsClass.NewObj()\n\tframe.PushRef(unixFsObj)\n\n\t// call <init>\n\tframe.PushRef(unixFsObj) // this\n\tconstructor := unixFsClass.GetDefaultConstructor()\n\tthread.InvokeMethod(constructor)\n}", "func NewFileSystemClient() FileSystemClient {\n\treturn FsClient{}\n}", "func createDir(path string, host string) error {\n\tsshCmd := fmt.Sprintf(\"mkdir -p %s\", path)\n\tframework.Logf(\"Invoking command '%v' on ESX host %v\", sshCmd, host)\n\tresult, err := fssh.SSH(sshCmd, host+\":22\", framework.TestContext.Provider)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: '%s' on ESX host: %v\", sshCmd, err)\n\t}\n\treturn nil\n}", "func createFile( filename string) {\n f, err := os.Create(filename)\n u.ErrNil(err, \"Unable to create file\")\n defer f.Close()\n log.Printf(\"Created %s\\n\", f.Name())\n}", "func (s stage) createFilesystemsFiles(config types.Config) error {\n\tif len(config.Storage.Filesystems) == 0 {\n\t\treturn nil\n\t}\n\ts.Logger.PushPrefix(\"createFilesystemsFiles\")\n\tdefer s.Logger.PopPrefix()\n\n\tfileMap, err := s.mapFilesToFilesystems(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor fs, f := range fileMap {\n\t\tif err := s.createFiles(fs, f); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create files: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}" ]
[ "0.7532974", "0.72078437", "0.71549237", "0.709281", "0.7048207", "0.7030605", "0.70085895", "0.6557903", "0.6551424", "0.6468269", "0.6361563", "0.63513356", "0.62807924", "0.62282985", "0.60684615", "0.6032318", "0.60243344", "0.6024124", "0.5850698", "0.5837949", "0.58215404", "0.5810168", "0.57509744", "0.5714654", "0.57115144", "0.5705758", "0.56912595", "0.5687771", "0.5687322", "0.56753075", "0.56544155", "0.5639041", "0.56385124", "0.56263703", "0.56133443", "0.55980855", "0.5580407", "0.5572527", "0.554794", "0.55458665", "0.55422986", "0.55417556", "0.5535347", "0.5501125", "0.54907024", "0.5486937", "0.5483352", "0.5479818", "0.54775447", "0.54694265", "0.5465236", "0.5435946", "0.5434246", "0.542073", "0.5413105", "0.5404915", "0.5403999", "0.53954613", "0.5391681", "0.5388665", "0.5383335", "0.53696805", "0.53653055", "0.53588873", "0.5355973", "0.5339503", "0.5306384", "0.53048205", "0.53014916", "0.52904594", "0.5267698", "0.5260379", "0.52532434", "0.52514195", "0.52505386", "0.5225272", "0.52097625", "0.51984113", "0.51943094", "0.5193183", "0.51904637", "0.5171209", "0.51609224", "0.5158876", "0.5148563", "0.5142918", "0.5137802", "0.5120682", "0.51134884", "0.51048166", "0.5102921", "0.5102047", "0.5095436", "0.5084666", "0.5081923", "0.5080624", "0.5072222", "0.50719994", "0.50650585", "0.5062041" ]
0.74027896
1
CreateFileSystemWithChan invokes the dfs.CreateFileSystem API asynchronously
CreateFileSystemWithChan вызывает асинхронно API dfs.CreateFileSystem
func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) { responseChan := make(chan *CreateFileSystemResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.CreateFileSystem(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (client *Client) ListFileSystemsWithChan(request *ListFileSystemsRequest) (<-chan *ListFileSystemsResponse, <-chan error) {\n\tresponseChan := make(chan *ListFileSystemsResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ListFileSystems(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (client *Client) CreateFileDetectWithChan(request *CreateFileDetectRequest) (<-chan *CreateFileDetectResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileDetectResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileDetect(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func MakeFsOnDisk() FileSystem { return filesys.MakeFsOnDisk() }", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func NewFileSystemClient() (FileSystemClient, error) {\n\taddress := os.Getenv(constants.EnvFileSystemAddress)\n\tif address == \"\" {\n\t\treturn nil, fmt.Errorf(\"Environment variable '%s' not set\", constants.EnvFileSystemAddress)\n\t}\n\n\t// Create a connection\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a client\n\tc := fs.NewFileSystemClient(conn)\n\n\treturn &fileSystemClient{c: c, conn: conn}, nil\n}", "func (storage *B2Storage) CreateDirectory(threadIndex int, dir string) (err error) {\n return nil\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (client *Client) CreateFileDetectWithCallback(request *CreateFileDetectRequest, callback func(response *CreateFileDetectResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileDetectResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileDetect(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) ListFileSystemsWithCallback(request *ListFileSystemsRequest, callback func(response *ListFileSystemsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ListFileSystemsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ListFileSystems(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func (fsys *gcsFS) Create(name string) (WriterFile, error) {\n\tf, err := fsys.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*GCSFile), nil\n}", "func (client *Client) CreateGatewayFileShareWithChan(request *CreateGatewayFileShareRequest) (<-chan *CreateGatewayFileShareResponse, <-chan error) {\n\tresponseChan := make(chan *CreateGatewayFileShareResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateGatewayFileShare(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func execNewChan(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.NewChan(types.ChanDir(args[0].(int)), args[1].(types.Type))\n\tp.Ret(2, ret)\n}", "func (fs osFS) Create(path string) (io.WriteCloser, error) {\n\tf, err := os.Create(fs.resolve(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Open: %s is a directory\", path)\n\t}\n\n\treturn f, nil\n}", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func (d *Definition) Create() error {\n\terrChan := make(chan error)\n\ttree := d.ResourceTree\n\n\t// Check definition context exists\n\tif _, err := os.Stat(tree.Root().ID()); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t`Definition Create: Expected context: \"%s\" to exist.`,\n\t\t\ttree.Root().Name(),\n\t\t)\n\t}\n\n\tgo func() {\n\t\tdefer close(errChan)\n\t\ttree.Traverse(func(r Resource) {\n\t\t\terrChan <- r.Create(d.Options)\n\t\t})\n\t}()\n\n\tfor err := range errChan {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Definition Create: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func (self *File_Client) CreateDir(path interface{}, name interface{}) error {\n\n\trqst := &filepb.CreateDirRequest{\n\t\tPath: Utility.ToString(path),\n\t\tName: Utility.ToString(name),\n\t}\n\n\t_, err := self.c.CreateDir(context.Background(), rqst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *Client) ListAvailableFileSystemTypesWithChan(request *ListAvailableFileSystemTypesRequest) (<-chan *ListAvailableFileSystemTypesResponse, <-chan error) {\n\tresponseChan := make(chan *ListAvailableFileSystemTypesResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ListAvailableFileSystemTypes(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func CreateFiles(fS *FileCollection, ts int64, filelock chan int64) {\n\tvar lt time.Time\n\tvar err error\n\n\tselect {\n\tcase <- time.After(5 * time.Second):\n\t\t//If 5 seconds pass without getting the proper lock, abort\n\t\tlog.Printf(\"partdisk.CreateFiles(): timeout waiting for lock\\n\")\n\t\treturn\n\tcase chts := <- filelock:\n\t\tif chts == ts { //Got the lock and it matches the timestamp received\n\t\t\t//Proceed\n\t\t\tfS.flid = ts\n\t\t\tdefer func(){\n\t\t\t\tfilelock <- 0 //Release lock\n\t\t\t}()\n\t\t\tlt = time.Now() //Start counting how long does the parts creation take\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, timestamps match: %d\\n\",ts)\n\t\t} else {\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, but timestamps missmatch: %d - %d\\n\", ts,chts)\n\t\t\tfilelock <- chts\n\t\t\treturn\n\t\t}\n\t}\n\t//Lock obtained proper, create/delete the files\n\terr = adrefiles(fS)\n\tif err != nil {\n\t\tlog.Printf(\"CreateFiles(): Error creating file: %s\\n\",err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"CreateFiles(): Request %d completed in %d seconds\\n\",ts,int64(time.Since(lt).Seconds()))\n}", "func (fb *FileBase) Create(ID string) (io.WriteCloser, error) {\n\treturn fb.fs.Create(filepath.Join(fb.root, ID))\n}", "func (linux *Linux) FileCreate(filePath string) error {\n\tif !linux.FileExists(filePath) {\n\t\tfile, err := os.Create(linux.applyChroot(filePath))\n\t\tdefer file.Close()\n\t\treturn err\n\t}\n\treturn os.ErrExist\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func NewFS(basedir string) (kvs *FS, err error) {\n\treturn newFileSystem(basedir, os.MkdirAll)\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func init() {\n\tioops.CreateDirectory(Root)\n\tchPic = make(chan string, 1)\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (cs *ControllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {\n\tname := req.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume name must be provided\")\n\t}\n\tif err := cs.validateVolumeCapabilities(req.GetVolumeCapabilities()); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\treqCapacity := req.GetCapacityRange().GetRequiredBytes()\n\tnfsVol, err := cs.newNFSVolume(name, reqCapacity, req.GetParameters())\n\tif err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tvar volCap *csi.VolumeCapability\n\tif len(req.GetVolumeCapabilities()) > 0 {\n\t\tvolCap = req.GetVolumeCapabilities()[0]\n\t} // 执行挂载 命令\n\t// Mount nfs base share so we can create a subdirectory\n\tif err = cs.internalMount(ctx, nfsVol, volCap); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to mount nfs server: %v\", err.Error())\n\t}\n\tdefer func() {\n\t\tif err = cs.internalUnmount(ctx, nfsVol); err != nil {\n\t\t\tklog.Warningf(\"failed to unmount nfs server: %v\", err.Error())\n\t\t}\n\t}()\n\n\t// Create subdirectory under base-dir\n\t// TODO: revisit permissions\n\tinternalVolumePath := cs.getInternalVolumePath(nfsVol)\n\tif err = os.Mkdir(internalVolumePath, 0777); err != nil && !os.IsExist(err) {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to make subdirectory: %v\", err.Error())\n\t}\n\t// Remove capacity setting when provisioner 1.4.0 is available with fix for\n\t// https://github.com/kubernetes-csi/external-provisioner/pull/271\n\treturn &csi.CreateVolumeResponse{Volume: cs.nfsVolToCSI(nfsVol, reqCapacity)}, nil\n}", "func (c *Client) Create(path gfs.Path) error {\n\tvar reply gfs.CreateFileReply\n\terr := util.Call(c.master, \"Master.RPCCreateFile\", gfs.CreateFileArg{path}, &reply)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (fs *VolatileFileSystem) CreateFile(name string, data []byte) error {\n\tvar flags C.int = C.SQLITE_OPEN_EXCLUSIVE | C.SQLITE_OPEN_CREATE\n\n\tiFd, rc := fs.vfs.Open(name, flags)\n\tif rc != C.SQLITE_OK {\n\t\treturn Error{\n\t\t\tCode: ErrIoErr,\n\t\t\tExtendedCode: ErrNoExtended(rc),\n\t\t}\n\t}\n\n\tfile, _ := fs.vfs.FileByFD(iFd)\n\tfile.mu.Lock()\n\tfile.data = data\n\tfile.mu.Unlock()\n\n\treturn nil\n}", "func (client *Client) CreateGatewayFileShareWithCallback(request *CreateGatewayFileShareRequest, callback func(response *CreateGatewayFileShareResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateGatewayFileShareResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateGatewayFileShare(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func Create(instructionData reflect.Value, finished chan bool) int {\n\tfmt.Println(\"FIBER INFO: Creating File ...\")\n\n\tpath, err := variable.GetValue(instructionData, \"PathVarName\", \"PathIsVar\", \"Path\")\n\tif err != nil {\n\t\tfinished <- true\n\t\treturn -1\n\t}\n\n\tf, _ := os.Create(path.(string))\n\tf.Close()\n\tfinished <- true\n\treturn -1\n}", "func Create(p []string) (Task, error) {\n\tt := Task{\n\t\tPaths: p,\n\t}\n\tw, err := fsnotify.NewWatcher()\n\tt.FSWatcher = w\n\treturn t, err\n}", "func (z *zfsctl) ReceiveFileSystem(ctx context.Context, name, options string, properties map[string]string, xProperty string, de string) *execute {\n\targs := []string{\"receive\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, strings.TrimSuffix(kv, \" \"))\n\t}\n\tif len(xProperty) > 0 {\n\t\targs = append(args, \"-x \"+xProperty)\n\t}\n\tswitch de {\n\tcase \"-d\":\n\t\targs = append(args, \"-d\")\n\tcase \"-e\":\n\t\targs = append(args, \"-e\")\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func (daemon *Daemon) openContainerFS(container *container.Container) (_ *containerFSView, err error) {\n\tif err := daemon.Mount(container); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = daemon.Unmount(container)\n\t\t}\n\t}()\n\n\tmounts, err := daemon.setupMounts(container)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = container.UnmountVolumes(daemon.LogVolumeEvent)\n\t\t}\n\t}()\n\n\t// Setup in initial mount namespace complete. We're ready to unshare the\n\t// mount namespace and bind the volume mounts into that private view of\n\t// the container FS.\n\ttodo := make(chan future)\n\tdone := make(chan error)\n\terr = unshare.Go(unix.CLONE_NEWNS,\n\t\tfunc() error {\n\t\t\tif err := mount.MakeRSlave(\"/\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, m := range mounts {\n\t\t\t\tdest, err := container.GetResourcePath(m.Destination)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tvar stat os.FileInfo\n\t\t\t\tstat, err = os.Stat(m.Source)\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 := fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tbindMode := \"rbind\"\n\t\t\t\tif m.NonRecursive {\n\t\t\t\t\tbindMode = \"bind\"\n\t\t\t\t}\n\t\t\t\twriteMode := \"ro\"\n\t\t\t\tif m.Writable {\n\t\t\t\t\twriteMode = \"rw\"\n\t\t\t\t\tif m.ReadOnlyNonRecursive {\n\t\t\t\t\t\treturn errors.New(\"options conflict: Writable && ReadOnlyNonRecursive\")\n\t\t\t\t\t}\n\t\t\t\t\tif m.ReadOnlyForceRecursive {\n\t\t\t\t\t\treturn errors.New(\"options conflict: Writable && ReadOnlyForceRecursive\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif m.ReadOnlyNonRecursive && m.ReadOnlyForceRecursive {\n\t\t\t\t\treturn errors.New(\"options conflict: ReadOnlyNonRecursive && ReadOnlyForceRecursive\")\n\t\t\t\t}\n\n\t\t\t\t// openContainerFS() is called for temporary mounts\n\t\t\t\t// outside the container. Soon these will be unmounted\n\t\t\t\t// with lazy unmount option and given we have mounted\n\t\t\t\t// them rbind, all the submounts will propagate if these\n\t\t\t\t// are shared. If daemon is running in host namespace\n\t\t\t\t// and has / as shared then these unmounts will\n\t\t\t\t// propagate and unmount original mount as well. So make\n\t\t\t\t// all these mounts rprivate. Do not use propagation\n\t\t\t\t// property of volume as that should apply only when\n\t\t\t\t// mounting happens inside the container.\n\t\t\t\topts := strings.Join([]string{bindMode, writeMode, \"rprivate\"}, \",\")\n\t\t\t\tif err := mount.Mount(m.Source, dest, \"\", opts); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif !m.Writable && !m.ReadOnlyNonRecursive {\n\t\t\t\t\tif err := makeMountRRO(dest); err != nil {\n\t\t\t\t\t\tif m.ReadOnlyForceRecursive {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.G(context.TODO()).WithError(err).Debugf(\"Failed to make %q recursively read-only\", dest)\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\treturn mounttree.SwitchRoot(container.BaseFS)\n\t\t},\n\t\tfunc() {\n\t\t\tdefer close(done)\n\n\t\t\tfor it := range todo {\n\t\t\t\terr := it.fn()\n\t\t\t\tif it.res != nil {\n\t\t\t\t\tit.res <- err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// The thread will terminate when this goroutine returns, taking the\n\t\t\t// mount namespace and all the volume bind-mounts with it.\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvw := &containerFSView{\n\t\td: daemon,\n\t\tctr: container,\n\t\ttodo: todo,\n\t\tdone: done,\n\t}\n\truntime.SetFinalizer(vw, (*containerFSView).Close)\n\treturn vw, nil\n}", "func mkChannel(path string) (chan uint8, <-chan vm.Msg, error) {\n\tfd, err := os.OpenFile(path, unix.O_RDWR, 0600|os.ModeExclusive)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"OpenFile %s\", path)\n\t}\n\n\tackChan := make(chan uint8)\n\tmsgChan := make(chan vm.Msg, 1)\n\n\tgo func() {\n\t\tfor {\n\t\t\tvalue := <-ackChan\n\t\t\tif _, err := fd.Write([]byte{value}); err != nil {\n\t\t\t\tlog.Printf(\"Write: %v\", err)\n\t\t\t}\n\t\t\tackChan <- 0\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\t// read header\n\t\t\tbuf := make([]byte, headerSize)\n\t\t\tif _, err := io.ReadFull(fd, buf); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\n\t\t\tpayloadSize := int(binary.BigEndian.Uint32(buf[:4]))\n\t\t\tmsgType := vm.Msgtype(buf[4])\n\n\t\t\t// read payload\n\t\t\tbuf = make([]byte, payloadSize)\n\t\t\trd := bufio.NewReaderSize(fd, payloadSize)\n\t\t\tif _, err := io.ReadFull(rd, buf); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\n\t\t\tmsgChan <- vm.Msg{\n\t\t\t\tType: msgType,\n\t\t\t\tData: buf,\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ackChan, msgChan, nil\n}", "func newFile(fd uintptr, name string, kind newFileKind) *File {\n\tfdi := int(fd)\n\tif fdi < 0 {\n\t\treturn nil\n\t}\n\tf := &File{&file{\n\t\tpfd: poll.FD{\n\t\t\tSysfd: fdi,\n\t\t\tIsStream: true,\n\t\t\tZeroReadIsEOF: true,\n\t\t},\n\t\tname: name,\n\t\tstdoutOrErr: fdi == 1 || fdi == 2,\n\t}}\n\n\tpollable := kind == kindOpenFile || kind == kindPipe || kind == kindNonBlock\n\n\t// If the caller passed a non-blocking filedes (kindNonBlock),\n\t// we assume they know what they are doing so we allow it to be\n\t// used with kqueue.\n\tif kind == kindOpenFile {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\", \"ios\", \"dragonfly\", \"freebsd\", \"netbsd\", \"openbsd\":\n\t\t\tvar st syscall.Stat_t\n\t\t\terr := ignoringEINTR(func() error {\n\t\t\t\treturn syscall.Fstat(fdi, &st)\n\t\t\t})\n\t\t\ttyp := st.Mode & syscall.S_IFMT\n\t\t\t// Don't try to use kqueue with regular files on *BSDs.\n\t\t\t// On FreeBSD a regular file is always\n\t\t\t// reported as ready for writing.\n\t\t\t// On Dragonfly, NetBSD and OpenBSD the fd is signaled\n\t\t\t// only once as ready (both read and write).\n\t\t\t// Issue 19093.\n\t\t\t// Also don't add directories to the netpoller.\n\t\t\tif err == nil && (typ == syscall.S_IFREG || typ == syscall.S_IFDIR) {\n\t\t\t\tpollable = false\n\t\t\t}\n\n\t\t\t// In addition to the behavior described above for regular files,\n\t\t\t// on Darwin, kqueue does not work properly with fifos:\n\t\t\t// closing the last writer does not cause a kqueue event\n\t\t\t// for any readers. See issue #24164.\n\t\t\tif (runtime.GOOS == \"darwin\" || runtime.GOOS == \"ios\") && typ == syscall.S_IFIFO {\n\t\t\t\tpollable = false\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := f.pfd.Init(\"file\", pollable); err != nil {\n\t\t// An error here indicates a failure to register\n\t\t// with the netpoll system. That can happen for\n\t\t// a file descriptor that is not supported by\n\t\t// epoll/kqueue; for example, disk files on\n\t\t// Linux systems. We assume that any real error\n\t\t// will show up in later I/O.\n\t} else if pollable {\n\t\t// We successfully registered with netpoll, so put\n\t\t// the file into nonblocking mode.\n\t\tif err := syscall.SetNonblock(fdi, true); err == nil {\n\t\t\tf.nonblock = true\n\t\t}\n\t}\n\n\truntime.SetFinalizer(f.file, (*file).close)\n\treturn f\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\t// fmt.Printf(\"creating file in dir with inode %d\\n\", d.inodeNum)\n\t// fmt.Println(\"name of file to be created is: \" + req.Name)\n\tdirTable, err := getTable(d.inode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileExists := dirTable.Table[req.Name] != 0\n\tvar inode *Inode\n\tvar inodeNum uint64\n\tif !fileExists {\n\t\t// fmt.Println(\"file does not yet exist in Create\")\n\t\tvar isDir int8 = 0\n\t\tinode = createInode(isDir)\n\t\tinodeNum = d.inodeStream.next()\n\t\tinode.init(d.inodeNum, inodeNum)\n\t\td.addFile(req.Name, inodeNum)\n\t} else {\n\t\t// fmt.Println(\"file already exists in Create\")\n\t\tinodeNum = dirTable.Table[req.Name]\n\t\tinode, err = getInode(inodeNum)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tchild := &File{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t\tinodeStream: d.inodeStream,\n\t}\n\thandle := &FileHandle{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t}\n\t// can any errors happen here?\n\treturn child, handle, nil\n}", "func CrawlFileSystem(workQueue chan *Data, root string, wg *sync.WaitGroup, verbose bool) {\n\tdefer wg.Done()\n\tID := int64(0)\n\t\n\t// Start timing\n\tstart := time.Now()\n\t\n\t// Walk file system\n\terr := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {\n\t\tworkQueue <- &Data{path, ID}\n\t\tID++\n\t\treturn err\n\t})\n\n\tif err != nil && verbose {\n\t\tlog.Printf(\"crawl error: %s\", err)\n\t}\n\n\tlog.Printf(\"Finished crawling %s in %s\", root, time.Since(start))\n\tclose(workQueue)\n}", "func mkdirForFile(path string) error {\n\treturn os.MkdirAll(filepath.Dir(path), DefaultDirectoryPermissions)\n}", "func NewFileSystem() FileSystem {\n\treturn &fs{\n\t\trunner: NewCommandRunner(),\n\t}\n}", "func (fsi *fsIOPool) Create(path string) (wlk *lock.LockedFile, err error) {\n\tif err = checkPathLength(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates parent if missing.\n\tif err = mkdirAll(pathutil.Dir(path), 0777); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attempt to create the file.\n\twlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsPermission(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tcase isSysErrIsDir(err):\n\t\t\treturn nil, errIsNotRegular\n\t\tcase isSysErrPathNotFound(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Success.\n\treturn wlk, nil\n}", "func Factory(token string, channelID string) (func(string) error, error) {\n\ts, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Before using the message endpoint, you must connect to\n\t// and identify with a gateway at least once.\n\terr = s.Open()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = s.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcb := func(src string) error {\n\t\tf, err := os.Open(src)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\n\t\t_, err = s.ChannelFileSend(channelID, filepath.Base(src), f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn cb, nil\n}", "func getFileSystem(frame *rtda.Frame) {\n\tthread := frame.Thread\n\tunixFsClass := frame.GetClassLoader().LoadClass(\"java/io/UnixFileSystem\")\n\tif unixFsClass.InitializationNotStarted() {\n\t\tframe.NextPC = thread.PC // undo getFileSystem\n\t\tthread.InitClass(unixFsClass)\n\t\treturn\n\t}\n\n\tunixFsObj := unixFsClass.NewObj()\n\tframe.PushRef(unixFsObj)\n\n\t// call <init>\n\tframe.PushRef(unixFsObj) // this\n\tconstructor := unixFsClass.GetDefaultConstructor()\n\tthread.InvokeMethod(constructor)\n}", "func createPaths() {\n\tdataDir, err := conf.GetDataLoc()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdirs := []string{\"uploads\", \"sources\", \"sinks\", \"functions\", \"services\", \"services/schemas\", \"connections\"}\n\n\tfor _, v := range dirs {\n\t\t// Create dir if not exist\n\t\trealDir := filepath.Join(dataDir, v)\n\t\tif _, err := os.Stat(realDir); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(realDir, os.ModePerm); err != nil {\n\t\t\t\tfmt.Printf(\"Failed to create dir %s: %v\", realDir, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfiles := []string{\"connections/connection.yaml\"}\n\tfor _, v := range files {\n\t\t// Create dir if not exist\n\t\trealFile := filepath.Join(dataDir, v)\n\t\tif _, err := os.Stat(realFile); os.IsNotExist(err) {\n\t\t\tif _, err := os.Create(realFile); err != nil {\n\t\t\t\tfmt.Printf(\"Failed to create file %s: %v\", realFile, err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func Create(name string) (*os.File, error)", "func createDir(path string, host string) error {\n\tsshCmd := fmt.Sprintf(\"mkdir -p %s\", path)\n\tframework.Logf(\"Invoking command '%v' on ESX host %v\", sshCmd, host)\n\tresult, err := fssh.SSH(sshCmd, host+\":22\", framework.TestContext.Provider)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: '%s' on ESX host: %v\", sshCmd, err)\n\t}\n\treturn nil\n}", "func (s Storage) Create(path string) (io.ReadWriteCloser, error) {\n\tloc, err := s.fullPath(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir, _ := filepath.Split(loc)\n\t_, err = os.Stat(dir)\n\n\tif err != nil && os.IsNotExist(err) {\n\t\terr = os.MkdirAll(dir, 0766)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.OpenFile(loc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0766)\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func newFSConn(token, infoPath string) (conn *FSConn, err error) {\n\tvar info slack.Info\n\tconn = new(FSConn)\n\n\tif infoPath != \"\" {\n\t\tbuf, err := ioutil.ReadFile(infoPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadFile(%s): %s\", infoPath, err)\n\t\t}\n\t\terr = json.Unmarshal(buf, &info)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unmarshal: %s\", err)\n\t\t}\n\t} else {\n\t\tconn.api = slack.New(token)\n\t\t//conn.api.SetDebug(true)\n\t\tconn.ws, err = conn.api.StartRTM(\"\", \"https://slack.com\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"StartRTM(): %s\\n\", err)\n\t\t}\n\t\tinfo = conn.api.GetInfo()\n\t}\n\n\tconn.in = make(chan slack.SlackEvent)\n\tconn.sinks = make([]EventHandler, 0, 5)\n\tconn.Super = NewSuper()\n\n\tusers := make([]*User, 0, len(info.Users))\n\tfor _, u := range info.Users {\n\t\tusers = append(users, NewUser(u, conn))\n\t}\n\tconn.users, err = NewUserSet(\"users\", conn, NewUserDir, users)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewUserSet: %s\", err)\n\t}\n\n\tconn.self, err = NewSelf(conn, info.User, info.Team)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewSelf: %s\", err)\n\t}\n\n\tchans := make([]Room, 0, len(info.Channels))\n\tfor _, c := range info.Channels {\n\t\tchans = append(chans, NewChannel(c, conn))\n\t}\n\tconn.channels, err = NewRoomSet(\"channels\", conn, NewChannelDir, chans)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\tgroups := make([]Room, 0, len(info.Groups))\n\tfor _, g := range info.Groups {\n\t\tgroups = append(groups, NewGroup(g, conn))\n\t}\n\tconn.groups, err = NewRoomSet(\"groups\", conn, NewGroupDir, groups)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\tims := make([]Room, 0, len(info.IMs))\n\tfor _, im := range info.IMs {\n\t\tims = append(ims, NewIM(im, conn))\n\t}\n\tconn.ims, err = NewRoomSet(\"ims\", conn, NewIMDir, ims)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\t// simplify dispatch code by keeping track of event handlers\n\t// in a slice. We (FSConn) are an event sink too - add\n\t// ourselves to the list first, so that we can separate\n\t// routing logic from connection-level handling logic.\n\tconn.sinks = append(conn.sinks, conn,\n\t\tconn.users, conn.channels, conn.groups, conn.ims)\n\n\t// only spawn goroutines in online mode\n\tif infoPath == \"\" {\n\t\tgo conn.ws.HandleIncomingEvents(conn.in)\n\t\tgo conn.ws.Keepalive(10 * time.Second)\n\t\tgo conn.consumeEvents()\n\t}\n\n\treturn conn, nil\n}", "func (client *Client) CreateClusterWithChan(request *CreateClusterRequest) (<-chan *CreateClusterResponse, <-chan error) {\n\tresponseChan := make(chan *CreateClusterResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateCluster(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func createFormatFS(fsPath string) error {\n\tfsFormatPath := pathJoin(fsPath, minioMetaBucket, formatConfigFile)\n\n\t// Attempt a write lock on formatConfigFile `format.json`\n\t// file stored in minioMetaBucket(.minio.sys) directory.\n\tlk, err := lock.TryLockedOpenFile((fsFormatPath), os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn traceError(err)\n\t}\n\t// Close the locked file upon return.\n\tdefer lk.Close()\n\n\t// Load format on disk, checks if we are unformatted\n\t// writes the new format.json\n\tvar format = &formatConfigV1{}\n\terr = format.LoadFormat(lk)\n\tif errorCause(err) == errUnformattedDisk {\n\t\t_, err = newFSFormat().WriteTo(lk)\n\t\treturn err\n\t}\n\treturn err\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateFilesystem(path string) error {\n\treturn nil\n}", "func createNode(parent string, infos []FileInfo) error {\n\tfor _, info := range infos {\n\t\tpath := filepath.Join(parent, info.Name)\n\t\tif info.Type == DirType { // info is a dir\n\t\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\t\tos.Mkdir(path, 0755)\n\t\t\t}\n\t\t\tif info.Children != nil && len(info.Children) > 0 {\n\t\t\t\tif err := createNode(path, info.Children); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else if info.Type == FileType { // info is a file\n\t\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\t\tif err := ioutil.WriteFile(path, []byte(info.Content), 0755); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unknown FileInfo type: %v\", info.Type)\n\t\t}\n\t}\n\treturn nil\n}", "func (fs *EmbedFs) Create(path string) (file, error) {\n\treturn nil, ErrNotAvail\n}", "func CreateRecursive(ctx context.Context, conn *ZkConn, zkPath string, value []byte, flags int32, aclv []zk.ACL, maxCreationDepth int) (string, error) {\n\tpathCreated, err := conn.Create(ctx, zkPath, value, flags, aclv)\n\tif err == zk.ErrNoNode {\n\t\tif maxCreationDepth == 0 {\n\t\t\treturn \"\", zk.ErrNoNode\n\t\t}\n\n\t\t// Make sure that nodes are either \"file\" or\n\t\t// \"directory\" to mirror file system semantics.\n\t\tdirAclv := make([]zk.ACL, len(aclv))\n\t\tfor i, acl := range aclv {\n\t\t\tdirAclv[i] = acl\n\t\t\tdirAclv[i].Perms = PermDirectory\n\t\t}\n\t\tparentPath := path.Dir(zkPath)\n\t\t_, err = CreateRecursive(ctx, conn, parentPath, nil, 0, dirAclv, maxCreationDepth-1)\n\t\tif err != nil && err != zk.ErrNodeExists {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpathCreated, err = conn.Create(ctx, zkPath, value, flags, aclv)\n\t}\n\treturn pathCreated, err\n}", "func (m *FileSystem) Create(file string) (io.Writer, error) {\n\tret := m.ctrl.Call(m, \"Create\", file)\n\tret0, _ := ret[0].(io.Writer)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (fs osFsEval) Create(path string) (*os.File, error) {\n\treturn os.Create(path)\n}", "func createRepo(c *config, repo string, ch chan<- bool) error {\n\t// create context\n\tctxt, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tcdp, err := chromedp.New(ctxt, chromedp.WithLog(log.Printf))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// run task list\n\terr = cdp.Run(ctxt, gitHub(c, repo))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// shutdown chrome\n\terr = cdp.Shutdown(ctxt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// wait for chrome to finish\n\terr = cdp.Wait()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tch <- true\n\treturn nil\n}", "func NewCfnFileSystem(scope awscdk.Construct, id *string, props *CfnFileSystemProps) CfnFileSystem {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnFileSystem{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_fsx.CfnFileSystem\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func createFile( filename string) {\n f, err := os.Create(filename)\n u.ErrNil(err, \"Unable to create file\")\n defer f.Close()\n log.Printf(\"Created %s\\n\", f.Name())\n}", "func ServeFuseFS(\n\tfilesys *plugin.Registry,\n\tmountpoint string,\n\tanalyticsClient analytics.Client,\n) (chan<- context.Context, <-chan struct{}, error) {\n\tfuse.Debug = func(msg interface{}) {\n\t\tlog.Tracef(\"FUSE: %v\", msg)\n\t}\n\n\tlog.Infof(\"FUSE: Mounting at %v\", mountpoint)\n\tfuseConn, err := fuse.Mount(mountpoint)\n\tif err != nil {\n\t\treturn nil, nil, mountFailedErr(err)\n\t}\n\n\t// Start the FUSE server. We use the serverExitedCh to catch externally triggered unmounts.\n\t// If we're explicitly asked to shutdown the server, we want to wait until both Unmount and\n\t// Serve have exited before signaling completion.\n\tserverExitedCh := make(chan struct{})\n\tgo func() {\n\t\tserverConfig := &fs.Config{\n\t\t\tWithContext: func(ctx context.Context, req fuse.Request) context.Context {\n\t\t\t\tpid := int(req.Hdr().Pid)\n\t\t\t\tnewctx := context.WithValue(ctx, activity.JournalKey, activity.JournalForPID(pid))\n\t\t\t\tnewctx = context.WithValue(newctx, analytics.ClientKey, analyticsClient)\n\t\t\t\treturn newctx\n\t\t\t},\n\t\t}\n\t\tserver := fs.New(fuseConn, serverConfig)\n\t\troot := newRoot(filesys)\n\t\tif err := server.Serve(&root); err != nil {\n\t\t\tlog.Warnf(\"FUSE: fs.Serve errored with: %v\", err)\n\t\t}\n\n\t\t// check if the mount process has an error to report\n\t\t<-fuseConn.Ready\n\t\tif err := fuseConn.MountError; err != nil {\n\t\t\tlog.Warnf(\"FUSE: Mount process errored with: %v\", err)\n\t\t}\n\t\tlog.Infof(\"FUSE: Serve complete\")\n\n\t\t// Signal that Serve exited so the clean-up goroutine can close the stopped channel\n\t\t// if it hasn't already done so.\n\t\tdefer close(serverExitedCh)\n\t}()\n\n\t// Clean-up\n\tstopCh := make(chan context.Context)\n\tstoppedCh := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\t// Handle explicit shutdown\n\t\t\tlog.Infof(\"FUSE: Shutting down the server\")\n\n\t\t\tlog.Infof(\"FUSE: Unmounting %v\", mountpoint)\n\t\t\tif err = fuse.Unmount(mountpoint); err != nil {\n\t\t\t\tlog.Warnf(\"FUSE: Shutdown failed: %v\", err)\n\t\t\t\tlog.Warnf(\"FUSE: Manual cleanup required: umount %v\", mountpoint)\n\n\t\t\t\t// Retry in a loop until no longer blocked buy an open handle.\n\t\t\t\t// All errors are `*os.PathError`, so we just match a known error string.\n\t\t\t\t// Note that casing of the error message differs on macOS and Linux.\n\t\t\t\tfor ; err != nil && strings.HasSuffix(strings.ToLower(err.Error()), \"resource busy\"); err = fuse.Unmount(mountpoint) {\n\t\t\t\t\tlog.Debugf(\"FUSE: Unmount failed: %v\", err)\n\t\t\t\t\ttime.Sleep(3 * time.Second)\n\t\t\t\t}\n\t\t\t\tlog.Debugf(\"FUSE: Unmount: %v\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"FUSE: Unmount complete\")\n\t\tcase <-serverExitedCh:\n\t\t\t// Server exited on its own, fallthrough.\n\t\t}\n\t\t// Check that Serve has exited successfully in case we initiated the Unmount.\n\t\t<-serverExitedCh\n\t\terr := fuseConn.Close()\n\t\tif err != nil {\n\t\t\tlog.Infof(\"FUSE: Error closing the connection: %v\", err)\n\t\t}\n\t\tlog.Infof(\"FUSE: Server shutdown complete\")\n\t\tclose(stoppedCh)\n\t}()\n\n\treturn stopCh, stoppedCh, nil\n}", "func createFile(filePath string) error {\n\tfile, err := os.OpenFile(filePath, os.O_RDONLY|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn file.Close()\n}", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func createTransfer(path, name string, friendNumber uint32, file *os.File, size uint64, callback func(status State)) *transfer {\n\treturn &transfer{\n\t\tpath: path,\n\t\tname: name,\n\t\tfriend: friendNumber,\n\t\tfile: file,\n\t\tsize: size,\n\t\tprogress: 0,\n\t\tdoneCallback: callback,\n\t\tisDone: false}\n}", "func createDirectories() error {\n\n\tvar brickPath = glusterBrickPath + \"/\" + glusterVolumeName\n\tvar mountPath = glusterMountPath + \"/\" + glusterVolumeName\n\tvar volumePath = glusterDockerVolumePath\n\n\tdirPath := []string{brickPath, mountPath, volumePath}\n\n\tfor i := 0; i < len(dirPath); i++ {\n\t\tif helpers.Exists(dirPath[i]) == false {\n\t\t\terr := helpers.CreateDir(dirPath[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (f *Fs) mkdir(ctx context.Context, dirPath string) (err error) {\n\t// defer log.Trace(dirPath, \"\")(\"err=%v\", &err)\n\terr = f._mkdir(ctx, dirPath)\n\tif apiErr, ok := err.(*api.Error); ok {\n\t\t// parent does not exist so create it first then try again\n\t\tif apiErr.StatusCode == http.StatusConflict {\n\t\t\terr = f.mkParentDir(ctx, dirPath)\n\t\t\tif err == nil {\n\t\t\t\terr = f._mkdir(ctx, dirPath)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func BuildFs(fs Filesystem, basepath string, opts *BuildOpts) (ops chan OpData, prog chan string) {\n\n\tops = make(chan OpData)\n\tprog = make(chan string)\n\n\tgo build(fs, basepath, ops, prog, opts)\n\n\treturn\n}", "func (client *Client) CreateVSwitchWithChan(request *CreateVSwitchRequest) (<-chan *CreateVSwitchResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVSwitchResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVSwitch(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func createDirectoryOrCancelTask(path string, tid int64,\n\tcancel chan bool) bool {\n\tvar ack bool\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\tconn.Call(\"WorkerAPI.PublishTaskResult\", remote_worker.Result{\n\t\t\t\tTid: tid,\n\t\t\t\tStdout: \"\",\n\t\t\t\tStderr: \"Cannot create cache directory!\",\n\t\t\t\tExit_status: -1,\n\t\t\t}, &ack)\n\t\t\t<-cancel\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c *fileSystemClient) CreateFileURI(ctx context.Context, in *fs.CreateFileURIRequest, opts ...grpc.CallOption) (*fs.CreateFileURIResponse, error) {\n\treturn c.c.CreateFileURI(ctx, in, opts...)\n}", "func (b *Broker) createFolders() (err error) {\n\t_oldUMask := syscall.Umask(0)\n\n\tvar _folderRight os.FileMode\n\t_folderRight = 0755 // for writes... (so creation of file need 'X', hence owner should be RWX = 7, others... usually for R+X = 5)\n\n\t// [Path] Data\n\tlog.Tracef(\"[createFolders] *** data: %v log: %v\", b.Path.Data, b.Path.Log)\n\t_exists, _ := util.IsFileExists(b.Path.Data)\n\tif !_exists {\n\t\terr = os.MkdirAll(b.Path.Data, _folderRight)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// [Path] Log\n\t_exists, _ = util.IsFileExists(b.Path.Log)\n\tif !_exists {\n\t\terr = os.MkdirAll(b.Path.Log, _folderRight)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// TODO: update folder creation if more configs were added\n\tsyscall.Umask(_oldUMask)\n\n\treturn\n}", "func (client StorageGatewayClient) connectFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems/{fileSystemName}/actions/connect\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ConnectFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func NewFileSystem() FileSystem {\r\n\treturn &osFileSystem{}\r\n}", "func (s *storager) Create(ctx context.Context, location string, mode os.FileMode, reader io.Reader, isDir bool, options ...storage.Option) error {\n\troot := s.Root\n\tif isDir {\n\t\t_, err := root.Folder(location, mode)\n\t\treturn err\n\t}\n\treturn s.Upload(ctx, location, mode, reader)\n}" ]
[ "0.7438406", "0.59352165", "0.58698547", "0.58682775", "0.5800312", "0.5783298", "0.5782387", "0.5774499", "0.56610906", "0.56329244", "0.5362752", "0.53274715", "0.52781004", "0.52586395", "0.52302724", "0.5204847", "0.517791", "0.5176203", "0.5168632", "0.50918365", "0.5090746", "0.50887173", "0.5078688", "0.5070004", "0.5014069", "0.4998363", "0.4966987", "0.4965756", "0.49635392", "0.49505255", "0.49483892", "0.49271625", "0.49203116", "0.49142587", "0.49135125", "0.4898408", "0.4898084", "0.4873829", "0.4859631", "0.48377973", "0.48311728", "0.48270527", "0.48255876", "0.48138842", "0.4810215", "0.48006475", "0.4772576", "0.47668034", "0.47651732", "0.47540152", "0.47516978", "0.47491857", "0.47448534", "0.47374976", "0.4735826", "0.47166464", "0.47125658", "0.47108907", "0.4697916", "0.46862173", "0.46815112", "0.46746534", "0.46739498", "0.4664394", "0.46534875", "0.46508607", "0.46426266", "0.46417794", "0.46410203", "0.46394387", "0.46349168", "0.4629937", "0.46276748", "0.4612222", "0.46106598", "0.4597719", "0.4596728", "0.45904416", "0.45886105", "0.4586888", "0.45717865", "0.45525908", "0.45525286", "0.45525286", "0.45525286", "0.45519158", "0.45517004", "0.45457235", "0.4541163", "0.45408356", "0.45401004", "0.45312417", "0.45234653", "0.45216343", "0.45184454", "0.45148808", "0.45132414", "0.45107666", "0.4509462", "0.45084605" ]
0.80296123
0
CreateFileSystemWithCallback invokes the dfs.CreateFileSystem API asynchronously
CreateFileSystemWithCallback вызывает асинхронно API dfs.CreateFileSystem
func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *CreateFileSystemResponse var err error defer close(result) response, err = client.CreateFileSystem(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func (client *Client) ListFileSystemsWithCallback(request *ListFileSystemsRequest, callback func(response *ListFileSystemsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ListFileSystemsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ListFileSystems(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (client *Client) CreateFileDetectWithCallback(request *CreateFileDetectRequest, callback func(response *CreateFileDetectResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileDetectResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileDetect(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func MakeFsOnDisk() FileSystem { return filesys.MakeFsOnDisk() }", "func (storage *B2Storage) CreateDirectory(threadIndex int, dir string) (err error) {\n return nil\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func NewFileSystem(fs http.FileSystem, name string) FileSystem {\n\treturn Trace(&fileSystem{fs}, name)\n}", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func NewFileSystemClient() (FileSystemClient, error) {\n\taddress := os.Getenv(constants.EnvFileSystemAddress)\n\tif address == \"\" {\n\t\treturn nil, fmt.Errorf(\"Environment variable '%s' not set\", constants.EnvFileSystemAddress)\n\t}\n\n\t// Create a connection\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a client\n\tc := fs.NewFileSystemClient(conn)\n\n\treturn &fileSystemClient{c: c, conn: conn}, nil\n}", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func NewFileSystem() FileSystem {\n\treturn &fs{\n\t\trunner: NewCommandRunner(),\n\t}\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func (fs *VolatileFileSystem) CreateFile(name string, data []byte) error {\n\tvar flags C.int = C.SQLITE_OPEN_EXCLUSIVE | C.SQLITE_OPEN_CREATE\n\n\tiFd, rc := fs.vfs.Open(name, flags)\n\tif rc != C.SQLITE_OK {\n\t\treturn Error{\n\t\t\tCode: ErrIoErr,\n\t\t\tExtendedCode: ErrNoExtended(rc),\n\t\t}\n\t}\n\n\tfile, _ := fs.vfs.FileByFD(iFd)\n\tfile.mu.Lock()\n\tfile.data = data\n\tfile.mu.Unlock()\n\n\treturn nil\n}", "func (client *Client) ListAvailableFileSystemTypesWithCallback(request *ListAvailableFileSystemTypesRequest, callback func(response *ListAvailableFileSystemTypesResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ListAvailableFileSystemTypesResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ListAvailableFileSystemTypes(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func NewFS(basedir string) (kvs *FS, err error) {\n\treturn newFileSystem(basedir, os.MkdirAll)\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func (fsys *gcsFS) Create(name string) (WriterFile, error) {\n\tf, err := fsys.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*GCSFile), nil\n}", "func NewCfnFileSystem(scope awscdk.Construct, id *string, props *CfnFileSystemProps) CfnFileSystem {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnFileSystem{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_fsx.CfnFileSystem\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func (d *Definition) Create() error {\n\terrChan := make(chan error)\n\ttree := d.ResourceTree\n\n\t// Check definition context exists\n\tif _, err := os.Stat(tree.Root().ID()); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t`Definition Create: Expected context: \"%s\" to exist.`,\n\t\t\ttree.Root().Name(),\n\t\t)\n\t}\n\n\tgo func() {\n\t\tdefer close(errChan)\n\t\ttree.Traverse(func(r Resource) {\n\t\t\terrChan <- r.Create(d.Options)\n\t\t})\n\t}()\n\n\tfor err := range errChan {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Definition Create: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CreateRecursive(ctx context.Context, conn *ZkConn, zkPath string, value []byte, flags int32, aclv []zk.ACL, maxCreationDepth int) (string, error) {\n\tpathCreated, err := conn.Create(ctx, zkPath, value, flags, aclv)\n\tif err == zk.ErrNoNode {\n\t\tif maxCreationDepth == 0 {\n\t\t\treturn \"\", zk.ErrNoNode\n\t\t}\n\n\t\t// Make sure that nodes are either \"file\" or\n\t\t// \"directory\" to mirror file system semantics.\n\t\tdirAclv := make([]zk.ACL, len(aclv))\n\t\tfor i, acl := range aclv {\n\t\t\tdirAclv[i] = acl\n\t\t\tdirAclv[i].Perms = PermDirectory\n\t\t}\n\t\tparentPath := path.Dir(zkPath)\n\t\t_, err = CreateRecursive(ctx, conn, parentPath, nil, 0, dirAclv, maxCreationDepth-1)\n\t\tif err != nil && err != zk.ErrNodeExists {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpathCreated, err = conn.Create(ctx, zkPath, value, flags, aclv)\n\t}\n\treturn pathCreated, err\n}", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func (client *Client) CreateGatewayFileShareWithCallback(request *CreateGatewayFileShareRequest, callback func(response *CreateGatewayFileShareResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateGatewayFileShareResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateGatewayFileShare(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewFileSystemClient() FileSystemClient {\n\treturn FsClient{}\n}", "func (self *File_Client) CreateDir(path interface{}, name interface{}) error {\n\n\trqst := &filepb.CreateDirRequest{\n\t\tPath: Utility.ToString(path),\n\t\tName: Utility.ToString(name),\n\t}\n\n\t_, err := self.c.CreateDir(context.Background(), rqst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func NewFileSystem(t mockConstructorTestingTNewFileSystem) *FileSystem {\n\tmock := &FileSystem{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func NewFileSystem() FileSystem {\r\n\treturn &osFileSystem{}\r\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\t// Parse config into Options struct\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = checkUploadChunkSize(opt.ChunkSize)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dropbox: chunk size: %w\", err)\n\t}\n\n\t// Convert the old token if it exists. The old token was just\n\t// just a string, the new one is a JSON blob\n\toldToken, ok := m.Get(config.ConfigToken)\n\toldToken = strings.TrimSpace(oldToken)\n\tif ok && oldToken != \"\" && oldToken[0] != '{' {\n\t\tfs.Infof(name, \"Converting token to new format\")\n\t\tnewToken := fmt.Sprintf(`{\"access_token\":\"%s\",\"token_type\":\"bearer\",\"expiry\":\"0001-01-01T00:00:00Z\"}`, oldToken)\n\t\terr := config.SetValueAndSave(name, config.ConfigToken, newToken)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"NewFS convert token: %w\", err)\n\t\t}\n\t}\n\n\toAuthClient, _, err := oauthutil.NewClient(ctx, name, m, getOauthConfig(m))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to configure dropbox: %w\", err)\n\t}\n\n\tci := fs.GetConfig(ctx)\n\n\tf := &Fs{\n\t\tname: name,\n\t\topt: *opt,\n\t\tci: ci,\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(opt.PacerMinSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t}\n\tf.batcher, err = newBatcher(ctx, f, f.opt.BatchMode, f.opt.BatchSize, time.Duration(f.opt.BatchTimeout))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg := dropbox.Config{\n\t\tLogLevel: dropbox.LogOff, // logging in the SDK: LogOff, LogDebug, LogInfo\n\t\tClient: oAuthClient, // maybe???\n\t\tHeaderGenerator: f.headerGenerator,\n\t}\n\n\t// unauthorized config for endpoints that fail with auth\n\tucfg := dropbox.Config{\n\t\tLogLevel: dropbox.LogOff, // logging in the SDK: LogOff, LogDebug, LogInfo\n\t}\n\n\t// NOTE: needs to be created pre-impersonation so we can look up the impersonated user\n\tf.team = team.New(cfg)\n\n\tif opt.Impersonate != \"\" {\n\t\tuser := team.UserSelectorArg{\n\t\t\tEmail: opt.Impersonate,\n\t\t}\n\t\tuser.Tag = \"email\"\n\n\t\tmembers := []*team.UserSelectorArg{&user}\n\t\targs := team.NewMembersGetInfoArgs(members)\n\n\t\tmemberIds, err := f.team.MembersGetInfo(args)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid dropbox team member: %q: %w\", opt.Impersonate, err)\n\t\t}\n\t\tif len(memberIds) == 0 || memberIds[0].MemberInfo == nil || memberIds[0].MemberInfo.Profile == nil {\n\t\t\treturn nil, fmt.Errorf(\"dropbox team member not found: %q\", opt.Impersonate)\n\t\t}\n\n\t\tcfg.AsMemberID = memberIds[0].MemberInfo.Profile.MemberProfile.TeamMemberId\n\t}\n\n\tf.srv = files.New(cfg)\n\tf.svc = files.New(ucfg)\n\tf.sharing = sharing.New(cfg)\n\tf.users = users.New(cfg)\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tReadMimeType: false,\n\t\tCanHaveEmptyDirectories: true,\n\t})\n\n\t// do not fill features yet\n\tif f.opt.SharedFiles {\n\t\tf.setRoot(root)\n\t\tif f.root == \"\" {\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.findSharedFile(ctx, f.root)\n\t\tf.root = \"\"\n\t\tif err == nil {\n\t\t\treturn f, fs.ErrorIsFile\n\t\t}\n\t\treturn f, nil\n\t}\n\n\tif f.opt.SharedFolders {\n\t\tf.setRoot(root)\n\t\tif f.root == \"\" {\n\t\t\treturn f, nil // our root it empty so we probably want to list shared folders\n\t\t}\n\n\t\tdir := path.Dir(f.root)\n\t\tif dir == \".\" {\n\t\t\tdir = f.root\n\t\t}\n\n\t\t// root is not empty so we have find the right shared folder if it exists\n\t\tid, err := f.findSharedFolder(ctx, dir)\n\t\tif err != nil {\n\t\t\t// if we didn't find the specified shared folder we have to bail out here\n\t\t\treturn nil, err\n\t\t}\n\t\t// we found the specified shared folder so let's mount it\n\t\t// this will add it to the users normal root namespace and allows us\n\t\t// to actually perform operations on it using the normal api endpoints.\n\t\terr = f.mountSharedFolder(ctx, id)\n\t\tif err != nil {\n\t\t\tswitch e := err.(type) {\n\t\t\tcase sharing.MountFolderAPIError:\n\t\t\t\tif e.EndpointError == nil || (e.EndpointError != nil && e.EndpointError.Tag != sharing.MountFolderErrorAlreadyMounted) {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// if the mount failed we have to abort here\n\t\t}\n\t\t// if the mount succeeded it's now a normal folder in the users root namespace\n\t\t// we disable shared folder mode and proceed normally\n\t\tf.opt.SharedFolders = false\n\t}\n\n\tf.features.Fill(ctx, f)\n\n\t// If root starts with / then use the actual root\n\tif strings.HasPrefix(root, \"/\") {\n\t\tvar acc *users.FullAccount\n\t\terr = f.pacer.Call(func() (bool, error) {\n\t\t\tacc, err = f.users.GetCurrentAccount()\n\t\t\treturn shouldRetry(ctx, err)\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"get current account failed: %w\", err)\n\t\t}\n\t\tswitch x := acc.RootInfo.(type) {\n\t\tcase *common.TeamRootInfo:\n\t\t\tf.ns = x.RootNamespaceId\n\t\tcase *common.UserRootInfo:\n\t\t\tf.ns = x.RootNamespaceId\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown RootInfo type %v %T\", acc.RootInfo, acc.RootInfo)\n\t\t}\n\t\tfs.Debugf(f, \"Using root namespace %q\", f.ns)\n\t}\n\tf.setRoot(root)\n\n\t// See if the root is actually an object\n\tif f.root != \"\" {\n\t\t_, err = f.getFileMetadata(ctx, f.slashRoot)\n\t\tif err == nil {\n\t\t\tnewRoot := path.Dir(f.root)\n\t\t\tif newRoot == \".\" {\n\t\t\t\tnewRoot = \"\"\n\t\t\t}\n\t\t\tf.setRoot(newRoot)\n\t\t\t// return an error with an fs which points to the parent\n\t\t\treturn f, fs.ErrorIsFile\n\t\t}\n\t}\n\treturn f, nil\n}", "func (fb *FileBase) Create(ID string) (io.WriteCloser, error) {\n\treturn fb.fs.Create(filepath.Join(fb.root, ID))\n}", "func (a DBFSAPI) Create(path string, overwrite bool, data string) (err error) {\n\tbyteArr, err := base64.StdEncoding.DecodeString(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbyteChunks := split(byteArr, 1e6)\n\thandle, err := a.createHandle(path, overwrite)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\terr = a.closeHandle(handle)\n\t}()\n\tfor _, byteChunk := range byteChunks {\n\t\tb64Data := base64.StdEncoding.EncodeToString(byteChunk)\n\t\terr := a.addBlock(b64Data, handle)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateFilesystem(path string) error {\n\treturn nil\n}", "func getFileSystem(frame *rtda.Frame) {\n\tthread := frame.Thread\n\tunixFsClass := frame.GetClassLoader().LoadClass(\"java/io/UnixFileSystem\")\n\tif unixFsClass.InitializationNotStarted() {\n\t\tframe.NextPC = thread.PC // undo getFileSystem\n\t\tthread.InitClass(unixFsClass)\n\t\treturn\n\t}\n\n\tunixFsObj := unixFsClass.NewObj()\n\tframe.PushRef(unixFsObj)\n\n\t// call <init>\n\tframe.PushRef(unixFsObj) // this\n\tconstructor := unixFsClass.GetDefaultConstructor()\n\tthread.InvokeMethod(constructor)\n}", "func (linux *Linux) FileCreate(filePath string) error {\n\tif !linux.FileExists(filePath) {\n\t\tfile, err := os.Create(linux.applyChroot(filePath))\n\t\tdefer file.Close()\n\t\treturn err\n\t}\n\treturn os.ErrExist\n}", "func NewFileSystemServer(fs FileSystem) fuse.Server {\n\treturn &fileSystemServer{\n\t\tfs: fs,\n\t}\n}", "func createTransfer(path, name string, friendNumber uint32, file *os.File, size uint64, callback func(status State)) *transfer {\n\treturn &transfer{\n\t\tpath: path,\n\t\tname: name,\n\t\tfriend: friendNumber,\n\t\tfile: file,\n\t\tsize: size,\n\t\tprogress: 0,\n\t\tdoneCallback: callback,\n\t\tisDone: false}\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\t// Parse config into Options struct\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(opt.Headers)%2 != 0 {\n\t\treturn nil, errors.New(\"odd number of headers supplied\")\n\t}\n\n\tif !strings.HasSuffix(opt.Endpoint, \"/\") {\n\t\topt.Endpoint += \"/\"\n\t}\n\n\t// Parse the endpoint and stick the root onto it\n\tbase, err := url.Parse(opt.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu, err := rest.URLJoin(base, rest.URLPathEscape(root))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := fshttp.NewClient(ctx)\n\n\tendpoint, isFile := getFsEndpoint(ctx, client, u.String(), opt)\n\tfs.Debugf(nil, \"Root: %s\", endpoint)\n\tu, err = url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tci := fs.GetConfig(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tci: ci,\n\t\thttpClient: client,\n\t\tendpoint: u,\n\t\tendpointURL: u.String(),\n\t}\n\tf.features = (&fs.Features{\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\n\tif isFile {\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\n\tif !strings.HasSuffix(f.endpointURL, \"/\") {\n\t\treturn nil, errors.New(\"internal error: url doesn't end with /\")\n\t}\n\n\treturn f, nil\n}", "func NewFs(client *api.Client) (*fs, nodefs.Node) {\n\tdefaultfs := pathfs.NewDefaultFileSystem() // Returns ENOSYS by default\n\treadonlyfs := pathfs.NewReadonlyFileSystem(defaultfs) // R/W calls return EPERM\n\n\tkwfs := &fs{readonlyfs, client}\n\tnfs := pathfs.NewPathNodeFs(kwfs, nil)\n\tnfs.SetDebug(true)\n\treturn kwfs, nfs.Root()\n}", "func NewFileSystem(ctrl *gomock.Controller) *FileSystem {\n\tmock := &FileSystem{ctrl: ctrl}\n\tmock.recorder = &FileSystemMockRecorder{mock}\n\treturn mock\n}", "func (fs *EmbedFs) Create(path string) (file, error) {\n\treturn nil, ErrNotAvail\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\t// fmt.Printf(\"creating file in dir with inode %d\\n\", d.inodeNum)\n\t// fmt.Println(\"name of file to be created is: \" + req.Name)\n\tdirTable, err := getTable(d.inode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileExists := dirTable.Table[req.Name] != 0\n\tvar inode *Inode\n\tvar inodeNum uint64\n\tif !fileExists {\n\t\t// fmt.Println(\"file does not yet exist in Create\")\n\t\tvar isDir int8 = 0\n\t\tinode = createInode(isDir)\n\t\tinodeNum = d.inodeStream.next()\n\t\tinode.init(d.inodeNum, inodeNum)\n\t\td.addFile(req.Name, inodeNum)\n\t} else {\n\t\t// fmt.Println(\"file already exists in Create\")\n\t\tinodeNum = dirTable.Table[req.Name]\n\t\tinode, err = getInode(inodeNum)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tchild := &File{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t\tinodeStream: d.inodeStream,\n\t}\n\thandle := &FileHandle{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t}\n\t// can any errors happen here?\n\treturn child, handle, nil\n}", "func (f *Fs) mkdir(ctx context.Context, dirPath string) (err error) {\n\t// defer log.Trace(dirPath, \"\")(\"err=%v\", &err)\n\terr = f._mkdir(ctx, dirPath)\n\tif apiErr, ok := err.(*api.Error); ok {\n\t\t// parent does not exist so create it first then try again\n\t\tif apiErr.StatusCode == http.StatusConflict {\n\t\t\terr = f.mkParentDir(ctx, dirPath)\n\t\t\tif err == nil {\n\t\t\t\terr = f._mkdir(ctx, dirPath)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (fs *dsFileSys) Create(name string) (fsi.File, error) {\n\n\t// WriteFile & Create\n\tdir, bname := fs.SplitX(name)\n\n\tf := DsFile{}\n\tf.fSys = fs\n\tf.BName = common.Filify(bname)\n\tf.Dir = dir\n\tf.MModTime = time.Now()\n\tf.MMode = 0644\n\n\t// let all the properties by set by fs.saveFileByPath\n\terr := f.Sync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return &f, nil\n\tff := fsi.File(&f)\n\treturn ff, err\n\n}", "func Create(name string) (*os.File, error)", "func (fs osFS) Create(path string) (io.WriteCloser, error) {\n\tf, err := os.Create(fs.resolve(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Open: %s is a directory\", path)\n\t}\n\n\treturn f, nil\n}", "func (fs *bundleFs) Create(name string) (afero.File, error) {\n\treturn nil, ErrReadOnly\n}", "func (c *fileSystemClient) CreateVolumeForWrite(ctx context.Context, in *fs.CreateVolumeForWriteRequest, opts ...grpc.CallOption) (*fs.CreateVolumeForWriteResponse, error) {\n\treturn c.c.CreateVolumeForWrite(ctx, in, opts...)\n}", "func (z *zfsctl) MountFileSystem(ctx context.Context, name, options, opts string, all bool) *execute {\n\targs := []string{\"mount\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif len(opts) > 0 {\n\t\targs = append(args, opts)\n\t}\n\tif all {\n\t\targs = append(args, \"-a\")\n\t} else {\n\t\targs = append(args, name)\n\t}\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (s *storager) Create(ctx context.Context, location string, mode os.FileMode, reader io.Reader, isDir bool, options ...storage.Option) error {\n\troot := s.Root\n\tif isDir {\n\t\t_, err := root.Folder(location, mode)\n\t\treturn err\n\t}\n\treturn s.Upload(ctx, location, mode, reader)\n}", "func NewFs(remote string) fs.Fs {\n\tf, err := fs.NewFs(remote)\n\tif err != nil {\n\t\tfs.Stats.Error()\n\t\tlog.Fatalf(\"Failed to create file system for %q: %v\", remote, err)\n\t}\n\treturn f\n}", "func (a *FileStorageApiService) CreateDirectoryExecute(r ApiCreateDirectoryRequest) (SingleNode, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SingleNode\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.Ctx, \"FileStorageApiService.CreateDirectory\")\n\tif localBasePath == \"/\" {\n\t localBasePath = \"\"\n\t}\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v2/file_storage/buckets/{bucket_id}/create_directory\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucket_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_bucketId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.P_nodeRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"nodeRequest is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\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\t// body params\n\tlocalVarPostBody = r.P_nodeRequest\n\treq, err := a.client.prepareRequest(r.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(req)\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 (*FileSystemBase) Fsync(path string, datasync bool, fh uint64) int {\n\treturn -ENOSYS\n}", "func CheckFsCreationInProgress(device model.Device) (inProgress bool, err error) {\n\treturn linux.CheckFsCreationInProgress(device)\n}", "func (fsi *fsIOPool) Create(path string) (wlk *lock.LockedFile, err error) {\n\tif err = checkPathLength(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates parent if missing.\n\tif err = mkdirAll(pathutil.Dir(path), 0777); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attempt to create the file.\n\twlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsPermission(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tcase isSysErrIsDir(err):\n\t\t\treturn nil, errIsNotRegular\n\t\tcase isSysErrPathNotFound(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Success.\n\treturn wlk, nil\n}", "func (client *Client) ListFileSystemsWithChan(request *ListFileSystemsRequest) (<-chan *ListFileSystemsResponse, <-chan error) {\n\tresponseChan := make(chan *ListFileSystemsResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ListFileSystems(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *fileSystemClient) CreateFileView(ctx context.Context, in *fs.CreateFileViewRequest, opts ...grpc.CallOption) (*fs.CreateFileViewResponse, error) {\n\treturn c.c.CreateFileView(ctx, in, opts...)\n}", "func NewFS(db *bolt.DB, bucketpath string) (*FileSystem, error) {\n\n\t// create buckets\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\treturn bucketInit(tx, bucketpath)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// load or initialize\n\trootIno := uint64(1)\n\tfs := &FileSystem{\n\t\tdb: db,\n\t\tbucket: bucketpath,\n\t\trootIno: rootIno,\n\t\tcwd: \"/\",\n\t}\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tbb, err := openBucket(tx, bucketpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb := newFsBucket(bb)\n\n\t\t// create the `nil` node if it doesn't exist\n\t\terr = b.InodeInit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// load the\n\t\tdata := make([]byte, 4)\n\t\tbinary.BigEndian.PutUint32(data, uint32(0755))\n\t\t_, err = b.LoadOrSet(\"umask\", data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// load the root Ino if one is available\n\t\tdata, err = b.LoadOrSet(\"rootIno\", i2b(rootIno))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trootIno = b2i(data)\n\n\t\t_, err = b.GetInode(rootIno)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err == os.ErrNotExist {\n\t\t\tnode := newInode(os.ModeDir | 0755)\n\t\t\tnode.countUp()\n\t\t\terr = b.PutInode(rootIno, node)\n\t\t\tif err != nil {\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfs.rootIno = rootIno\n\treturn fs, nil\n\n}", "func (client *Client) RenameDbfsWithCallback(request *RenameDbfsRequest, callback func(response *RenameDbfsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RenameDbfsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RenameDbfs(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func createFormatFS(fsPath string) error {\n\tfsFormatPath := pathJoin(fsPath, minioMetaBucket, formatConfigFile)\n\n\t// Attempt a write lock on formatConfigFile `format.json`\n\t// file stored in minioMetaBucket(.minio.sys) directory.\n\tlk, err := lock.TryLockedOpenFile((fsFormatPath), os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn traceError(err)\n\t}\n\t// Close the locked file upon return.\n\tdefer lk.Close()\n\n\t// Load format on disk, checks if we are unformatted\n\t// writes the new format.json\n\tvar format = &formatConfigV1{}\n\terr = format.LoadFormat(lk)\n\tif errorCause(err) == errUnformattedDisk {\n\t\t_, err = newFSFormat().WriteTo(lk)\n\t\treturn err\n\t}\n\treturn err\n}", "func (lm LinksManager) CreateFile(url *url.URL, t resource.Type) (*os.File, resource.Issue) {\n\treturn nil, resource.NewIssue(url.String(), \"NOT_IMPLEMENTED_YET\", \"CreateFile not implemented in graph.LinkLifecyleSettings\", true)\n}", "func NewFS(dataDir string) Interface {\n\treturn &fsLoader{dataDir: dataDir}\n}", "func NewFilesystem(_ context.Context, cfgMap map[string]interface{}) (qfs.Filesystem, error) {\n\treturn NewFS(cfgMap)\n}", "func createTmpConfigInFileSystem(rawJSON string) (func(), error) {\n\tconfigJSONFile, err := os.CreateTemp(os.TempDir(), \"configJSON-\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create file %v: %v\", configJSONFile.Name(), err)\n\t}\n\t_, err = configJSONFile.Write(json.RawMessage(rawJSON))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot write marshalled JSON: %v\", err)\n\t}\n\toldObservabilityConfigFile := envconfig.ObservabilityConfigFile\n\tenvconfig.ObservabilityConfigFile = configJSONFile.Name()\n\treturn func() {\n\t\tconfigJSONFile.Close()\n\t\tenvconfig.ObservabilityConfigFile = oldObservabilityConfigFile\n\t}, nil\n}", "func CreateFiles(fS *FileCollection, ts int64, filelock chan int64) {\n\tvar lt time.Time\n\tvar err error\n\n\tselect {\n\tcase <- time.After(5 * time.Second):\n\t\t//If 5 seconds pass without getting the proper lock, abort\n\t\tlog.Printf(\"partdisk.CreateFiles(): timeout waiting for lock\\n\")\n\t\treturn\n\tcase chts := <- filelock:\n\t\tif chts == ts { //Got the lock and it matches the timestamp received\n\t\t\t//Proceed\n\t\t\tfS.flid = ts\n\t\t\tdefer func(){\n\t\t\t\tfilelock <- 0 //Release lock\n\t\t\t}()\n\t\t\tlt = time.Now() //Start counting how long does the parts creation take\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, timestamps match: %d\\n\",ts)\n\t\t} else {\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, but timestamps missmatch: %d - %d\\n\", ts,chts)\n\t\t\tfilelock <- chts\n\t\t\treturn\n\t\t}\n\t}\n\t//Lock obtained proper, create/delete the files\n\terr = adrefiles(fS)\n\tif err != nil {\n\t\tlog.Printf(\"CreateFiles(): Error creating file: %s\\n\",err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"CreateFiles(): Request %d completed in %d seconds\\n\",ts,int64(time.Since(lt).Seconds()))\n}", "func (z *ZkPlus) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tz.forPath(path).Log(logkey.ZkMethod, \"Create\")\n\tp, err := z.blockOnConn().Create(z.realPath(path), data, flags, acl)\n\tif strings.HasPrefix(p, z.pathPrefix) && z.pathPrefix != \"\" {\n\t\tp = p[len(z.pathPrefix)+1:]\n\t}\n\treturn p, errors.Annotatef(err, \"cannot create zk path %s\", path)\n}", "func NewStatsFileSystem(sc *statsclient.StatsClient) (root fs.InodeEmbedder, err error) {\n\treturn &dirNode{client: sc}, nil\n}", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func (dw *DirWatcher) onRootCreated() {\n\tvar (\n\t\tlogp = \"DirWatcher.onRootCreated\"\n\t\terr error\n\t)\n\n\tdw.fs, err = New(&dw.Options)\n\tif err != nil {\n\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\treturn\n\t}\n\n\tdw.root, err = dw.fs.Get(\"/\")\n\tif err != nil {\n\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\treturn\n\t}\n\n\tdw.dirsLocker.Lock()\n\tdw.dirs = make(map[string]*Node)\n\tdw.dirsLocker.Unlock()\n\tdw.mapSubdirs(dw.root)\n\n\tns := NodeState{\n\t\tNode: *dw.root,\n\t\tState: FileStateCreated,\n\t}\n\n\tselect {\n\tcase dw.qchanges <- ns:\n\tdefault:\n\t}\n}", "func NewFileSystemWatch(files []string, ev func(fsnotify.Event), errs func(error)) *FileSystemWatch {\n\treturn &FileSystemWatch{\n\t\tfiles: files,\n\t\tevents: ev,\n\t\terrors: errs,\n\t}\n}", "func (fs *Fs) Create(name string) (*os.File, error) {\n\treturn os.Create(name) // #nosec G304\n}", "func createDirectories() error {\n\n\tvar brickPath = glusterBrickPath + \"/\" + glusterVolumeName\n\tvar mountPath = glusterMountPath + \"/\" + glusterVolumeName\n\tvar volumePath = glusterDockerVolumePath\n\n\tdirPath := []string{brickPath, mountPath, volumePath}\n\n\tfor i := 0; i < len(dirPath); i++ {\n\t\tif helpers.Exists(dirPath[i]) == false {\n\t\t\terr := helpers.CreateDir(dirPath[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *DriveDB) createRoot() error {\n\tlaunch, _ := time.Unix(1335225600, 0).MarshalText()\n\tfile := &gdrive.File{\n\t\tId: d.rootId,\n\t\tTitle: \"/\",\n\t\tMimeType: driveFolderMimeType,\n\t\tLastViewedByMeDate: string(launch),\n\t\tModifiedDate: string(launch),\n\t\tCreatedDate: string(launch),\n\t}\n\t// Inode allocation special-cases the rootId, so we can let the usual\n\t// code paths do all the work\n\t_, err := d.UpdateFile(nil, file)\n\treturn err\n}", "func (cs *ControllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {\n\tname := req.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume name must be provided\")\n\t}\n\tif err := cs.validateVolumeCapabilities(req.GetVolumeCapabilities()); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\treqCapacity := req.GetCapacityRange().GetRequiredBytes()\n\tnfsVol, err := cs.newNFSVolume(name, reqCapacity, req.GetParameters())\n\tif err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tvar volCap *csi.VolumeCapability\n\tif len(req.GetVolumeCapabilities()) > 0 {\n\t\tvolCap = req.GetVolumeCapabilities()[0]\n\t} // 执行挂载 命令\n\t// Mount nfs base share so we can create a subdirectory\n\tif err = cs.internalMount(ctx, nfsVol, volCap); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to mount nfs server: %v\", err.Error())\n\t}\n\tdefer func() {\n\t\tif err = cs.internalUnmount(ctx, nfsVol); err != nil {\n\t\t\tklog.Warningf(\"failed to unmount nfs server: %v\", err.Error())\n\t\t}\n\t}()\n\n\t// Create subdirectory under base-dir\n\t// TODO: revisit permissions\n\tinternalVolumePath := cs.getInternalVolumePath(nfsVol)\n\tif err = os.Mkdir(internalVolumePath, 0777); err != nil && !os.IsExist(err) {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to make subdirectory: %v\", err.Error())\n\t}\n\t// Remove capacity setting when provisioner 1.4.0 is available with fix for\n\t// https://github.com/kubernetes-csi/external-provisioner/pull/271\n\treturn &csi.CreateVolumeResponse{Volume: cs.nfsVolToCSI(nfsVol, reqCapacity)}, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}" ]
[ "0.66443145", "0.6494744", "0.64063805", "0.6279257", "0.6207732", "0.6184654", "0.61342597", "0.60683924", "0.6045436", "0.56931496", "0.5614541", "0.55832964", "0.5576147", "0.54953367", "0.5450374", "0.5437641", "0.53679824", "0.536721", "0.536561", "0.53433496", "0.5338602", "0.5312654", "0.53121203", "0.52847797", "0.5273296", "0.52483857", "0.5241643", "0.5208248", "0.52045506", "0.51309025", "0.5125862", "0.5084794", "0.50722307", "0.5061616", "0.5048797", "0.5023597", "0.49996778", "0.49942267", "0.49849206", "0.4979911", "0.49797067", "0.49671754", "0.49670565", "0.49569687", "0.4930457", "0.492508", "0.4915943", "0.49115378", "0.49071872", "0.4906612", "0.48995763", "0.48977298", "0.4892283", "0.48877427", "0.48847038", "0.48770732", "0.48481736", "0.48409742", "0.48370454", "0.4830748", "0.48241818", "0.48014215", "0.4798321", "0.47835004", "0.4754567", "0.47537243", "0.4735462", "0.473011", "0.47294652", "0.47267115", "0.47211236", "0.47104704", "0.47069806", "0.4700375", "0.4694624", "0.46938145", "0.4687137", "0.46792284", "0.4675613", "0.46699896", "0.46686015", "0.4668587", "0.46647882", "0.46610698", "0.4659716", "0.46509025", "0.46493894", "0.46449304", "0.4642953", "0.4631977", "0.463056", "0.46190038", "0.46152478", "0.46079794", "0.46075723", "0.46060452", "0.46001044", "0.4598306", "0.4598306", "0.4598306" ]
0.8151044
0
CreateCreateFileSystemRequest creates a request to invoke CreateFileSystem API
CreateCreateFileSystemRequest создает запрос для вызова API CreateFileSystem
func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) { request = &CreateFileSystemRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("DFS", "2018-06-20", "CreateFileSystem", "alidfs", "openAPI") request.Method = requests.POST return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func CreateCreateFileDetectRequest() (request *CreateFileDetectRequest) {\n\trequest = &CreateFileDetectRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Sas\", \"2018-12-03\", \"CreateFileDetect\", \"sas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateListAvailableFileSystemTypesRequest() (request *ListAvailableFileSystemTypesRequest) {\n\trequest = &ListAvailableFileSystemTypesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EHPC\", \"2018-04-12\", \"ListAvailableFileSystemTypes\", \"ehs\", \"openAPI\")\n\treturn\n}", "func CreateFile(w http.ResponseWriter, r *http.Request) {\n\tvar body datastructures.CreateBody\n\n\tif reqBody, err := ioutil.ReadAll(r.Body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Could not read request body\"))\n\t\treturn\n\t} else if err = json.Unmarshal(reqBody, &body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"Bad request\"))\n\t\treturn\n\t}\n\n\tlog.Println(\n\t\t\"Create file request for\",\n\t\t\"workspace\", body.Workspace.ToString(),\n\t\t\"path\", filepath.Join(body.File.Path...),\n\t)\n\n\tif err := utils.CreateFile(body.Workspace, body.File); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFaceConfigRequest() (request *CreateFaceConfigRequest) {\n\trequest = &CreateFaceConfigRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Cloudauth\", \"2019-03-07\", \"CreateFaceConfig\", \"cloudauth\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateRenameDbfsRequest() (request *RenameDbfsRequest) {\n\trequest = &RenameDbfsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DBFS\", \"2020-04-18\", \"RenameDbfs\", \"dbfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateClusterRequest() (request *CreateClusterRequest) {\n\trequest = &CreateClusterRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"CS\", \"2015-12-15\", \"CreateCluster\", \"/clusters\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateVSwitchRequest() (request *CreateVSwitchRequest) {\n\trequest = &CreateVSwitchRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ecs\", \"2014-05-26\", \"CreateVSwitch\", \"ecs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateGetDirectoryOrFilePropertiesRequest() (request *GetDirectoryOrFilePropertiesRequest) {\n\trequest = &GetDirectoryOrFilePropertiesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"NAS\", \"2017-06-26\", \"GetDirectoryOrFileProperties\", \"nas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func CreateCreateGatewayFileShareRequest() (request *CreateGatewayFileShareRequest) {\n\trequest = &CreateGatewayFileShareRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"sgw\", \"2018-05-11\", \"CreateGatewayFileShare\", \"hcs_sgw\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateRequest(c context.Context, record *models.FileRequest) error {\n\treturn FromContext(c).CreateRequest(record)\n}", "func (client *KeyVaultClient) createKeyCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyCreateParameters, options *KeyVaultClientCreateKeyOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}/create\"\n\tif keyName == \"\" {\n\t\treturn nil, errors.New(\"parameter keyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-name}\", url.PathEscape(keyName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func (client *KeyVaultClient) createKeyCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyCreateParameters, options *KeyVaultClientCreateKeyOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}/create\"\n\tif keyName == \"\" {\n\t\treturn nil, errors.New(\"parameter keyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-name}\", url.PathEscape(keyName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.3\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func CreateCreateScheduleRequest() (request *CreateScheduleRequest) {\n\trequest = &CreateScheduleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"fnf\", \"2019-03-15\", \"CreateSchedule\", \"fnf\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func newCreateRequest(path, name string) (*Request, error) {\n\t// XXX Better to delay reading the file content until it is needed\n\t// inside sendRequests() loop, and skip the overhead from copying data.\n\t// ==> Replace Request.Data by the file descriptor, then use\n\t// splice(2) (or other) for zero-copying (use\n\t// rpc.NewClientWithCodec() instead of rpc.NewClient())\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Request{Type: requestCreate, Path: name, Data: content}, nil\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (z *ZFS) Create(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CreateArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif args.Name == \"\" {\n\t\treturn nil, nil, errors.New(\"missing arg: name\")\n\t}\n\n\tif err := fixPropertyTypesFromJSON(args.Properties); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar ds *gozfs.Dataset\n\tvar err error\n\tswitch args.Type {\n\tcase gozfs.DatasetFilesystem:\n\t\tds, err = gozfs.CreateFilesystem(args.Name, args.Properties)\n\tcase gozfs.DatasetVolume:\n\t\tif args.Volsize <= 0 {\n\t\t\terr = errors.New(\"missing or invalid arg: volsize\")\n\t\t\tbreak\n\t\t}\n\t\tds, err = gozfs.CreateVolume(args.Name, args.Volsize, args.Properties)\n\tdefault:\n\t\terr = errors.New(\"missing or invalid arg: type\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &DatasetResult{newDataset(ds)}, nil, nil\n}", "func CreateCreateTopicRequest() (request *CreateTopicRequest) {\n\trequest = &CreateTopicRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"alikafka\", \"2019-09-16\", \"CreateTopic\", \"alikafka\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateFabricChannelRequest() (request *CreateFabricChannelRequest) {\n\trequest = &CreateFabricChannelRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Baas\", \"2018-12-21\", \"CreateFabricChannel\", \"baas\", \"openAPI\")\n\treturn\n}", "func CreateDescribeLogstoreStorageRequest() (request *DescribeLogstoreStorageRequest) {\n\trequest = &DescribeLogstoreStorageRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Sas\", \"2018-12-03\", \"DescribeLogstoreStorage\", \"sas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func CreateCreateAgentRequest() (request *CreateAgentRequest) {\n\trequest = &CreateAgentRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"scsp\", \"2020-07-02\", \"CreateAgent\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *FileServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *FileServicesListOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodGet, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2019-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func (client *ContainerClient) createCreateRequest(ctx context.Context, options *ContainerClientCreateOptions, containerCPKScopeInfo *ContainerCPKScopeInfo) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"restype\", \"container\")\n\tif options != nil && options.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*options.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\tif options != nil && options.Metadata != nil {\n\t\tfor k, v := range options.Metadata {\n\t\t\tif v != nil {\n\t\t\t\treq.Raw().Header[\"x-ms-meta-\"+k] = []string{*v}\n\t\t\t}\n\t\t}\n\t}\n\tif options != nil && options.Access != nil {\n\t\treq.Raw().Header[\"x-ms-blob-public-access\"] = []string{string(*options.Access)}\n\t}\n\treq.Raw().Header[\"x-ms-version\"] = []string{\"2020-10-02\"}\n\tif options != nil && options.RequestID != nil {\n\t\treq.Raw().Header[\"x-ms-client-request-id\"] = []string{*options.RequestID}\n\t}\n\tif containerCPKScopeInfo != nil && containerCPKScopeInfo.DefaultEncryptionScope != nil {\n\t\treq.Raw().Header[\"x-ms-default-encryption-scope\"] = []string{*containerCPKScopeInfo.DefaultEncryptionScope}\n\t}\n\tif containerCPKScopeInfo != nil && containerCPKScopeInfo.PreventEncryptionScopeOverride != nil {\n\t\treq.Raw().Header[\"x-ms-deny-encryption-scope-override\"] = []string{strconv.FormatBool(*containerCPKScopeInfo.PreventEncryptionScopeOverride)}\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/xml\"}\n\treturn req, nil\n}", "func (client *FileServicesClient) setServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters FileServiceProperties, options *FileServicesSetServicePropertiesOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/{FileServicesName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\turlPath = strings.ReplaceAll(urlPath, \"{FileServicesName}\", url.PathEscape(\"default\"))\n\treq, err := azcore.NewRequest(ctx, http.MethodPut, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2019-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, req.MarshalAsJSON(parameters)\n}", "func CreateCreateTagTaskRequest() (request *CreateTagTaskRequest) {\n\trequest = &CreateTagTaskRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"viapi-regen\", \"2021-11-19\", \"CreateTagTask\", \"selflearning\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func CreateCreateMeetingRequest() (request *CreateMeetingRequest) {\n\trequest = &CreateMeetingRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"aliyuncvc\", \"2019-10-30\", \"CreateMeeting\", \"aliyuncvc\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateOrUpdateDataSourceRequest() (request *CreateOrUpdateDataSourceRequest) {\n\trequest = &CreateOrUpdateDataSourceRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"aegis\", \"2016-11-11\", \"CreateOrUpdateDataSource\", \"vipaegis\", \"openAPI\")\n\treturn\n}", "func CreateCreateExchangeRequest() (request *CreateExchangeRequest) {\n\trequest = &CreateExchangeRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"amqp-open\", \"2019-12-12\", \"CreateExchange\", \"onsproxy\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateExpressSyncRequest() (request *CreateExpressSyncRequest) {\n\trequest = &CreateExpressSyncRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"sgw\", \"2018-05-11\", \"CreateExpressSync\", \"hcs_sgw\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateStackRequest() (request *CreateStackRequest) {\n\trequest = &CreateStackRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"ROS\", \"2019-09-10\", \"CreateStack\", \"ros\", \"openAPI\")\n\treturn\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func NewTaskCreateRequest(flux string) *TaskCreateRequest {\n\tthis := TaskCreateRequest{}\n\tthis.Flux = flux\n\treturn &this\n}", "func NewQtreeCreateRequest() *QtreeCreateRequest {\n\treturn &QtreeCreateRequest{}\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (client *Client) sapDiskConfigurationsCreateRequest(ctx context.Context, location string, options *ClientSAPDiskConfigurationsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.Workloads/locations/{location}/sapVirtualInstanceMetadata/default/getDiskConfigurations\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif location == \"\" {\n\t\treturn nil, errors.New(\"parameter location cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{location}\", url.PathEscape(location))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-12-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif options != nil && options.SAPDiskConfigurations != nil {\n\t\treturn req, runtime.MarshalAsJSON(req, *options.SAPDiskConfigurations)\n\t}\n\treturn req, nil\n}", "func (connection *Connection) CreateStoreRequest(fnr Fnr) (*StoreRequest, error) {\n\treturn NewStoreRequestAdabas(connection.adabasToData, fnr), nil\n}", "func CreateCreateFaceGroupRequest() (request *CreateFaceGroupRequest) {\n\trequest = &CreateFaceGroupRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"multimediaai\", \"2019-08-10\", \"CreateFaceGroup\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func Create(name string) (*os.File, error)", "func CreateCreateApplicationGroupRequest() (request *CreateApplicationGroupRequest) {\n\trequest = &CreateApplicationGroupRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"oos\", \"2019-06-01\", \"CreateApplicationGroup\", \"oos\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateVmAndSaveStockRequest() (request *CreateVmAndSaveStockRequest) {\n\trequest = &CreateVmAndSaveStockRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ens\", \"2017-11-10\", \"CreateVmAndSaveStock\", \"ens\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewCreateanewSystemContactRequest(server string, body CreateanewSystemContactJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewSystemContactRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (client *VirtualMachinesClient) createCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineName string, body VirtualMachine, options *VirtualMachinesClientBeginCreateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/virtualMachines/{virtualMachineName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif virtualMachineName == \"\" {\n\t\treturn nil, errors.New(\"parameter virtualMachineName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{virtualMachineName}\", url.PathEscape(virtualMachineName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-10-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, body)\n}", "func (c *UFSClient) NewCreateUFSVolumeRequest() *CreateUFSVolumeRequest {\n\treq := &CreateUFSVolumeRequest{}\n\n\t// setup request with client config\n\tc.Client.SetupRequest(req)\n\n\t// setup retryable with default retry policy (retry for non-create action and common error)\n\treq.SetRetryable(false)\n\treturn req\n}", "func CreateDescribeParentPlatformRequest() (request *DescribeParentPlatformRequest) {\n\trequest = &DescribeParentPlatformRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"vs\", \"2018-12-12\", \"DescribeParentPlatform\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateModifyDirectoryRequest() (request *ModifyDirectoryRequest) {\n\trequest = &ModifyDirectoryRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"vs\", \"2018-12-12\", \"ModifyDirectory\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateTrafficMirrorFilterRequest() (request *CreateTrafficMirrorFilterRequest) {\n\trequest = &CreateTrafficMirrorFilterRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Vpc\", \"2016-04-28\", \"CreateTrafficMirrorFilter\", \"vpc\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewCreateOrderRequest(server string, body CreateOrderJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateOrderRequestWithBody(server, \"application/json\", bodyReader)\n}", "func CreateSegmentSkyRequest() (request *SegmentSkyRequest) {\n\trequest = &SegmentSkyRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"imageseg\", \"2019-12-30\", \"SegmentSky\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateMetastoreCreateTableRequest() (request *MetastoreCreateTableRequest) {\n\trequest = &MetastoreCreateTableRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"MetastoreCreateTable\", \"emr\", \"openAPI\")\n\treturn\n}", "func createFileUploadRequest(url string, extraParameters map[string]string, parameterName, filePath string, fileContent []byte) *Request {\n\tfile := &RequestFile{\n\t\tParameterName: parameterName,\n\t\tFilePath: filePath,\n\t\tFileContent: fileContent,\n\t}\n\trequest := &Request{\n\t\tURL: url,\n\t\tMethod: \"PUT\",\n\t\tParameters: extraParameters,\n\t\tFiles: []*RequestFile{\n\t\t\tfile,\n\t\t},\n\t}\n\treturn request\n}", "func NewCreateUserRequest(userName string) *CreateUserRequest {\n\tthis := CreateUserRequest{}\n\tthis.UserName = userName\n\treturn &this\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func (client *Client) uploadCreateRequest(ctx context.Context, ruleID string, streamName string, logs []byte, options *UploadOptions) (*policy.Request, error) {\n\turlPath := \"/dataCollectionRules/{ruleId}/streams/{stream}\"\n\tif ruleID == \"\" {\n\t\treturn nil, errors.New(\"parameter ruleID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ruleId}\", url.PathEscape(ruleID))\n\tif streamName == \"\" {\n\t\treturn nil, errors.New(\"parameter streamName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{stream}\", url.PathEscape(streamName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\tif options != nil && options.ContentEncoding != nil {\n\t\treq.Raw().Header[\"Content-Encoding\"] = []string{*options.ContentEncoding}\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, req.SetBody(streaming.NopCloser(bytes.NewReader(logs)), \"application/json\")\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func CreateTestFlowStrategy01Request() (request *TestFlowStrategy01Request) {\n\trequest = &TestFlowStrategy01Request{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ft\", \"2018-07-13\", \"TestFlowStrategy01\", \"\", \"\")\n\trequest.Method = requests.PUT\n\treturn\n}", "func (service *Service) CreateRequest(parameters map[string]string) (*Request, error) {\n\tvar int1, int2, limit int64\n\tvar err error\n\n\t// Convert string parameters to int64\n\tif int1, err = strconv.ParseInt(parameters[\"int1\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\tif int2, err = strconv.ParseInt(parameters[\"int2\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\tif limit, err = strconv.ParseInt(parameters[\"limit\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Request{\n\t\tInt1: int1,\n\t\tInt2: int2,\n\t\tLimit: limit,\n\t\tStr1: parameters[\"str1\"],\n\t\tStr2: parameters[\"str2\"],\n\t}, nil\n}", "func CreateActionDiskRmaRequest() (request *ActionDiskRmaRequest) {\n\trequest = &ActionDiskRmaRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"TeslaDam\", \"2018-01-18\", \"ActionDiskRma\", \"tesladam\", \"openAPI\")\n\treturn\n}", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func NewFileSystem(fs http.FileSystem, name string) FileSystem {\n\treturn Trace(&fileSystem{fs}, name)\n}", "func (c *Client) NewCreateLabelRequest(ctx context.Context, path string, payload *CreateLabelPayload) (*http.Request, error) {\n\tvar body bytes.Buffer\n\terr := c.Encoder.Encode(payload, &body, \"*/*\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\tif c.JWTSigner != nil {\n\t\tc.JWTSigner.Sign(req)\n\t}\n\treturn req, nil\n}", "func CreateNormalRpcHsfApiRequest() (request *NormalRpcHsfApiRequest) {\n\trequest = &NormalRpcHsfApiRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ft\", \"2021-01-01\", \"NormalRpcHsfApi\", \"\", \"\")\n\trequest.Method = requests.GET\n\treturn\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func (client *SparkJobDefinitionClient) executeSparkJobDefinitionCreateRequest(ctx context.Context, sparkJobDefinitionName string, options *SparkJobDefinitionBeginExecuteSparkJobDefinitionOptions) (*azcore.Request, error) {\n\turlPath := \"/sparkJobDefinitions/{sparkJobDefinitionName}/execute\"\n\tif sparkJobDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter sparkJobDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sparkJobDefinitionName}\", url.PathEscape(sparkJobDefinitionName))\n\treq, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\treqQP := req.URL.Query()\n\treqQP.Set(\"api-version\", \"2019-06-01-preview\")\n\treq.URL.RawQuery = reqQP.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (g Graph) CreateDrive(w http.ResponseWriter, r *http.Request) {\n\tus, ok := ctxpkg.ContextGetUser(r.Context())\n\tif !ok {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"invalid user\")\n\t\treturn\n\t}\n\n\t// TODO determine if the user tries to create his own personal space and pass that as a boolean\n\tif !canCreateSpace(r.Context(), false) {\n\t\t// if the permission is not existing for the user in context we can assume we don't have it. Return 401.\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"insufficient permissions to create a space.\")\n\t\treturn\n\t}\n\n\tclient := g.GetGatewayClient()\n\tdrive := libregraph.Drive{}\n\tif err := json.NewDecoder(r.Body).Decode(&drive); err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, \"invalid schema definition\")\n\t\treturn\n\t}\n\tspaceName := *drive.Name\n\tif spaceName == \"\" {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"invalid name\")\n\t\treturn\n\t}\n\n\tvar driveType string\n\tif drive.DriveType != nil {\n\t\tdriveType = *drive.DriveType\n\t}\n\tswitch driveType {\n\tcase \"\", \"project\":\n\t\tdriveType = \"project\"\n\tdefault:\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, fmt.Sprintf(\"drives of type %s cannot be created via this api\", driveType))\n\t\treturn\n\t}\n\n\tcsr := storageprovider.CreateStorageSpaceRequest{\n\t\tOwner: us,\n\t\tType: driveType,\n\t\tName: spaceName,\n\t\tQuota: getQuota(drive.Quota, g.config.Spaces.DefaultQuota),\n\t}\n\n\tif drive.Description != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"description\", *drive.Description)\n\t}\n\n\tif drive.DriveAlias != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"spaceAlias\", *drive.DriveAlias)\n\t}\n\n\tresp, err := client.CreateStorageSpace(r.Context(), &csr)\n\tif err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tif resp.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tnewDrive, err := g.cs3StorageSpaceToDrive(r.Context(), wdu, resp.StorageSpace)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing space\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trender.Status(r, http.StatusCreated)\n\trender.JSON(w, r, newDrive)\n}", "func (c *Client) BuildStorageVolumesCreateRequest(ctx context.Context, v interface{}) (*http.Request, error) {\n\tu := &url.URL{Scheme: c.scheme, Host: c.host, Path: StorageVolumesCreateSpinRegistryPath()}\n\treq, err := http.NewRequest(\"POST\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, goahttp.ErrInvalidURL(\"spin-registry\", \"storage_volumes_create\", u.String(), err)\n\t}\n\tif ctx != nil {\n\t\treq = req.WithContext(ctx)\n\t}\n\n\treturn req, nil\n}", "func (c *Client) NewCreateScansRequest(ctx context.Context, path string, payload *ScanPayload) (*http.Request, error) {\n\tvar body bytes.Buffer\n\terr := c.Encoder.Encode(payload, &body, \"*/*\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\treturn req, nil\n}", "func (client *ContainerClient) ListBlobHierarchySegmentCreateRequest(ctx context.Context, delimiter string, options *ContainerClientListBlobHierarchySegmentOptions) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"restype\", \"container\")\n\treqQP.Set(\"comp\", \"list\")\n\tif options != nil && options.Prefix != nil {\n\t\treqQP.Set(\"prefix\", *options.Prefix)\n\t}\n\treqQP.Set(\"delimiter\", delimiter)\n\tif options != nil && options.Marker != nil {\n\t\treqQP.Set(\"marker\", *options.Marker)\n\t}\n\tif options != nil && options.Maxresults != nil {\n\t\treqQP.Set(\"maxresults\", strconv.FormatInt(int64(*options.Maxresults), 10))\n\t}\n\tif options != nil && options.Include != nil {\n\t\treqQP.Set(\"include\", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(options.Include), \"[]\")), \",\"))\n\t}\n\tif options != nil && options.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*options.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"x-ms-version\"] = []string{\"2020-10-02\"}\n\tif options != nil && options.RequestID != nil {\n\t\treq.Raw().Header[\"x-ms-client-request-id\"] = []string{*options.RequestID}\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/xml\"}\n\treturn req, nil\n}", "func NewCreateDNSZoneRequest(server string, body CreateDNSZoneJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateDNSZoneRequestWithBody(server, \"application/json\", bodyReader)\n}", "func CreateUploadIoTDataToBlockchainRequest() (request *UploadIoTDataToBlockchainRequest) {\n\trequest = &UploadIoTDataToBlockchainRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"lto\", \"2021-07-07\", \"UploadIoTDataToBlockchain\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateEvaluateTaskRequest() (request *CreateEvaluateTaskRequest) {\n\trequest = &CreateEvaluateTaskRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Drds\", \"2019-01-23\", \"CreateEvaluateTask\", \"Drds\", \"openAPI\")\n\treturn\n}", "func (c *Client) NewCreateLambdaRequest(ctx context.Context, path string, payload *LambdaPayload, contentType string) (*http.Request, error) {\n\tvar body bytes.Buffer\n\tif contentType == \"\" {\n\t\tcontentType = \"*/*\" // Use default encoder\n\t}\n\terr := c.Encoder.Encode(payload, &body, contentType)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\tif contentType == \"*/*\" {\n\t\theader.Set(\"Content-Type\", \"application/json\")\n\t} else {\n\t\theader.Set(\"Content-Type\", contentType)\n\t}\n\treturn req, nil\n}", "func CreateDescribeExplorerRequest() (request *DescribeExplorerRequest) {\n\trequest = &DescribeExplorerRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Baas\", \"2018-07-31\", \"DescribeExplorer\", \"\", \"\")\n\treturn\n}", "func NewFileSystem(ctrl *gomock.Controller) *FileSystem {\n\tmock := &FileSystem{ctrl: ctrl}\n\tmock.recorder = &FileSystemMockRecorder{mock}\n\treturn mock\n}", "func CreateCreateDataAPIServiceRequest() (request *CreateDataAPIServiceRequest) {\n\trequest = &CreateDataAPIServiceRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Iot\", \"2018-01-20\", \"CreateDataAPIService\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func NewCreateSksClusterRequest(server string, body CreateSksClusterJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateSksClusterRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func newMkdirRequest(name string) *Request {\n\treturn &Request{Type: requestMkdir, Path: name}\n}", "func CreateCreateContainerInstancesRequest() (request *CreateContainerInstancesRequest) {\n\trequest = &CreateContainerInstancesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ecs\", \"2014-05-26\", \"CreateContainerInstances\", \"ecs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (c *Client) NewCreateUserRequest(ctx context.Context, path string, payload *CreateUserPayload, contentType string) (*http.Request, error) {\n\tvar body bytes.Buffer\n\tif contentType == \"\" {\n\t\tcontentType = \"*/*\" // Use default encoder\n\t}\n\terr := c.Encoder.Encode(payload, &body, contentType)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\tif contentType == \"*/*\" {\n\t\theader.Set(\"Content-Type\", \"application/json\")\n\t} else {\n\t\theader.Set(\"Content-Type\", contentType)\n\t}\n\treturn req, nil\n}", "func CreateDescribeFpgaImagesRequest() (request *DescribeFpgaImagesRequest) {\n\trequest = &DescribeFpgaImagesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"faas\", \"2020-02-17\", \"DescribeFpgaImages\", \"faas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *CloudServicesClient) startCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginStartOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/start\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif cloudServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter cloudServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{cloudServiceName}\", url.PathEscape(cloudServiceName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-09-04\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (store *Engine) CreateRequest(request *Request) (string, error) {\n\tvar id struct {\n\t\tID string `json:\"id\"`\n\t}\n\n\t_, err := store.api.\n\t\tURL(\"/workflow-engine/api/v1/requests\").\n\t\tPost(&request, &id)\n\n\treturn id.ID, err\n}", "func NewCreateanewSoundFileRequest(server string, body CreateanewSoundFileJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewSoundFileRequestWithBody(server, \"application/json\", bodyReader)\n}" ]
[ "0.74044955", "0.7277164", "0.7208954", "0.7005334", "0.6775199", "0.67420554", "0.66735137", "0.662397", "0.6544891", "0.63551843", "0.6137757", "0.605717", "0.59149057", "0.5900351", "0.58727604", "0.57616615", "0.57495767", "0.5742306", "0.573904", "0.57332695", "0.5698775", "0.56630176", "0.56537527", "0.5620307", "0.55950856", "0.55882853", "0.55834025", "0.55513746", "0.5546973", "0.55397207", "0.55282634", "0.5514236", "0.5502149", "0.5499126", "0.5494996", "0.5479951", "0.5461243", "0.54531705", "0.5445831", "0.5442856", "0.54374444", "0.5433586", "0.54317313", "0.5426106", "0.54243225", "0.5420428", "0.5418315", "0.5406106", "0.53952247", "0.53826046", "0.5382112", "0.53784746", "0.5375143", "0.53695434", "0.53506595", "0.53495955", "0.5342001", "0.53415763", "0.5341148", "0.5339594", "0.5338037", "0.5320624", "0.5303603", "0.52918744", "0.528945", "0.5286966", "0.52761173", "0.52728903", "0.527197", "0.52678263", "0.5255856", "0.5225574", "0.5224698", "0.52106935", "0.5206156", "0.52008516", "0.51979434", "0.51975197", "0.51938534", "0.518828", "0.5182749", "0.5172974", "0.5171404", "0.5156043", "0.5154647", "0.5154103", "0.5153118", "0.5146945", "0.51424366", "0.5141831", "0.51413965", "0.51412755", "0.5130506", "0.5128824", "0.51250714", "0.5122296", "0.51214105", "0.51170045", "0.511427", "0.51112175" ]
0.8567599
0
CreateCreateFileSystemResponse creates a response to parse from CreateFileSystem response
CreateCreateFileSystemResponse создает ответ для парсинга из ответа CreateFileSystem
func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) { response = &CreateFileSystemResponse{ BaseResponse: &responses.BaseResponse{}, } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func CreateListFileSystemsResponse() (response *ListFileSystemsResponse) {\n\tresponse = &ListFileSystemsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateFileDetectResponse() (response *CreateFileDetectResponse) {\n\tresponse = &CreateFileDetectResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateRenameDbfsResponse() (response *RenameDbfsResponse) {\n\tresponse = &RenameDbfsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateListAvailableFileSystemTypesResponse() (response *ListAvailableFileSystemTypesResponse) {\n\tresponse = &ListAvailableFileSystemTypesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func CreateCreateGatewayFileShareResponse() (response *CreateGatewayFileShareResponse) {\n\tresponse = &CreateGatewayFileShareResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateFile(w http.ResponseWriter, r *http.Request) {\n\tvar body datastructures.CreateBody\n\n\tif reqBody, err := ioutil.ReadAll(r.Body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Could not read request body\"))\n\t\treturn\n\t} else if err = json.Unmarshal(reqBody, &body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"Bad request\"))\n\t\treturn\n\t}\n\n\tlog.Println(\n\t\t\"Create file request for\",\n\t\t\"workspace\", body.Workspace.ToString(),\n\t\t\"path\", filepath.Join(body.File.Path...),\n\t)\n\n\tif err := utils.CreateFile(body.Workspace, body.File); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func CreateGetDirectoryOrFilePropertiesResponse() (response *GetDirectoryOrFilePropertiesResponse) {\n\tresponse = &GetDirectoryOrFilePropertiesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFaceConfigResponse() (response *CreateFaceConfigResponse) {\n\tresponse = &CreateFaceConfigResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateModifyDirectoryResponse() (response *ModifyDirectoryResponse) {\n\tresponse = &ModifyDirectoryResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateClusterResponse() (response *CreateClusterResponse) {\n\tresponse = &CreateClusterResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func NewQtreeCreateResponse() *QtreeCreateResponse {\n\treturn &QtreeCreateResponse{}\n}", "func CreateUploadIoTDataToBlockchainResponse() (response *UploadIoTDataToBlockchainResponse) {\n\tresponse = &UploadIoTDataToBlockchainResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (a *FileStorageApiService) CreateDirectoryExecute(r ApiCreateDirectoryRequest) (SingleNode, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SingleNode\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.Ctx, \"FileStorageApiService.CreateDirectory\")\n\tif localBasePath == \"/\" {\n\t localBasePath = \"\"\n\t}\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v2/file_storage/buckets/{bucket_id}/create_directory\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucket_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_bucketId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.P_nodeRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"nodeRequest is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\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\t// body params\n\tlocalVarPostBody = r.P_nodeRequest\n\treq, err := a.client.prepareRequest(r.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(req)\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 CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateVSwitchResponse() (response *CreateVSwitchResponse) {\n\tresponse = &CreateVSwitchResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (cfr CreateFilesystemResponse) Response() *http.Response {\n\treturn cfr.rawResponse\n}", "func (f FileURL) Create(ctx context.Context, size int64, h FileHTTPHeaders, metadata Metadata) (*FileCreateResponse, error) {\n\tpermStr, permKey, fileAttr, fileCreateTime, FileLastWriteTime, err := h.selectSMBPropertyValues(false, defaultPermissionString, defaultFileAttributes, defaultCurrentTimeString)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.fileClient.Create(ctx, size, fileAttr, fileCreateTime, FileLastWriteTime, nil,\n\t\t&h.ContentType, &h.ContentEncoding, &h.ContentLanguage, &h.CacheControl,\n\t\th.ContentMD5, &h.ContentDisposition, metadata, permStr, permKey)\n}", "func CreateCreatedResponse(w http.ResponseWriter, data interface{}) {\n\tif data != nil {\n\t\tbytes, err := json.Marshal(data)\n\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tw.Write(bytes)\n\t}\n}", "func CreateActionDiskRmaResponse() (response *ActionDiskRmaResponse) {\n\tresponse = &ActionDiskRmaResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func CreateDescribeGatewayFileSharesResponse() (response *DescribeGatewayFileSharesResponse) {\n\tresponse = &DescribeGatewayFileSharesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateNormalRpcHsfApiResponse() (response *NormalRpcHsfApiResponse) {\n\tresponse = &NormalRpcHsfApiResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func CreateCreateStackResponse() (response *CreateStackResponse) {\n\tresponse = &CreateStackResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (z *ZFS) Create(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CreateArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif args.Name == \"\" {\n\t\treturn nil, nil, errors.New(\"missing arg: name\")\n\t}\n\n\tif err := fixPropertyTypesFromJSON(args.Properties); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar ds *gozfs.Dataset\n\tvar err error\n\tswitch args.Type {\n\tcase gozfs.DatasetFilesystem:\n\t\tds, err = gozfs.CreateFilesystem(args.Name, args.Properties)\n\tcase gozfs.DatasetVolume:\n\t\tif args.Volsize <= 0 {\n\t\t\terr = errors.New(\"missing or invalid arg: volsize\")\n\t\t\tbreak\n\t\t}\n\t\tds, err = gozfs.CreateVolume(args.Name, args.Volsize, args.Properties)\n\tdefault:\n\t\terr = errors.New(\"missing or invalid arg: type\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &DatasetResult{newDataset(ds)}, nil, nil\n}", "func CreateCreateExpressSyncResponse() (response *CreateExpressSyncResponse) {\n\tresponse = &CreateExpressSyncResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func CreateCreateExchangeResponse() (response *CreateExchangeResponse) {\n\tresponse = &CreateExchangeResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_api_proto_rawDescGZIP(), []int{2}\n}", "func CreateDescribeExplorerResponse() (response *DescribeExplorerResponse) {\n\tresponse = &DescribeExplorerResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFaceGroupResponse() (response *CreateFaceGroupResponse) {\n\tresponse = &CreateFaceGroupResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func CreateMetastoreCreateTableResponse() (response *MetastoreCreateTableResponse) {\n\tresponse = &MetastoreCreateTableResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func CreateCreateTagTaskResponse() (response *CreateTagTaskResponse) {\n\tresponse = &CreateTagTaskResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateVmAndSaveStockResponse() (response *CreateVmAndSaveStockResponse) {\n\tresponse = &CreateVmAndSaveStockResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFabricChannelResponse() (response *CreateFabricChannelResponse) {\n\tresponse = &CreateFabricChannelResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateTrafficMirrorFilterResponse() (response *CreateTrafficMirrorFilterResponse) {\n\tresponse = &CreateTrafficMirrorFilterResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDescribeLogstoreStorageResponse() (response *DescribeLogstoreStorageResponse) {\n\tresponse = &DescribeLogstoreStorageResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateResponse() *application.HTTPResponse {\n\tresponse := &application.HTTPResponse{}\n\tresponse.Headers = make(map[string]*application.HTTPResponse_HTTPHeaderParameter)\n\treturn response\n}", "func CreateCreateFileDetectRequest() (request *CreateFileDetectRequest) {\n\trequest = &CreateFileDetectRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Sas\", \"2018-12-03\", \"CreateFileDetect\", \"sas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateTopicResponse() (response *CreateTopicResponse) {\n\tresponse = &CreateTopicResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func Create(name string) (*os.File, error)", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func CreateDescribeImportOASTaskResponse() (response *DescribeImportOASTaskResponse) {\n\tresponse = &DescribeImportOASTaskResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateResponse(resultCode uint32, internalCommand []byte) ([]byte, error) {\n\t// Response frame:\n\t// - uint32 (size of response)\n\t// - []byte (response)\n\t// - uint32 (code)\n\tvar buf bytes.Buffer\n\n\tif err := binary.Write(&buf, binary.BigEndian, uint32(len(internalCommand))); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := buf.Write(internalCommand); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := binary.Write(&buf, binary.BigEndian, resultCode); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func CreateResponse(w *gin.Context, payload interface{}) {\n\tw.JSON(200, payload)\n}", "func CreateCreateDataAPIServiceResponse() (response *CreateDataAPIServiceResponse) {\n\tresponse = &CreateDataAPIServiceResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDescribeServiceMeshesResponse() (response *DescribeServiceMeshesResponse) {\n\tresponse = &DescribeServiceMeshesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*MkDirResponse) Descriptor() ([]byte, []int) {\n\treturn file_IOService_proto_rawDescGZIP(), []int{3}\n}", "func CreateDescribeParentPlatformResponse() (response *DescribeParentPlatformResponse) {\n\tresponse = &DescribeParentPlatformResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (o *CreateFoldersCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(201)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_task_v1_task_proto_rawDescGZIP(), []int{2}\n}", "func (c *WSCodec) CreateResponse(id interface{}, reply interface{}) interface{} {\n\treturn &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}\n}", "func (client BaseClient) CreateSystemResponder(resp *http.Response) (result System, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func CreateCreateScheduleResponse() (response *CreateScheduleResponse) {\n\tresponse = &CreateScheduleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createResponse(req *http.Request) *http.Response {\n\treturn &http.Response{\n\t\tStatusCode: http.StatusOK,\n\t\tRequest: req,\n\t\tHeader: make(http.Header),\n\t\tBody: ioutil.NopCloser(bytes.NewBuffer([]byte{})),\n\t}\n}", "func (*CreateNodeResponse) Descriptor() ([]byte, []int) {\n\treturn file_service_node_proto_rawDescGZIP(), []int{1}\n}", "func CreateUploadFileByURLResponse() (response *UploadFileByURLResponse) {\n\tresponse = &UploadFileByURLResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (d *VolumeDriver) Create(r volume.Request) volume.Response {\n\tlog.Errorf(\"VolumeDriver Create to be implemented\")\n\treturn volume.Response{Err: \"\"}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_account_proto_rawDescGZIP(), []int{1}\n}", "func (fs *dsFileSys) Create(name string) (fsi.File, error) {\n\n\t// WriteFile & Create\n\tdir, bname := fs.SplitX(name)\n\n\tf := DsFile{}\n\tf.fSys = fs\n\tf.BName = common.Filify(bname)\n\tf.Dir = dir\n\tf.MModTime = time.Now()\n\tf.MMode = 0644\n\n\t// let all the properties by set by fs.saveFileByPath\n\terr := f.Sync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return &f, nil\n\tff := fsi.File(&f)\n\treturn ff, err\n\n}", "func create() (*os.File, error) {\n\tbaseURL, err := url.Parse(*root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.Create(baseURL.Host + \".xml\")\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func CreateFile(buf []byte) (File, error) {\n\tfileFormat, dataType, err := getFileInformation(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf, err := NewFile(*fileFormat)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif *dataType == JsonData {\n\t\terr = json.Unmarshal(buf, f)\n\t} else {\n\t\terr = f.Parse(string(buf))\n\t}\n\treturn f, err\n}", "func (s *Systemd) Create(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CreateArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif args.Name == \"\" {\n\t\treturn nil, nil, errors.New(\"missing arg: name\")\n\t}\n\n\tunitFilePath, err := s.config.UnitFilePath(args.Name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif _, err = os.Stat(unitFilePath); err == nil {\n\t\treturn nil, nil, errors.New(\"unit file already exists\")\n\t}\n\n\tunitFileContents, err := ioutil.ReadAll(unit.Serialize(args.UnitOptions))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// TODO: Sort out file permissions\n\treturn nil, nil, ioutil.WriteFile(unitFilePath, unitFileContents, os.ModePerm)\n}", "func CreateGetServiceInputMappingResponse() (response *GetServiceInputMappingResponse) {\n\tresponse = &GetServiceInputMappingResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateResponse(result interface{}, err error) *Response {\n\tif err == nil {\n\t\treturn CreateSuccessResponse(result)\n\t}\n\treturn CreateErrorResponse(err)\n}", "func (e *FileExistsError) ConstructResponse() string {\n\tresponse := \"already_\"\n\tif e.state == Published {\n\t\tresponse += \"published\"\n\t} else {\n\t\tresponse += \"uploaded\"\n\t}\n\tif e.userIsOwner {\n\t\tresponse += \"_self\"\n\t}\n\treturn response\n}", "func CreateDeleteServiceTimeConfigResponse() (response *DeleteServiceTimeConfigResponse) {\n\tresponse = &DeleteServiceTimeConfigResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_todo_proto_rawDescGZIP(), []int{2}\n}", "func CreateCreateAgentResponse() (response *CreateAgentResponse) {\n\tresponse = &CreateAgentResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createJSONFile (outputDir string, fileName string) *os.File {\n\n file, err := os.Create(filepath.Join(outputDir, fileName+jsonExt)) \n check(err) \n\n return file\n}", "func CreateUpdateMediaStorageClassResponse() (response *UpdateMediaStorageClassResponse) {\n\tresponse = &UpdateMediaStorageClassResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateListAvailableFileSystemTypesRequest() (request *ListAvailableFileSystemTypesRequest) {\n\trequest = &ListAvailableFileSystemTypesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EHPC\", \"2018-04-12\", \"ListAvailableFileSystemTypes\", \"ehs\", \"openAPI\")\n\treturn\n}", "func MakeCreateEndpoint(s service.FilesCreatorService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(CreateRequest)\n\t\ts0 := s.Create(ctx, req.FileDescriptor)\n\t\treturn CreateResponse{S0: s0}, nil\n\t}\n}", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func CreateCreateETLJobResponse() (response *CreateETLJobResponse) {\n\tresponse = &CreateETLJobResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateMeetingResponse() (response *CreateMeetingResponse) {\n\tresponse = &CreateMeetingResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (dcr DirectoryCreateResponse) Response() *http.Response {\n\treturn PathCreateResponse(dcr).Response()\n}", "func CreateDropPartitionResponse() (response *DropPartitionResponse) {\n\tresponse = &DropPartitionResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateSegmentSkyResponse() (response *SegmentSkyResponse) {\n\tresponse = &SegmentSkyResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}" ]
[ "0.7409187", "0.7196471", "0.7153243", "0.68064606", "0.67132664", "0.66525936", "0.65382826", "0.6406937", "0.6363215", "0.6359061", "0.6322241", "0.6244479", "0.61652124", "0.61642545", "0.61275655", "0.6105425", "0.5946818", "0.5941657", "0.5848543", "0.5826824", "0.577976", "0.57733905", "0.5758492", "0.5747923", "0.5744731", "0.57396835", "0.5689065", "0.5681631", "0.5680091", "0.56444407", "0.563234", "0.56201255", "0.5608951", "0.56014705", "0.5592805", "0.5585474", "0.5582265", "0.5581949", "0.55807084", "0.55626774", "0.5546555", "0.55463594", "0.5546118", "0.5535951", "0.5530715", "0.55220884", "0.551553", "0.55060273", "0.5500247", "0.5495028", "0.54948586", "0.54770744", "0.54632044", "0.54516846", "0.54378635", "0.53995013", "0.53981733", "0.5388875", "0.5382732", "0.5371733", "0.53707623", "0.5369803", "0.5367772", "0.5366723", "0.535142", "0.5351372", "0.5333564", "0.5331378", "0.5327585", "0.53202814", "0.5311656", "0.5311418", "0.53090256", "0.52991235", "0.5297834", "0.52957904", "0.5293028", "0.52919465", "0.52918726", "0.5288642", "0.528266", "0.528248", "0.52755314", "0.5274467", "0.5273221", "0.5272936", "0.5263046", "0.5259504", "0.5258404", "0.52569115", "0.5256101", "0.5248763", "0.5244914", "0.5240597", "0.5235423", "0.5224955", "0.52202874", "0.5220245", "0.52052367", "0.51974773" ]
0.8397854
0
SaveBody creates or overwrites the existing response body file for the url associated with the given Fetcher
SaveBody создает или перезаписывает существующий файл тела ответа для URL, связанного с заданным Fetcher
func (f Fetcher) SaveBody() { file, err := os.Create(f.url) check(err) defer file.Close() b := f.processBody() _, err = file.Write(b) check(err) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Response) Save(fileName string) error {\r\n\treturn ioutil.WriteFile(fileName, r.Body, 0644)\r\n}", "func (response *S3Response) WriteBody(dst io.Writer) error {\n defer response.Close()\n _, err := io.Copy(dst, response.httpResponse.Body)\n return err\n}", "func saveFile(savedPath string, res *http.Response) {\n\t// create a file of the given name and in the given path\n\tf, err := os.Create(savedPath)\n\terrCheck(err)\n\tio.Copy(f, res.Body)\n}", "func (resp *Response) SaveFile(filename string, perm os.FileMode) (err error) {\n\tvar file *os.File\n\tfile, err = os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)\n\tif err == nil {\n\t\tdefer file.Close()\n\t\terr = drainBody(resp.Body, file)\n\t}\n\treturn\n}", "func (p *Page) save() error {\n filename := p.Title + \".txt\"\n return ioutil.WriteFile(filename, p.Body, 0600)\n}", "func (p *para) saveFile(res *http.Response) error {\n\tvar err error\n\tp.ContentType = res.Header[\"Content-Type\"][0]\n\terr = p.getFilename(res)\n\tif err = p.getFilename(res); err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.Create(filepath.Join(p.WorkDir, p.Filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(file, res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileInfo, err := file.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"{\\\"Filename\\\": \\\"%s\\\", \\\"Type\\\": \\\"%s\\\", \\\"MimeType\\\": \\\"%s\\\", \\\"FileSize\\\": %d}\\n\", p.Filename, p.Kind, p.ContentType, fileInfo.Size())\n\tdefer func() {\n\t\tfile.Close()\n\t\tres.Body.Close()\n\t}()\n\treturn nil\n}", "func api_save_cert_of_need(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"api_save_cert_of_need\", r.URL.Scheme, \"method=\", r.Method)\n\tfmt.Println(\"URL=\", r.URL)\n\tvar urstr = r.URL.RequestURI()\n\tid := strings.Replace(urstr, \"/api/save-cert-of-need/\", \"\", 1)\n\tfmt.Println(\"id =\", id)\n\tid = strings.SplitN(id, \"?\", 2)[0]\n\tid = strings.Replace(id, \"\\\\\", \"-\", -1)\n\tid = strings.Replace(id, \"/\", \"-\", -1)\n\tid = strings.Replace(id, \" \", \"-\", -1)\n\tid = strings.Replace(id, \":\", \"-\", -1)\n\tfmt.Println(\"id=\", id)\n\tif len(id) < 2 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"id is mandatory as last segment of URI\")\n\t\treturn\n\t}\n\t// Read the body string.\n\tfmt.Println(\"contentLength=\", r.ContentLength)\n\tbodya := make([]byte, r.ContentLength)\n\t_, err := r.Body.Read(bodya)\n\n\toutFiName := \"data/cert-of-need/\" + id + \".JSON\"\n\terr = ioutil.WriteFile(outFiName, bodya, 0644)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"err saving file \", err)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"{'status' : 'sucess'}\")\n\n\tbodys := string(bodya)\n\tfmt.Println(\"bodys=\", bodys)\n}", "func DownloadFile(filepath string, url string) error {\n\n // Get the data\n resp, err := http.Get(url)\n if err != nil {\n //return err\n fmt.Println(\"Get the data\")\n }\n defer resp.Body.Close()\n\n // Create the file\n out, err := os.Create(filepath)\n if err != nil {\n fmt.Println(\"Create the file\")\n }\n defer out.Close()\n\n // Write the body to file\n _, err = io.Copy(out, resp.Body)\n return err\n}", "func (s *Saver) SaveResponse(resp *http.Response) error {\n\trespName, err := GetResponseFilename(s.reqName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(filepath.Join(s.dir, respName))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer handleClose(&err, f)\n\n\treturn resp.Write(f)\n}", "func (p *Page) save() error {\n\tfilename := \"data/\" + p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}", "func writeBody(fileName, line string) (string, error) {\n\t//make the temp directory if not exist\n\tdir, err := ioutil.TempDir(\"\", APP_SHORT_NAME)\n\tif err != nil {\n\t\treturn fileName, err\n\t}\n\t//write the file inside the HOME/directory\n\ttempGoFile := filepath.Join(dir, fileName) + EXT\n\treturn tempGoFile, ioutil.WriteFile(tempGoFile, []byte(line), 0644)\n}", "func (s *Scraper) storeDownload(u *url.URL, buf *bytes.Buffer, fileExtension string) {\n\tisAPage := false\n\tif fileExtension == \"\" {\n\t\thtml, fixed, err := s.fixURLReferences(u, buf)\n\t\tif err != nil {\n\t\t\ts.logger.Error(\"Fixing file references failed\",\n\t\t\t\tlog.Stringer(\"url\", u),\n\t\t\t\tlog.Err(err))\n\t\t\treturn\n\t\t}\n\n\t\tif fixed {\n\t\t\tbuf = bytes.NewBufferString(html)\n\t\t}\n\t\tisAPage = true\n\t}\n\n\tfilePath := s.GetFilePath(u, isAPage)\n\t// always update html files, content might have changed\n\tif err := s.writeFile(filePath, buf); err != nil {\n\t\ts.logger.Error(\"Writing to file failed\",\n\t\t\tlog.Stringer(\"URL\", u),\n\t\t\tlog.String(\"file\", filePath),\n\t\t\tlog.Err(err))\n\t}\n}", "func SaveFileByFileInfo(fileInfo resource.IResource, resp *http.Response) resource.IResource {\n\tMakeDirAll(fileInfo.GetSaveParentPath())\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tfmt.Println(\"push body read error is \", err)\n\t\treturn nil\n\t}\n\tdataSize := len(body)\n\terr = ioutil.WriteFile(fileInfo.GetSavePath(), body, 0644)\n\tif err != nil {\n\t\tfmt.Println(\"push body write error is \", err)\n\t\treturn nil\n\t}\n\tfileInfo.SetDataSize(dataSize)\n\treturn fileInfo\n}", "func (r *Recipe) Save(fname string) (err error) {\n\tb, err := json.MarshalIndent(r, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(fname, b, 0644)\n\treturn\n}", "func (p *Page) save() error {\r\n\tfilename := p.Title + \".txt\"\r\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\r\n}", "func (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}", "func fetchWriteCache(url string, body *string) <-chan struct{} {\n\tIOComplete := make(chan struct{})\n\tgo func() {\n\t\tfetchCache.WriteString(\"\", Id(NormalizeURL(url)), body, false)\n\t\tclose(IOComplete)\n\t}()\n\treturn IOComplete\n}", "func DownloadFile(saveto string, extension string, url string, maxMegabytes uint64) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tfilename := saveto + \"/\" + FilenameFromURL(url)\n\t// Create the file\n\tvar out *os.File\n\tif _, err := os.Stat(filename); err == nil {\n\t\tout, err = os.Create(filename + randString(10) + \".\" + extension)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tout, err = os.Create(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t//_, err = io.Copy(out, resp.Body)\n\tmegabytes := int64(maxMegabytes * 1024000)\n\t_, err = io.CopyN(out, resp.Body, megabytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (f *fetcher) Save(data []byte) {\n\t// Implementation can be application dependent\n\t// eg. you may implement connect to a redis server here\n\tfmt.Println(string(data))\n}", "func (f Fetcher) processBody() []byte {\n\tb, err := io.ReadAll(f.resp.Body)\n\tf.resp.Body.Close()\n\tif f.resp.StatusCode >= 300 {\n\t\tlog.Fatalf(\"Response failed with status code: %d\\n and body: %s\\n\", f.resp.StatusCode, b)\n\t}\n\tcheck(err)\n\treturn b\n}", "func saveHandler(w http.ResponseWriter, r *http.Request) {\r\n title := r.URL.Path[len(\"/save/\"):]\r\n body := r.FormValue(\"body\")\r\n p := &Page{Title: title, Body: []byte(body)}\r\n p.save()\r\n http.Redirect(w, r, \"/view/\"+title, http.StatusFound)\r\n}", "func PostHandler(basePath string, w http.ResponseWriter, r *http.Request) {\n\tname := fileKey(r.URL)\n\tf := NewFile(name, r.Header.Get(\"Content-Type\"))\n\n\tFilesLock.Lock()\n\tFiles.Add(name, f)\n\tFilesLock.Unlock()\n\n\t// Start writing to file without holding lock so that GET requests can read from it\n\tio.Copy(f, r.Body)\n\tr.Body.Close()\n\tf.Close()\n\n\terr := f.WriteToDisk(basePath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error saving to disk: %v\", err)\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\t// 0600 = r-w permissions for current user only\n}", "func (page *Page) save() error {\n\tfilename := page.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, page.Body, 0600)\n}", "func Save(r *http.Request, w http.ResponseWriter) error {\n\n}", "func DownloadToFile(outputFilePath, defaultFileName string, body []byte, extension string, permissions os.FileMode, overwrite bool) string {\n\tmsgPrinter := i18n.GetMessagePrinter()\n\tvar fileName string\n\t// if no fileName and filePath specified, data will be saved in current dir, with name {defaultFileName}\n\tif outputFilePath == \"\" {\n\t\tfileName = defaultFileName\n\t} else {\n\t\t// trim the ending \"/\" if there are more than 1 \"/\"\n\t\tfor strings.HasSuffix(outputFilePath, \"//\") {\n\t\t\toutputFilePath = strings.TrimSuffix(outputFilePath, \"/\")\n\t\t}\n\n\t\tfi, _ := os.Stat(outputFilePath)\n\t\tif fi == nil {\n\t\t\t// outputFilePath is not an existing dir, then consider it as fileName, need to remove \"/\" in the end\n\t\t\tif strings.HasSuffix(outputFilePath, \"/\") {\n\t\t\t\toutputFilePath = strings.TrimSuffix(outputFilePath, \"/\")\n\t\t\t}\n\t\t\tfileName = outputFilePath\n\t\t} else {\n\t\t\tif fi.IsDir() {\n\t\t\t\tif !strings.HasSuffix(outputFilePath, \"/\") {\n\t\t\t\t\toutputFilePath = outputFilePath + \"/\"\n\t\t\t\t}\n\t\t\t\tfileName = fmt.Sprintf(\"%s%s\", outputFilePath, defaultFileName)\n\t\t\t} else {\n\t\t\t\tfileName = outputFilePath\n\t\t\t}\n\t\t}\n\t}\n\tif fileName[len(fileName)-len(extension):] != extension {\n\t\tfileName += extension\n\t}\n\n\tif !overwrite {\n\t\tif _, err := os.Stat(fileName); !os.IsNotExist(err) {\n\t\t\tFatal(CLI_INPUT_ERROR, msgPrinter.Sprintf(\"File %s already exists. Please specify a different file path or file name. To overwrite the existing file, use the '--overwrite' flag.\", fileName))\n\t\t}\n\t}\n\n\t// add newline to end of file\n\tbodyString := string(body)\n\tif bodyString[len(bodyString)-1] != '\\n' {\n\t\tbodyString += \"\\n\"\n\t}\n\tbody = []byte(bodyString)\n\n\tif err := ioutil.WriteFile(fileName, body, permissions); err != nil {\n\t\tFatal(INTERNAL_ERROR, msgPrinter.Sprintf(\"Failed to save data for object '%s' to file %s, err: %v\", defaultFileName, fileName, err))\n\t}\n\n\treturn fileName\n}", "func savePage(url url.URL, body []byte) bool{\n\t// TODO: Take save location as a CMD line flag\n\trootDir := \"/tmp/scraper\"\n\n\tdirPath := rootDir + \"/\" + url.Host + url.Path\n\n\terr := os.MkdirAll(dirPath, 0777)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot create directory %s. \\nError: %s\", dirPath, err)\n\t\treturn false\n\t}\n\n\tfilePath := dirPath + \"/index.html\"\n\n\terr = ioutil.WriteFile(filePath, body, 0777)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot write to file=%s. \\nError: %s\", filePath, err)\n\t\treturn false\n\t}\n\treturn true\n}", "func saveHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle, err := getTitle(w, r)\n\tif err != nil {\n\t\treturn\n\t}\n\tbody := r.FormValue(\"body\")\t// Get the page content. It is of type string - we must convert it to []byte before it will fit into the Page struct.ß\n\tp := &Page{Title: title, Body: []byte(body)}\n\terr = p.save()\t// Write the data to a file\n\t// An error that occurs during p.save() will be reported to the user\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}", "func SaveTo(ctx *log.Context, d []Downloader, dst string, mode os.FileMode) (int64, error) {\n\tf, err := os.OpenFile(dst, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, mode)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"failed to open file for writing\")\n\t}\n\tdefer f.Close()\n\n\tn, err := WithRetries(ctx, f, d, ActualSleep)\n\tif err != nil {\n\t\treturn n, errors.Wrapf(err, \"failed to download response and write to file: %s\", dst)\n\t}\n\n\treturn n, nil\n}", "func (m *CopyToDefaultContentLocationPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"destinationFileName\", m.GetDestinationFileName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"sourceFile\", m.GetSourceFile())\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}", "func DownloadFile(filepath string, url string)(err error){\n //Get the data \n resp, err := http.Get(url)\n if err != nil {\n logs.Error(\"Error downloading file: \"+err.Error())\n return err\n }\n defer resp.Body.Close()\n // Create the file\n out, err := os.Create(filepath)\n if err != nil {\n logs.Error(\"Error creating file after download: \"+err.Error())\n return err\n }\n defer out.Close()\n\n // Write the body to file\n _, err = io.Copy(out, resp.Body)\n if err != nil {\n logs.Error(\"Error Copying downloaded file: \"+err.Error())\n return err\n }\n return nil\n}", "func (fcb *FileCacheBackend) Save(ob types.OutgoingBatch) error {\n\tfilename := fcb.getFilename(fcb.getCacheFilename(ob))\n\tlog.Printf(\"Saving to %s\", filename)\n\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to save to %s - %s\", filename, err)\n\t}\n\tdefer file.Close()\n\tfor _, item := range ob.Values {\n\t\tfile.WriteString(item + \"\\n\")\n\t}\n\treturn nil\n}", "func (p *Page) save() error {\r\n\tfilename := p.Title\r\n\t//writes data to a file named by filename, the 0600 indicates that the file should be created with\r\n\t//read and write permissions for the user\r\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\r\n}", "func (p *Post) Download(loc string) error {\n\tres, err := http.Get(p.FileURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tfileName := path.Join(loc, p.GetFileName())\n\n\tfh, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fh.Close()\n\n\t_, err = io.Copy(fh, res.Body)\n\treturn err\n}", "func (r *Repository) Save(url string, toAddr, ccAddr []string, content string, status int) error {\n\treturn nil\n}", "func DownloadFile(client *http.Client, url, filepath string) (string, error) {\n\n\tlog.Println(\"Downloading\")\n\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tlog.Printf(\"error: GET, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"Received non 200 response code\")\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"error: READ, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\t// Create blank file\n\t//file, err := os.Create(filepath)\n\t//file, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t//if err != nil {\n\t//\treturn \"\", err\n\t//}\n\n\t//buff := make([]byte, 4096)\n\n\t//for {\n\t//\tnread, err := resp.Body.Read(buff)\n\t//\tif nread == 0 {\n\t//\t\tif err == nil {\n\t//\t\t\tcontinue\n\t//\t\t}\n\t//\t\tif _, err := file.Write(buff); err != nil {\n\t//\t\t\tbreak\n\t//\t\t}\n\t//\t\tif err != nil {\n\t//\t\t\tbreak\n\t//\t\t}\n\t//\t}\n\t//}\n\t////size, err := io.Copy(file, resp.Body)\n\t//defer file.Close()\n\n\t////if err != nil {\n\t////\tlog.Printf(\"error: WRITE, %s\", err)\n\t////\treturn \"\", err\n\t////}\n\t//statsFile, err := file.Stat()\n\t//log.Printf(\"Downloaded a file %s with size %d\", filepath, statsFile.Size())\n\n\tif err := ioutil.WriteFile(filepath, body, 0644); err != nil {\n\t\tlog.Printf(\"error: WRITE, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\t//content, err := ioutil.ReadAll(file)\n\t//if err != nil {\n\t//\tlog.Printf(\"error: READ, %s\", err)\n\t//\treturn \"\", err\n\t//}\n\n\tmd5sum := md5.Sum(body)\n\tmd5s := hex.EncodeToString(md5sum[0:])\n\n\treturn md5s, nil\n}", "func createBody(f *os.File, releaseTag, branch, docURL, exampleURL, releaseTars string) error {\n\tvar title string\n\tif *preview {\n\t\ttitle = \"Branch \"\n\t}\n\n\tif releaseTag == \"HEAD\" || releaseTag == branchHead {\n\t\ttitle += branch\n\t} else {\n\t\ttitle += releaseTag\n\t}\n\n\tif *preview {\n\t\tf.WriteString(fmt.Sprintf(\"**Release Note Preview - generated on %s**\\n\", time.Now().Format(\"Mon Jan 2 15:04:05 MST 2006\")))\n\t}\n\n\tf.WriteString(fmt.Sprintf(\"\\n# %s\\n\\n\", title))\n\tf.WriteString(fmt.Sprintf(\"[Documentation](%s) & [Examples](%s)\\n\\n\", docURL, exampleURL))\n\n\tif releaseTars != \"\" {\n\t\tf.WriteString(fmt.Sprintf(\"## Downloads for %s\\n\\n\", title))\n\t\ttables := []struct {\n\t\t\theading string\n\t\t\tfilename []string\n\t\t}{\n\t\t\t{\"\", []string{releaseTars + \"/kubernetes.tar.gz\", releaseTars + \"/kubernetes-src.tar.gz\"}},\n\t\t\t{\"Client Binaries\", []string{releaseTars + \"/kubernetes-client*.tar.gz\"}},\n\t\t\t{\"Server Binaries\", []string{releaseTars + \"/kubernetes-server*.tar.gz\"}},\n\t\t\t{\"Node Binaries\", []string{releaseTars + \"/kubernetes-node*.tar.gz\"}},\n\t\t}\n\n\t\tfor _, table := range tables {\n\t\t\terr := createDownloadsTable(f, releaseTag, table.heading, table.filename...)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create downloads table: %v\", err)\n\t\t\t}\n\t\t}\n\t\tf.WriteString(\"\\n\")\n\t}\n\treturn nil\n}", "func (api *api) save() {\n\tr := map[string]string{}\n\tfor k, v := range api.Manager.pathes {\n\t\tr[k] = v.content\n\t}\n\tdata, err := json.MarshalIndent(r, \"\", \" \")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(api.ConfigFile, data, 0755)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (p BlogPost) Save() error {\n\ttemp, err := json.Marshal(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"www/posts/\"+p.Path+\".json\", temp, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *Page) save() error {\n\tfilename := \"./pages/\" + p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}", "func writeHTTPResponseInWriter(httpRes http.ResponseWriter, httpReq *http.Request, nobelPrizeWinnersResponse []byte, err error) {\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(httpRes, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlog.Printf(\"Request %s Succesfully Completed\", httpReq.RequestURI)\n\thttpRes.Header().Set(\"Content-Type\", \"application/json\")\n\thttpRes.Write(nobelPrizeWinnersResponse)\n}", "func (r *historyRow) save(dir string) error {\n\trBytes, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thistoryFile := getLatestHistoryFile(dir)\n\n\tf, err := os.OpenFile(historyFile.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t_, err = f.Write(append(rBytes, []byte(\"\\n\")...))\n\treturn err\n}", "func writeToPath(resp *http.Response, path string) (int, error) {\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode > 299 {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn resp.StatusCode, errors.New(string(msg))\n\t}\n\n\tout, err := os.Create(path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer out.Close()\n\n\tio.Copy(out, resp.Body)\n\treturn resp.StatusCode, nil\n}", "func (env *Env) Save(res http.ResponseWriter, req *http.Request, title string) {\n\tenv.Log.V(1, \"beginning hanlding of Save.\")\n\ttitle = strings.Replace(strings.Title(title), \" \", \"_\", -1)\n\tbody := []byte(req.FormValue(\"body\"))\n\tpage := &webAppGo.Page{Title: title, Body: body}\n\terr := env.Cache.SaveToCache(page)\n\tif err != nil {\n\t\tenv.Log.V(1, \"notifying client that an internal error occured. Error is associated with Cache.SaveToCache.\")\n\t\thttp.Error(res, err.Error(), 500)\n\t}\n\terr = env.DB.SavePage(page)\n\tif err != nil {\n\t\tenv.Log.V(1, \"notifying client that an internal error occured. Error is associated with Cache.SavePage.\")\n\t\thttp.Error(res, err.Error(), 500)\n\t}\n\tenv.Log.V(1, \"The requested new page was successully saved, redirecting client to /view/PageTitle.\")\n\thttp.Redirect(res, req, \"/view/\"+title, http.StatusFound)\n}", "func SaveFileHandler(w http.ResponseWriter, r *http.Request) {\n\thttpSession, _ := session.HTTPSession.Get(r, session.CookieName)\n\tif httpSession.IsNew {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\tuid := httpSession.Values[\"uid\"].(string)\n\n\tresult := gulu.Ret.NewResult()\n\tdefer gulu.Ret.RetResult(w, r, result)\n\n\tif conf.Wide.ReadOnly {\n\t\tresult.Code = -1\n\t\tresult.Msg = \"readonly mode\"\n\t\treturn\n\t}\n\n\tvar args map[string]interface{}\n\n\tif err := json.NewDecoder(r.Body).Decode(&args); err != nil {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\treturn\n\t}\n\n\tfilePath := args[\"file\"].(string)\n\tsid := args[\"sid\"].(string)\n\n\tif gulu.Go.IsAPI(filePath) || !session.CanAccess(uid, filePath) {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\n\tfout, err := os.Create(filePath)\n\n\tif nil != err {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\treturn\n\t}\n\n\tcode := args[\"code\"].(string)\n\n\tfout.WriteString(code)\n\n\tif err := fout.Close(); nil != err {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\twSession := session.WideSessions.Get(sid)\n\t\twSession.EventQueue.Queue <- &event.Event{Code: event.EvtCodeServerInternalError, Sid: sid,\n\t\t\tData: \"can't save file \" + filePath}\n\n\t\treturn\n\t}\n}", "func (b *BodyWriter) Flush() {}", "func handleSave(w http.ResponseWriter, r *http.Request, title string) {\n\tvar (\n\t\tbody = r.FormValue(\"body\")\n\t\tp = &page.Page{Title: title, Body: []byte(body)}\n\t)\n\tif err := p.Save(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, pathView+title, http.StatusFound)\n\tlogInfo(p.Title, \"file saved succesfully\")\n}", "func SaveFileByURLPath(urlPath string, resp *http.Response) resource.IResource {\n\tfileInfo := resource.ParseURL(urlPath)\n\tif fileInfo != nil {\n\t\treturn SaveFileByFileInfo(fileInfo, resp)\n\t}\n\treturn nil\n}", "func (b *BaseHandler) SavePostFile(name, to string) error {\n\tb.request.ParseForm()\n\tfile, _, err := b.GetPostFile(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tout, err := os.Create(to)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, file)\n\n\treturn err\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 (mc *MockClient) AddBody(Method, Url, Body string, StatusCode int, header http.Header) {\n\tmc.AddResponse(Method, Url, http.Response{\n\t\tStatusCode: StatusCode,\n\t\tHeader: header,\n\t\tBody: io.NopCloser(bytes.NewReader([]byte(Body))),\n\t})\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 (c *Config) Save(filename string) (err error) {\n\tlog.Println(\"[DEBUG] Save\", filename)\n\n\tbody, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.writeFile(filename, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Write(body *multipart.Writer, item interface{}, files []File) error {\n\t// Encode the JSON body first\n\tw, err := body.CreateFormField(\"payload_json\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create bodypart for JSON\")\n\t}\n\n\tif err := json.EncodeStream(w, item); err != nil {\n\t\treturn errors.Wrap(err, \"failed to encode JSON\")\n\t}\n\n\tfor i, file := range files {\n\t\tnum := strconv.Itoa(i)\n\n\t\tw, err := body.CreateFormFile(\"file\"+num, file.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to create bodypart for \"+num)\n\t\t}\n\n\t\tif _, err := io.Copy(w, file.Reader); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to write for file \"+num)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *httpAxel) Download() error {\n\t// if save path exists, return conflicts\n\tif _, err := os.Stat(a.save); err == nil {\n\t\treturn fmt.Errorf(\"conflicts, save path [%s] already exists\", a.save)\n\t}\n\n\t// get the header & size\n\t// prepare for the chunk size\n\tresp, err := a.client.Get(a.remoteURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// return if not http status 200\n\tif code := resp.StatusCode; code != http.StatusOK {\n\t\treturn fmt.Errorf(\"%d - %s\", code, http.StatusText(code))\n\t}\n\n\t// detect total size & partial support\n\t// note: reset conn=1 if total size unknown\n\t// note: reset conn=1 if not supported partial download\n\ta.totalSize = resp.ContentLength\n\ta.supportPart = resp.Header.Get(\"Accept-Ranges\") != \"\"\n\tif a.totalSize <= 1 || !a.supportPart {\n\t\ta.conn = 1\n\t}\n\n\t// directly download and save\n\tif a.conn == 1 {\n\t\treturn a.directSave(resp.Body)\n\t}\n\n\t// partial downloa and save by concurrency\n\ta.chunkSize = a.totalSize / int64(a.conn)\n\ta.chunksDir = path.Join(filepath.Dir(a.save), filepath.Base(a.save)+\".chunks\")\n\tdefer os.RemoveAll(a.chunksDir)\n\n\t// concurrency get each chunks\n\terr = a.getAllChunks()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// join each pieces to the final save path\n\treturn a.join()\n}", "func downloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadBinaryFromResponse(response *http.Response, output *os.File, filePath string) error {\n\tif _, err := io.Copy(output, response.Body); err != nil {\n\t\treturn fmt.Errorf(\"problem saving %s to %s: %w\", response.Request.URL, filePath, err)\n\t}\n\n\t// Download was successful, add the rw bits.\n\tif err := output.Chmod(finishedFileMode); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *HTTPResponse) ToFile(filename string) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif r.resp.Body == nil {\n\t\treturn nil\n\t}\n\tdefer r.resp.Body.Close()\n\t_, err = io.Copy(f, r.resp.Body)\n\treturn err\n}", "func downloadFile(filepath string, url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadFile(filepath string, url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func (g *Generator) Save(w io.Writer) error {\n\tdata, err := json.MarshalIndent(g.spec, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func saveHandler(w http.ResponseWriter, r *http.Request, title string) {\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\terr := p.save()\n\tif err != nil {\n\t\tlog.Println(\"saveHandler() error: \", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}", "func (s *Storage) WriteBody(hash common.Hash, body *types.Body) {\n\ts.write(BODY, hash.Bytes(), body)\n\n\t/*\n\t\tdata, err := rlp.EncodeToBytes(body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn s.set(BODY, hash.Bytes(), data)\n\t*/\n}", "func saveHandler(w http.ResponseWriter, r *http.Request, title string) {\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\terr := p.save()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}", "func RespBody(r *http.Response) []byte {\n\tvar mw io.Writer\n\tvar body bytes.Buffer\n\tmw = io.MultiWriter(&body)\n\tio.Copy(mw, r.Body)\n\treturn body.Bytes()\n}", "func (w *WriterInterceptor) writeBody() (int, error) {\n\tif w.closed {\n\t\treturn 0, nil\n\t}\n\n\tbuf, err := ioutil.ReadAll(w.response.Body)\n\tdefer w.Close()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn w.writer.Write(buf)\n}", "func main() {\n\t// r here is a response, and r.Body is an io.Reader.\n\tr, err := http.Get(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Create a file to persist the response.\n\tfile, err := os.Create(os.Args[2])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer file.Close()\n\t//os.Stdout.Write(r.Body)\n\tvar buffer bytes.Buffer\n\tfor {\n\t\tb := make([]byte, 100)\n\t\tn, err := r.Body.Read(b)\n\t\tif n > 0 {\n\t\t\tbuffer.Write(b)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(buffer.String())\n\t// Use MultiWriter so we can write to stdout and\n\t// a file on the same write operation.\n\t//dest := io.MultiWriter(os.Stdout, file)\n\n\t// Read the response and write to both destinations.\n\t//io.Copy(dest, r.Body)\n\tif err := r.Body.Close(); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (c *Controller) Save(name string, f file.Any) error {\n\tb, err := json.Marshal(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\tutil.Log(string(b))\n\n\tr := bytes.NewReader(b)\n\n\tinput := &s3.PutObjectInput{\n\t\tBody: aws.ReadSeekCloser(r),\n\t\tBucket: aws.String(c.bucket),\n\t\tKey: aws.String(name),\n\t\tServerSideEncryption: aws.String(\"AES256\"),\n\t}\n\n\tswitch f.(type) {\n\tcase file.BananasMon:\n\t\tinput.Tagging = aws.String(\"App Name=hit-the-bananas\")\n\tcase file.D2sVendorDays:\n\t\tinput.Tagging = aws.String(\"App Name=drive-2-sku\")\n\t}\n\n\tresult, err := c.c3svc.PutObject(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.verIDs[name] = result.VersionId\n\n\treturn nil\n}", "func downloadHandler(w http.ResponseWriter, r *http.Request) {\n\tsession, err := store.Get(r, sessName)\n\tif err != nil {\n\t\tw.Write([]byte(\"bad cookie\"))\n\t\treturn\n\t}\n\n\t// authenticate user\n\tif session.Values[\"logged_in\"] != \"yes\" || !isAdmin(session.Values[\"andrew\"].(string)) {\n\t\thttp.Redirect(w, r, htmlRoot+\"/\", http.StatusFound)\n\t\treturn\n\t}\n\n\t// get andrew ID from GET\n\tandrew := r.URL.Query().Get(\"user\")\n\tif andrew == \"\" {\n\t\thttp.Redirect(w, r, htmlRoot+\"/admin\", http.StatusFound)\n\t}\n\n\t// find requested file in directory (gotta search b/c ext unknown)\n\tdir, err := ioutil.ReadDir(\"submissions\")\n\trx, _ := regexp.Compile(`[^\\.]+`)\n\tfor _, stat := range dir {\n\t\tmatches := rx.FindStringSubmatch(stat.Name())\n\t\tif matches[0] == andrew {\n\t\t\t// todo: use Content-Disposition or whatever to name file\n\t\t\tfile, err := os.Open(\"submissions/\" + stat.Name())\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tbuffer := make([]byte, stat.Size())\n\t\t\t_, err = file.Read(buffer)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tw.Write(buffer)\n\t\t\treturn\n\t\t}\n\t}\n\thttp.Redirect(w, r, htmlRoot+\"/admin\", http.StatusFound)\n}", "func (handler *ObjectWebHandler) Download(w http.ResponseWriter, r *http.Request) {\n\tparams := context.Get(r, CtxParamsKey).(httprouter.Params)\n\tif !bson.IsObjectIdHex(params.ByName(\"id\")) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid object ID\", nil)\n\t\treturn\n\t}\n\n\tobjID := bson.ObjectIdHex(params.ByName(\"id\"))\n\tfs := handler.Session.DB(os.Getenv(EnvGridFSDatabase)).GridFS(os.Getenv(EnvGridFSPrefix))\n\n\tfile, err := fs.OpenId(objID)\n\tif err == mgo.ErrNotFound {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\trespondWithError(w, http.StatusNotFound, \"Object does not exist\", err)\n\t\treturn\n\t} else if err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\trespondWithError(w, http.StatusInternalServerError, \"Operational error\", err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tif file.ContentType() != \"\" {\n\t\tw.Header().Set(\"Content-Type\", file.ContentType())\n\t}\n\tif file.Name() != \"\" {\n\t\tw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"inline; filename=\\\"%v\\\"\", file.Name()))\n\t}\n\n\t_, err = io.Copy(w, file)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, \"Operational error\", err)\n\t\treturn\n\t}\n}", "func handlerSave(w http.ResponseWriter, r *http.Request, title string) {\r\n\tbody := r.FormValue(\"body\")\r\n\tp := &Page{Title: title, Body: []byte(body)}\r\n\terr := p.save()\r\n\tif err != nil {\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\tos.Exit(1)\r\n\t}\r\n\thttp.Redirect(w, r, \"/view/\"+p.Title, http.StatusFound)\r\n}", "func downloadFile(filepath string, url string) error {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func downloadBookHandler(res http.ResponseWriter, req *http.Request) {\n _, claims, err := jwtauth.FromContext(req.Context())\n if err != nil {\n log.Println(err)\n res.WriteHeader(500)\n return\n }\n \n // Get the book's id from the request\n idQuery := req.URL.Query().Get(\"id\")\n var id primitive.ObjectID\n if _, err := hex.Decode(id[:], []byte(idQuery)); err != nil {\n res.WriteHeader(400)\n log.Println(err)\n return\n }\n\n // Check if the user owns the book\n if !userOwnsBook(claims[\"username\"].(string), id) {\n res.WriteHeader(400)\n log.Println(\"No such book\")\n return\n }\n\n // Load the book data from the database\n stream, err := booksBucket.OpenDownloadStream(id)\n defer stream.Close()\n if err != nil {\n res.WriteHeader(500)\n log.Println(err)\n return\n }\n\n // Send the book data to the user\n if _, err := io.Copy(res, stream); err != nil {\n log.Println(err)\n return\n }\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 Download(url string, filepath string) (err error) {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Writer the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func writeResponseLocation(request *restful.Request, response *restful.Response, identifier string) {\n\tlocation := request.Request.URL.Path\n\tif request.Request.Method == http.MethodPost {\n\t\tlocation = location + \"/\" + identifier\n\t}\n\tresponse.AddHeader(\"Content-Location\", location)\n\tresponse.WriteHeader(201)\n}", "func downloadFile(url, output string) error {\n\tif fsutil.IsExist(output) {\n\t\tos.Remove(output)\n\t}\n\n\tfd, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0644)\n\n\tif err != nil {\n\t\treturn fmtc.Errorf(\"Can't create file: %v\", err)\n\t}\n\n\tdefer fd.Close()\n\n\tresp, err := req.Request{URL: url}.Get()\n\n\tif err != nil {\n\t\treturn fmtc.Errorf(\"Can't download file: %v\", err)\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn fmtc.Errorf(\"Can't download file: server return status code %d\", resp.StatusCode)\n\t}\n\n\tw := bufio.NewWriter(fd)\n\t_, err = io.Copy(w, resp.Body)\n\n\tw.Flush()\n\n\tif err != nil {\n\t\treturn fmtc.Errorf(\"Can't write file: %v\", err)\n\t}\n\n\treturn nil\n}", "func (dr downloadResponse) Body() io.ReadCloser {\n\treturn dr.rawResponse.Body\n}", "func closeBody(r *http.Response) {\n\tif r.Body != nil {\n\t\t_, _ = io.Copy(io.Discard, r.Body)\n\t\t_ = r.Body.Close()\n\t}\n}", "func downloadFile(filepath string, url string) (err error) {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data into RAM - TODO stream straight to disk\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Check server response\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"bad status: %s\", resp.Status)\n\t}\n\n\t// write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *WebsiteSource) WriteToFile() error {\n\tsum := md5.Sum([]byte(w.URL + w.CSSSelect))\n\tfileName := hex.EncodeToString(sum[:]) //Try to generate a file name of fixed length\n\n\tsourceJSON, err := json.Marshal(*w)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error writing to file: %v\", err)\n\t}\n\n\tif err := os.MkdirAll(\"savedWebsites\", 0644); err != nil {\n\t\treturn fmt.Errorf(\"Error writing to file: %w\", err)\n\t}\n\n\treturn ioutil.WriteFile(\"savedWebsites/\"+fileName+\".json\", sourceJSON, 0644)\n}", "func SaveConfig(w http.ResponseWriter, r *http.Request) {\n\t//Load config-entry array from json\n\tlog.Println(\"Started answering save-request...\")\n\tlog.Println(\"Msg: \" + strconv.FormatInt(r.ContentLength, 10))\n\tjsonData, err := ioutil.ReadFile(configJsonPath)\n\tif err != nil {\n\t\tlog.Println(\"No \" + configJsonPath + \" found: \" + err.Error())\n\t}\n\tvar configEntries []Config\n\terr = json.Unmarshal(jsonData, &configEntries)\n\tif err != nil {\n\t\tlog.Println(\"Unmarshaling failed: \" + err.Error())\n\t}\n\t//Create and init config-entry\n\tvar newConfig Config\n\tmessage, err := readRequestBody(r)\n\tif err != nil {\n\t\treportError(w,400,\"Couldnt read the request-body\",\"could not read the request-body: \" + err.Error())\n\t\treturn\n\t}\n\tConfigInit(&newConfig, uint64(len(configEntries)))\n\t//Add config-entry to config array\n\tconfigEntries = append(configEntries, newConfig)\n\t//write config-entry array to json\n\tnewJson, err := json.MarshalIndent(configEntries, \"\", \" \")\n\tif err != nil {\n\t\treportError(w,500,\"Internal server error\",\"Failed marshaling the new Config-array: \" + err.Error())\n\t\treturn\n\t}\n\t//save config to fileURL\n\tioutil.WriteFile(configJsonPath, newJson, 0644)\n\t//create config file in configSavePath\n\tioutil.WriteFile(newConfig.FileUrl, []byte(message), 0644)\n\t//send back the new pwd\n\tw.Write([]byte(\"ID: \" + strconv.FormatUint(newConfig.ID, 10) + \" Password: \" + newConfig.Password))\n\tlog.Println(\"Answered save-request successfully...\")\n}", "func closeBody(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tf(w, r)\n\t\tr.Body.Close()\n\t}\n}", "func saveDocument(key string, c *gin.Context) *ResponseType {\n\tfilePath := dataDir + \"/\" + key\n\tfi, err := os.Stat(filePath)\n\tif err == nil && fi.Size() > 0 {\n\t\treturn newErrorResp(key, \"file exists\", fmt.Errorf(\"file already exists for key %s\", key))\n\t}\n\tf, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file creation error\", fmt.Errorf(\"error creating file for key %s: %s\", key, err.Error()))\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, c.Request.Body)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file write error\", fmt.Errorf(\"error copying body to file for key %s: %s\", key, err.Error()))\n\t}\n\tname := c.Request.FormValue(\"name\")\n\tcontentType := c.Request.Header.Get(\"Content-Type\")\n\textractor := c.Request.FormValue(\"extractor\")\n\ttitle := c.Request.FormValue(\"dc:title\")\n\tcreation := c.Request.FormValue(\"dcterms:created\")\n\tmodification := c.Request.FormValue(\"dcterms:modified\")\n\tmetadata := DocMetadata{\n\t\tTimestamp: time.Now().Unix(),\n\t\tName: name,\n\t\tContentType: contentType,\n\t\tExtractor: extractor,\n\t\tTitle: title,\n\t\tCreationDate: creation,\n\t\tModificationDate: modification,\n\t}\n\terr = saveMetadata(key, &metadata)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file metadata write error\", fmt.Errorf(\"error saving metadata for key %s: %s\", key, err.Error()))\n\t}\n\treturn newSuccessResp(key, \"document saved\")\n}", "func (app *service) Save(genesis Genesis) error {\n\tjs, err := app.adapter.ToJSON(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.fileService.Save(app.fileNameWithExt, js)\n}", "func (e EncodedFile) BodyAfterScanning(bodyByte []byte) string {\n\tencodedFile := base64.StdEncoding.EncodeToString(bodyByte)\n\te.data[\"Base64\"] = encodedFile\n\tj, _ := json.Marshal(e.data)\n\treturn string(j)\n}", "func (a *Asset) DownloadProxy(proxy Proxy) (string, error) {\n\tf, err := ioutil.TempFile(os.TempDir(), \"update-\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"creating temp file\")\n\t}\n\n\tlog.Debugf(\"fetch %q\", a.URL)\n\tres, err := http.Get(a.URL)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"fetching asset\")\n\t}\n\n\tkind := res.Header.Get(\"Content-Type\")\n\tsize, _ := strconv.Atoi(res.Header.Get(\"Content-Length\"))\n\tlog.Debugf(\"response %s – %s (%d KiB)\", res.Status, kind, size/1024)\n\n\tbody := proxy(size, res.Body)\n\n\tif res.StatusCode >= 400 {\n\t\tbody.Close()\n\t\treturn \"\", errors.Wrap(err, res.Status)\n\t}\n\n\tlog.Debugf(\"copy to %q\", f.Name())\n\tif _, err := io.Copy(f, body); err != nil {\n\t\tbody.Close()\n\t\treturn \"\", errors.Wrap(err, \"copying body\")\n\t}\n\n\tif err := body.Close(); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"closing body\")\n\t}\n\n\tif err := f.Close(); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"closing file\")\n\t}\n\n\tlog.Debugf(\"copied\")\n\treturn f.Name(), nil\n}", "func (r *Recipes) Save() error {\n\tb, err := json.Marshal(r.values)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := ioutil.WriteFile(\"recipes.json\", b, 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *CreateBlueprintInWorkspaceInternalParams) SetBody(body *model.BlueprintV4Request) {\n\to.Body = body\n}", "func (s *Saver) SaveRequest() error {\n\treqName, err := nameFromReqFileName(filepath.Base(s.fname))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdst := filepath.Join(s.dir, s.reqName)\n\n\tif !fileExists(dst) {\n\t\treturn copyFile(s.fname, dst)\n\t}\n\n\tok, err := compareFiles(s.fname, dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok {\n\t\treturn nil\n\t}\n\n\tdst = ReqFileName(reqName, s.dir)\n\ts.reqName = filepath.Base(dst)\n\n\treturn copyFile(s.fname, dst)\n}", "func (r *Reserve) Save(s *Store) error {\n\tdata, _ := json.Marshal(s)\n\tif err := ioutil.WriteFile(r.path, data, 0644); err != nil {\n\t\treturn fmt.Errorf(\"Failed to set %s: %s\", r.name, err)\n\t}\n\treturn nil\n}", "func Save(obj any, file string) error {\n\tfp, err := os.Create(file)\n\tdefer fp.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tbw := bufio.NewWriter(fp)\n\terr = Write(obj, bw)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\terr = bw.Flush()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn err\n}", "func (o *DownloadFlowFileContentParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.ClientID != nil {\n\n\t\t// query param clientId\n\t\tvar qrClientID string\n\n\t\tif o.ClientID != nil {\n\t\t\tqrClientID = *o.ClientID\n\t\t}\n\t\tqClientID := qrClientID\n\t\tif qClientID != \"\" {\n\n\t\t\tif err := r.SetQueryParam(\"clientId\", qClientID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif o.ClusterNodeID != nil {\n\n\t\t// query param clusterNodeId\n\t\tvar qrClusterNodeID string\n\n\t\tif o.ClusterNodeID != nil {\n\t\t\tqrClusterNodeID = *o.ClusterNodeID\n\t\t}\n\t\tqClusterNodeID := qrClusterNodeID\n\t\tif qClusterNodeID != \"\" {\n\n\t\t\tif err := r.SetQueryParam(\"clusterNodeId\", qClusterNodeID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// path param flowfile-uuid\n\tif err := r.SetPathParam(\"flowfile-uuid\", o.FlowfileUUID); err != nil {\n\t\treturn err\n\t}\n\n\t// path param id\n\tif err := r.SetPathParam(\"id\", o.ID); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (app *service) Save(state State) error {\n\tjs, err := app.adapter.ToJSON(state)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchainHash := state.Chain()\n\tindex := state.Height()\n\tpath := filePath(chainHash, index)\n\treturn app.fileService.Save(path, js)\n}", "func (bd *blobFSDownloader) GenerateDownloadFunc(jptm IJobPartTransferMgr, srcPipeline pipeline.Pipeline, destWriter common.ChunkedFileWriter, id common.ChunkID, length int64, pacer pacer) chunkFunc {\n\treturn createDownloadChunkFunc(jptm, id, func() {\n\n\t\t// step 1: Downloading the file from range startIndex till (startIndex + adjustedChunkSize)\n\t\tinfo := jptm.Info()\n\t\tu, _ := url.Parse(info.Source)\n\t\tsrcFileURL := azbfs.NewDirectoryURL(*u, srcPipeline).NewFileUrl()\n\t\t// At this point we create an HTTP(S) request for the desired portion of the file, and\n\t\t// wait until we get the headers back... but we have not yet read its whole body.\n\t\t// The Download method encapsulates any retries that may be necessary to get to the point of receiving response headers.\n\t\tjptm.LogChunkStatus(id, common.EWaitReason.HeaderResponse())\n\t\tget, err := srcFileURL.Download(jptm.Context(), id.OffsetInFile(), length)\n\t\tif err != nil {\n\t\t\tjptm.FailActiveDownload(\"Downloading response body\", err) // cancel entire transfer because this chunk has failed\n\t\t\treturn\n\t\t}\n\n\t\t// parse the remote lmt, there shouldn't be any error, unless the service returned a new format\n\t\tremoteLastModified, err := time.Parse(time.RFC1123, get.LastModified())\n\t\tcommon.PanicIfErr(err)\n\t\tremoteLmtLocation := remoteLastModified.Location()\n\n\t\t// Verify that the file has not been changed via a client side LMT check\n\t\tif !remoteLastModified.Equal(jptm.LastModifiedTime().In(remoteLmtLocation)) {\n\t\t\tjptm.FailActiveDownload(\"BFS File modified during transfer\",\n\t\t\t\terrors.New(\"BFS File modified during transfer\"))\n\t\t}\n\n\t\t// step 2: Enqueue the response body to be written out to disk\n\t\t// The retryReader encapsulates any retries that may be necessary while downloading the body\n\t\tjptm.LogChunkStatus(id, common.EWaitReason.Body())\n\t\tretryReader := get.Body(azbfs.RetryReaderOptions{\n\t\t\tMaxRetryRequests: MaxRetryPerDownloadBody,\n\t\t\tNotifyFailedRead: common.NewV1ReadLogFunc(jptm, u),\n\t\t})\n\t\tdefer retryReader.Close()\n\t\terr = destWriter.EnqueueChunk(jptm.Context(), id, length, newPacedResponseBody(jptm.Context(), retryReader, pacer), true)\n\t\tif err != nil {\n\t\t\tjptm.FailActiveDownload(\"Enqueuing chunk\", err)\n\t\t\treturn\n\t\t}\n\t})\n}", "func Fastly_http_body_write(\n\tbody_handle BodyHandle,\n\tbuf *uintptr,\n\tbuf_len *uintptr,\n\tend BodyWriteEnd,\n\tnwritten_out *uintptr, // *mut usize\n) int32", "func (i *buildEntry) ParseBodyWrite(rbody []byte, score int) (key string, err error) {\n\tfhidLogger.Loggo.Info(\"Processing image body request\", \"Body\", string(rbody))\n\terr = json.Unmarshal(rbody, i)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tt := time.Now()\n\ttstring := t.Format(\"2006-01-02 15:04:05\")\n\tkey = getUUID()\n\ti.ImageID = key\n\ti.CreateDate = tstring\n\tsrep, err := json.MarshalIndent(i, \"\", \" \")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = Rset(key, string(srep), score)\n\treturn key, err\n}", "func (h *httpFetcher) Fetch(ctx context.Context, url string, headers map[string]string) (*os.File, error) {\n\tif h.URLGetter == nil {\n\t\th.URLGetter = httpGet\n\t}\n\n\tif h.Limiter != nil {\n\t\tif !h.Limiter.Allow() {\n\t\t\treturn nil, fmt.Errorf(\"can't download asset due to rate limit\")\n\t\t}\n\t}\n\n\tresp, err := h.URLGetter(ctx, url, h.trustedCAFile, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\t// Write response to tmp\n\ttmpFile, err := ioutil.TempFile(os.TempDir(), \"sensu-asset\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't open tmp file for asset: %s\", err)\n\t}\n\n\tcleanup := func() {\n\t\ttmpFile.Close()\n\t\t_ = os.Remove(tmpFile.Name())\n\t}\n\n\tbuffered := bufio.NewWriter(tmpFile)\n\tif _, err = io.Copy(buffered, resp); err != nil {\n\t\tcleanup()\n\t\treturn nil, fmt.Errorf(\"error downloading asset: %s\", err)\n\t}\n\tif err := buffered.Flush(); err != nil {\n\t\tcleanup()\n\t\treturn nil, fmt.Errorf(\"error downloading asset: %s\", err)\n\t}\n\n\tif err := tmpFile.Sync(); err != nil {\n\t\tcleanup()\n\t\treturn nil, err\n\t}\n\n\tif _, err := tmpFile.Seek(0, 0); err != nil {\n\t\tcleanup()\n\t\treturn nil, err\n\t}\n\n\treturn tmpFile, nil\n}", "func (gl GroceryList) Save() error {\n\tgl.mu.Lock()\n\terr := ioutil.WriteFile(\"./resources/grocery-list.txt\", gl.Body, os.ModeDevice)\n\tgl.mu.Unlock()\n\treturn err\n}", "func (w bodyCacheWriter) Write(b []byte) (int, error) {\n\n\texceptionPaths := []string{\"search\"}\n\thasException := funk.Contains(exceptionPaths, w.model.Slug)\n\thasException = funk.Contains(exceptionPaths, w.model.Code)\n\n\tcacheIgnoredPaths := []string{\"search\"}\n\tisIgnored := funk.Contains(cacheIgnoredPaths, w.model.Slug)\n\tisIgnored = funk.Contains(cacheIgnoredPaths, w.model.Code)\n\n\t// Write the response to the cache only if a success code\n\tstatus := w.Status()\n\tif 200 <= status && status <= 299 && !isIgnored {\n\t\tswitch w.store {\n\t\tcase \"redis\":\n\t\t\tgo w.redis.Set(RedisResponsePrefix, w.itemKey, string(b), RedisResponseDefaultKeyExpirationTime)\n\n\t\t\tvar setKey string\n\t\t\tsetKey = w.groupKey\n\t\t\tif w.hasRequestParams && !hasException {\n\t\t\t\tsetKey = fmt.Sprint(w.groupKey, \":with_params\")\n\t\t\t}\n\n\t\t\titemKeyIndex := w.requestURI\n\t\t\tauthRole := *w.authUserRole\n\t\t\tauthUserID := *w.authUserID\n\n\t\t\tif authRole != \"\" && authUserID != 0 {\n\t\t\t\titemKeyIndex = fmt.Sprint(w.requestURI, \":user_role:\", authRole, \":user_id:\", authUserID)\n\n\t\t\t\tif w.model.ID != \"\" || w.model.Code != \"\" || (w.model.Slug != \"\" && !hasException) {\n\t\t\t\t\tgo w.redis.SAdd(RedisResponsePrefix, fmt.Sprint(w.groupKey, \":\", w.requestURI), itemKeyIndex)\n\t\t\t\t} else {\n\t\t\t\t\tif !w.hasRequestParams {\n\t\t\t\t\t\tgo w.redis.SAdd(RedisResponsePrefix, setKey, itemKeyIndex)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tgo w.redis.SAdd(RedisResponsePrefix, setKey, w.requestURI)\n\t\t\tgo w.redis.SAdd(RedisResponsePrefix, fmt.Sprint(w.groupKey, \":all\"), w.requestURI)\n\t\t}\n\n\t}\n\n\t// Then write the response to gin\n\treturn w.ResponseWriter.Write(b)\n}" ]
[ "0.6250908", "0.5745216", "0.54999065", "0.53012586", "0.52373475", "0.5236081", "0.52156407", "0.5190274", "0.5153593", "0.5066596", "0.50165904", "0.5004325", "0.5003726", "0.49831364", "0.49391568", "0.4936893", "0.49297172", "0.4924654", "0.49175733", "0.49039724", "0.48872268", "0.48849592", "0.48724967", "0.48633686", "0.48601738", "0.48408905", "0.4835482", "0.48346964", "0.48284206", "0.48160887", "0.48074564", "0.48025808", "0.47972956", "0.4789378", "0.47720528", "0.476858", "0.4753662", "0.47345617", "0.47309682", "0.47287366", "0.47176924", "0.47112498", "0.47075444", "0.47018388", "0.4699659", "0.46922952", "0.4664548", "0.46567246", "0.46471077", "0.46374145", "0.46371257", "0.46114537", "0.46004766", "0.45830727", "0.45651945", "0.45411554", "0.45346886", "0.45198193", "0.4519364", "0.4519364", "0.45177582", "0.45168605", "0.45115536", "0.45105916", "0.45084625", "0.4502075", "0.44971228", "0.4491625", "0.44734704", "0.4472949", "0.44695708", "0.44690493", "0.44584137", "0.4450451", "0.44466907", "0.4443132", "0.44308832", "0.44156304", "0.44110703", "0.4409355", "0.44050813", "0.44028366", "0.43910962", "0.43857595", "0.43823516", "0.43795165", "0.43750075", "0.43707013", "0.4367824", "0.436467", "0.43581614", "0.43577847", "0.4343641", "0.43372628", "0.43329254", "0.43319362", "0.4327579", "0.4326056", "0.4325922", "0.4311143" ]
0.85055155
0
processBody reads the response body associated for the given Fetcher and reports any errors
processBody считывает тело ответа, связанное с заданным Fetcher, и сообщает об любых ошибках
func (f Fetcher) processBody() []byte { b, err := io.ReadAll(f.resp.Body) f.resp.Body.Close() if f.resp.StatusCode >= 300 { log.Fatalf("Response failed with status code: %d\n and body: %s\n", f.resp.StatusCode, b) } check(err) return b }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func decodeBody(resp *http.Response, out interface{}) (error) {\n\tswitch resp.ContentLength {\n\tcase 0:\n\t\tif out == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"Got 0 byte response with non-nil decode object\")\n\tdefault:\n\t\tdec := json.NewDecoder(resp.Body)\n\t\treturn dec.Decode(out)\n\t}\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tswitch resp.ContentLength {\n\tcase 0:\n\t\tif out == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"Got 0 byte response with non-nil decode object\")\n\tdefault:\n\t\tdec := json.NewDecoder(resp.Body)\n\t\treturn dec.Decode(out)\n\t}\n}", "func (avisess *AviSession) fetchBody(verb, uri string, resp *http.Response) (result []byte, err error) {\n\turl := avisess.prefix + uri\n\terrorResult := AviError{HttpStatusCode: resp.StatusCode, Verb: verb, Url: url}\n\n\tif resp.StatusCode == 204 {\n\t\t// no content in the response\n\t\treturn result, nil\n\t}\n\t// It cannot be assumed that the error will always be from server side in response.\n\t// Error could be from HTTP client side which will not have body in response.\n\t// Need to change our API resp handling design if we want to handle client side errors separately.\n\n\t// Below block will take care for errors without body.\n\tif resp.Body == nil {\n\t\tglog.Errorf(\"Encountered client side error: %+v\", resp)\n\t\terrorResult.Message = &resp.Status\n\t\treturn result, errorResult\n\t}\n\n\tdefer resp.Body.Close()\n\tresult, err = ioutil.ReadAll(resp.Body)\n\tif err == nil {\n\t\tif resp.StatusCode < 200 || resp.StatusCode > 299 || resp.StatusCode == 500 {\n\t\t\tmres, merr := convertAviResponseToMapInterface(result)\n\t\t\tglog.Infof(\"Error code %v parsed resp: %v err %v\",\n\t\t\t\tresp.StatusCode, mres, merr)\n\t\t\temsg := fmt.Sprintf(\"%v\", mres)\n\t\t\terrorResult.Message = &emsg\n\t\t} else {\n\t\t\treturn result, nil\n\t\t}\n\t} else {\n\t\terrmsg := fmt.Sprintf(\"Response body read failed: %v\", err)\n\t\terrorResult.Message = &errmsg\n\t\tglog.Errorf(\"Error in reading uri %v %v\", uri, err)\n\t}\n\treturn result, errorResult\n}", "func decodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) *FailureResponse {\n\t// Check if Header is 'Content-Type: application/json'.\n\tif r.Header.Get(\"Content-Type\") != \"application/json\" {\n\t\treturn NewFailureResponse(http.StatusUnsupportedMediaType, \"The 'Content-Type' header is not 'application/json'!\")\n\t}\n\n\t// Parse body, and set max bytes reader (1KB).\n\t// No defaults because I believe there are no more possible errors. Please tell me if you think otherwise!\n\tr.Body = http.MaxBytesReader(w, r.Body, 1024)\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(dst); err != nil {\n\t\tvar syntaxError *json.SyntaxError\n\t\tvar unmarshalTypeError *json.UnmarshalTypeError\n\n\t\tswitch {\n\t\t// Handle syntax errors.\n\t\tcase errors.As(err, &syntaxError):\n\t\t\terrorMessage := fmt.Sprintf(\"Request body contains a badly formatted JSON at position %d!\", syntaxError.Offset)\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle unexpected EOFs.\n\t\tcase errors.Is(err, io.ErrUnexpectedEOF):\n\t\t\terrorMessage := \"Request body contains a badly-formed JSON!\"\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle wrong data-type in request body.\n\t\tcase errors.As(err, &unmarshalTypeError):\n\t\t\terrorMessage := fmt.Sprintf(\"Request body contains an invalid value for the %q field at position %d!\", unmarshalTypeError.Field, unmarshalTypeError.Offset)\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle unknown fields.\n\t\tcase strings.HasPrefix(err.Error(), \"json: unknown field \"):\n\t\t\tfieldName := strings.TrimPrefix(err.Error(), \"json: unknown field \")\n\t\t\terrorMessage := fmt.Sprintf(\"Request body contains unknown field '%s'!\", fieldName)\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle empty request body.\n\t\tcase errors.Is(err, io.EOF):\n\t\t\terrorMessage := \"Request body must not be empty!\"\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle too large body.\n\t\tcase err.Error() == \"http: request body too large\":\n\t\t\terrorMessage := \"Request body must not be larger than 1KB!\"\n\t\t\treturn NewFailureResponse(http.StatusRequestEntityTooLarge, errorMessage)\n\n\t\t}\n\t}\n\tdefer r.Body.Close()\n\n\t// Handle if client tries to send more than one JSON object.\n\tif err := decoder.Decode(&struct{}{}); err != io.EOF {\n\t\terrorMessage := \"Request body must only contain a single JSON object!\"\n\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\t}\n\n\t// Validate input.\n\tif err := validator.New().Struct(dst); err != nil {\n\t\treturn NewFailureResponse(http.StatusBadRequest, err.Error())\n\t}\n\n\t// If everything goes well, don't return anything.\n\treturn nil\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tdec := json.NewDecoder(resp.Body)\n\treturn dec.Decode(out)\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\treturn dec.Decode(out)\n}", "func parseBody(r *http.Request, dest interface{}) (int, error) {\n\t// Read the body of the request.\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\n\t// Were we able to read the request?\n\tif err == nil {\n\t\t// We were able to read it, so let's see if the data was valid.\n\t\terr = json.Unmarshal(body, &dest)\n\n\t\t// Was the data valid?\n\t\tif err == nil {\n\t\t\t// Data was valid.\n\t\t\treturn http.StatusOK, nil\n\t\t} else {\n\t\t\t// Data was invalid, so let the user know.\n\t\t\treturn http.StatusBadRequest, errors.New(\"Malformed request body.\")\n\t\t}\n\t} else {\n\t\t// There was an error. Send our error as the response.\n\t\treturn http.StatusBadRequest,\n\t\t\terrors.New(\"Could not read request. Size of request might be too large.\")\n\t}\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = json.Unmarshal(body, &out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ReadBodyJSON(output interface{}, body io.ReadCloser) ([]byte, *PzCustomError) {\n\trBytes, err := ioutil.ReadAll(body)\n\tif err != nil {\n\t\treturn nil, &PzCustomError{LogMsg: \"Could not read HTTP response.\"}\n\t}\n\terr = json.Unmarshal(rBytes, output)\n\tif err != nil {\n\t\treturn nil, &PzCustomError{LogMsg: \"Unmarshal failed: \" + err.Error() + \". Original input: \" + string(rBytes) + \".\", SimpleMsg: \"JSON error when reading HTTP Response. See log.\"}\n\t}\n\treturn rBytes, nil\n}", "func parseBody(r io.Reader, obj interface{}) {\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tlog.Println(\"Error reading body\", err)\n\t}\n\n\terr = json.Unmarshal(body, obj)\n\tif err != nil {\n\t\tlog.Println(\"Error parsing body\", err)\n\t}\n}", "func readBody(response *http.Response) ([]byte, error) {\n\tdefer response.Body.Close()\n\trtn, readErr := ioutil.ReadAll(response.Body)\n\n\treturn rtn, readErr\n}", "func ReadBody(resp *http.Response) (result []byte, err error) {\n\tdefer fs.CheckClose(resp.Body, &err)\n\treturn ioutil.ReadAll(resp.Body)\n}", "func (c *ClientWithResponses) ProcessEHRMessageWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ProcessEHRMessageResponse, error) {\n\trsp, err := c.ProcessEHRMessageWithBody(ctx, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseProcessEHRMessageResponse(rsp)\n}", "func DecodeBody(ctx context.Context, req *http.Request, m interface{}) error {\n\tif err := json.NewDecoder(req.Body).Decode(m); err != nil {\n\t\treturn errors.New(http.StatusText(http.StatusBadRequest))\n\t}\n\treturn nil\n}", "func processBodyIfNecessary(req *http.Request) io.Reader {\n\tswitch req.Header.Get(\"Content-Encoding\") {\n\tdefault:\n\t\treturn req.Body\n\n\tcase \"gzip\":\n\t\treturn gunzippedBodyIfPossible(req.Body)\n\n\tcase \"deflate\", \"zlib\":\n\t\treturn zlibUncompressedbody(req.Body)\n\t}\n}", "func (m *BaseMethod) ResponseProcess(body io.ReadCloser, h http.Header, s StatusCode, retries uint) (*Response, error) {\n\tb, err := ioutil.ReadAll(body)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(ReadBodyError)\n\t\treturn nil, ReadBodyError\n\t}\n\terr = body.Close()\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(CloseBodyError)\n\t\treturn nil, CloseBodyError\n\t}\n\tvar headers []KVPair\n\tfor k, vs := range h {\n\t\tfor _, v := range vs {\n\t\t\theaders = append(headers, KVPair{k, v})\n\t\t}\n\t}\n\treturn &Response{Bytes: b, StatusCode: s, Headers: headers, CountRetry: retries}, nil\n}", "func decodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) error {\n\tif r.Header.Get(\"Content-Type\") != \"\" {\n\t\tvalue, _ := header.ParseValueAndParams(r.Header, \"Content-Type\")\n\t\tif value != \"application/json\" {\n\t\t\tmsg := \"Content-Type header is not application/json\"\n\t\t\treturn &malformedRequest{status: http.StatusUnsupportedMediaType, msg: msg}\n\t\t}\n\t}\n\n\tr.Body = http.MaxBytesReader(w, r.Body, 1048576)\n\n\tdec := json.NewDecoder(r.Body)\n\tdec.DisallowUnknownFields()\n\n\terr := dec.Decode(&dst)\n\tif err != nil {\n\t\tvar syntaxError *json.SyntaxError\n\t\tvar unmarshalTypeError *json.UnmarshalTypeError\n\n\t\tswitch {\n\t\tcase errors.As(err, &syntaxError):\n\t\t\tmsg := fmt.Sprintf(\"Request body contains badly-formed JSON (at position %d)\", syntaxError.Offset)\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase errors.Is(err, io.ErrUnexpectedEOF):\n\t\t\tmsg := fmt.Sprintf(\"Request body contains badly-formed JSON\")\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase errors.As(err, &unmarshalTypeError):\n\t\t\tmsg := fmt.Sprintf(\"Request body contains an invalid value for the %q field (at position %d)\", unmarshalTypeError.Field, unmarshalTypeError.Offset)\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase strings.HasPrefix(err.Error(), \"json: unknown field \"):\n\t\t\tfieldName := strings.TrimPrefix(err.Error(), \"json: unknown field \")\n\t\t\tmsg := fmt.Sprintf(\"Request body contains unknown field %s\", fieldName)\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase errors.Is(err, io.EOF):\n\t\t\tmsg := \"Request body must not be empty\"\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase err.Error() == \"http: request body too large\":\n\t\t\tmsg := \"Request body must not be larger than 1MB\"\n\t\t\treturn &malformedRequest{status: http.StatusRequestEntityTooLarge, msg: msg}\n\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif dec.More() {\n\t\tmsg := \"Request body must only contain a single JSON object\"\n\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\t}\n\n\treturn nil\n}", "func decodeJsonBody(target interface{}, r *http.Request) error {\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.Body.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := json.Unmarshal(body, target); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) drainBody(body io.ReadCloser) {\n\tdefer body.Close()\n\n\t_, err := io.Copy(ioutil.Discard, io.LimitReader(body, 10))\n\tif err != nil {\n\t\tfmt.Println(\"Error reading response body: %v\", err)\n\t}\n}", "func ParseJsonBody(r io.ReadCloser, data interface{}) porterr.IError {\n\tif r == http.NoBody {\n\t\treturn nil\n\t}\n\tbody, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn porterr.New(porterr.PortErrorIO, \"I/O error. Request body error: \"+err.Error()).HTTP(http.StatusBadRequest)\n\t}\n\tdefer func() {\n\t\terr := r.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\terr = json.Unmarshal(body, data)\n\tif err != nil {\n\t\treturn porterr.New(porterr.PortErrorDecoder, \"Unmarshal error: \"+err.Error()).HTTP(http.StatusBadRequest)\n\t}\n\treturn nil\n}", "func (c *Client) readBody(resp *http.Response) ([]byte, error) {\n\tvar reader io.Reader = resp.Body\n\tswitch resp.Header.Get(\"Content-Encoding\") {\n\tcase \"\":\n\t\t// Do nothing\n\tcase \"gzip\":\n\t\treader = gzipDecompress(resp.Body)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"bug: comm.Client.JSONCall(): content was send with unsupported content-encoding %s\", resp.Header.Get(\"Content-Encoding\"))\n\t}\n\treturn io.ReadAll(reader)\n}", "func (b *Bulb) responseProcessor() {\n\tvar buff = make([]byte, 512)\n\tvar resp map[string]interface{}\n\n\tfor {\n\t\tn, err := b.conn.Read(buff)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tresponses := bytes.Split(buff[:n], []byte{CR, LF})\n\n\t\tfor _, r := range responses[:len(responses)-1] {\n\t\t\tresp = make(map[string]interface{})\n\n\t\t\terr = json.Unmarshal(r, &resp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"OKResponse err: %s\\n\", r)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase keysExists(resp, \"id\", \"result\"): // Command success\n\t\t\t\tvar unmarshaled OKResponse\n\t\t\t\terr = json.Unmarshal(r, &unmarshaled)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"second unmarshal error: %s\\n\", r)\n\t\t\t\t}\n\t\t\t\tb.results[unmarshaled.id()] <- &unmarshaled\n\t\t\tcase keysExists(resp, \"id\", \"error\"): // Command failed\n\t\t\t\tvar unmarshaled ERRResponse\n\t\t\t\terr = json.Unmarshal(r, &unmarshaled)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"second unmarshal error: %s\\n\", r)\n\t\t\t\t}\n\t\t\t\tb.results[unmarshaled.id()] <- &unmarshaled\n\t\t\tcase keysExists(resp, \"method\", \"params\"): // Notification\n\t\t\t\t// log.Printf(\"state change%s\\n\", r)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"unhandled response: %s\\n\", r)\n\t\t\t}\n\t\t}\n\t}\n\tlog.Printf(\"response processor exited\\n\")\n}", "func ReadBody(req *http.Request, p interface{}) error {\n\tbody, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read body error %v\", err)\n\t}\n\n\terr = json.Unmarshal(body, &p)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing body error %v\", err)\n\t}\n\n\treturn nil\n}", "func readBody(r *http.Request, v interface{}) error {\n\tbody, err := ioutil.ReadAll(r.Body)\n\t_ = r.Body.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"body read: %w\", err)\n\t}\n\n\terr = json.Unmarshal(body, v)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"json decode: %w\", err)\n\t}\n\n\treturn nil\n}", "func Body(resp *http.Response) (string, error) {\n\tdefer resp.Body.Close()\n\tb, e := ioutil.ReadAll(resp.Body)\n\treturn string(b), e\n}", "func (response *S3Response) UnmarshalBody(obj interface{}) error {\n defer response.Close()\n unmarshaller := xml.NewDecoder(response.httpResponse.Body)\n return unmarshaller.Decode(obj)\n}", "func (e *HTTPError) ResponseBody() interface{} {\n\treturn ErrRespopnse{\n\t\tCode: -1,\n\t\tMessage: e.Detail,\n\t}\n}", "func processResponse(resp mesos.Response, t agent.Response_Type) (agent.Response, error) {\n\tvar r agent.Response\n\tdefer func() {\n\t\tif resp != nil {\n\t\t\tresp.Close()\n\t\t}\n\t}()\n\tfor {\n\t\tif err := resp.Decode(&r); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn r, err\n\t\t}\n\t}\n\tif r.GetType() == t {\n\t\treturn r, nil\n\t} else {\n\t\treturn r, fmt.Errorf(\"processResponse expected type %q, got %q\", t, r.GetType())\n\t}\n}", "func decodeJSONBody(r *http.Request, dst interface{}) error {\n\tif r.Header.Get(\"Content-Type\") != \"\" {\n\t\tvalue, _ := header.ParseValueAndParams(r.Header, \"Content-Type\")\n\t\tif value != \"application/json\" {\n\t\t\treturn ContentHeaderError\n\t\t}\n\t}\n\n\tdec := json.NewDecoder(r.Body)\n\tdec.DisallowUnknownFields()\n\n\terr := dec.Decode(&dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dec.More() {\n\t\tmsg := \"Request body must only contain a single JSON object\"\n\t\treturn errors.New(msg)\n\t}\n\n\treturn nil\n}", "func safelyReadBody(r *http.Response) (io.ReadCloser, error) {\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\trdr := ioutil.NopCloser(bytes.NewBuffer(buf))\n\trdr2 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\n\tr.Body = rdr2\n\treturn rdr, nil\n}", "func DecodeResponseBody(body io.Reader, dest interface{}) error {\n\tdecoder := json.NewDecoder(body)\n\terr := decoder.Decode(dest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to decode response body: %s\", err.Error())\n\t}\n\n\treturn nil\n}", "func ParseProcessEHRMessageResponse(rsp *http.Response) (*ProcessEHRMessageResponse, error) {\n\tbodyBytes, err := io.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &ProcessEHRMessageResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\treturn response, nil\n}", "func (f Fetcher) SaveBody() {\n\tfile, err := os.Create(f.url)\n\tcheck(err)\n\tdefer file.Close()\n\n\tb := f.processBody()\n\t_, err = file.Write(b)\n\tcheck(err)\n}", "func (c *Client) consumeResponseBody(r *http.Response) {\n\tif r != nil && r.Body != nil {\n\t\tio.Copy(ioutil.Discard, r.Body)\n\t}\n}", "func readBodyContent(r *ResponseReader, res *Response) (string, error) {\n\t// 1. Any response to a HEAD request and any response with a 1xx\n\t// (Informational), 204 (No Content), or 304 (Not Modified) status\n\t// code always has empty body\n\tif (res.StatusCode/100 == 1) || (res.StatusCode == 204) || (res.StatusCode == 304) ||\n\t\t(res.Request != nil && res.Request.Method == \"HEAD\") {\n\t\tres.Body = \"\"\n\t\treturn \"\", nil\n\t}\n\n\tcontentLen := res.GetContentLength()\n\ttransferEnc := res.GetTransferEncoding()\n\t// fmt.Printf(\"Len: %v, Encoding: %v\", contentLen, transferEnc)\n\n\tbody := \"\"\n\tvar err error\n\tif transferEnc == \"chunked\" || contentLen == -1 {\n\t\tbody, err = readChunkedBodyContent(r, res)\n\t} else {\n\t\tbody, err = readLimitedBodyContent(r, res, contentLen)\n\t}\n\n\tres.Body = body\n\tres.AppendRaw(body, false)\n\treturn body, err\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 body(resp *http.Response) ([]byte, error) {\n\tvar buf bytes.Buffer\n\t_, err := buf.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func ValidateFounderResponseBody(body *FounderResponseBody) (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\treturn\n}", "func ParseJSONBody(body io.Reader) (map[string]interface{}, error) {\n\tif body == nil {\n\t\treturn nil, nil\n\t}\n\n\tdecoder := json.NewDecoder(body)\n\n\tparsed := make(map[string]interface{})\n\n\tif err := decoder.Decode(&parsed); err == io.EOF {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parsed, nil\n}", "func (res *ClientHTTPResponse) ReadAndUnmarshalBody(v interface{}) error {\n\trawBody, err := res.ReadAll()\n\tif err != nil {\n\t\t/* coverage ignore next line */\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(rawBody, v)\n\tif err != nil {\n\t\tres.req.Logger.Warn(\"Could not parse client json\",\n\t\t\tzap.String(\"error\", err.Error()),\n\t\t)\n\t\treturn errors.Wrapf(\n\t\t\terr,\n\t\t\t\"Could not parse client %q json\",\n\t\t\tres.req.ClientID,\n\t\t)\n\t}\n\n\treturn nil\n}", "func errorHandler(resp *http.Response) error {\n\tbody, err := rest.ReadBody(resp)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error when trying to read error from body: %w\", err)\n\t}\n\t// Decode error response\n\terrResponse := new(api.Error)\n\terr = xml.Unmarshal(body, &errResponse)\n\tif err != nil {\n\t\t// set the Message to be the body if can't parse the XML\n\t\terrResponse.Message = strings.TrimSpace(string(body))\n\t}\n\terrResponse.Status = resp.Status\n\terrResponse.StatusCode = resp.StatusCode\n\treturn errResponse\n}", "func ProcessWitResponse(message io.ReadCloser) WitMessage {\n\tintent, _ := ioutil.ReadAll(message)\n\n\tjsonString := string(intent[:])\n\t_ = jsonString\n\n\tvar jsonResponse WitMessage\n\terr := json.Unmarshal(intent, &jsonResponse)\n\tif err != nil {\n\t\tlog.Println(\"error parsing json: \", err)\n\t\tlog.Printf(\"plain text json was %+v\", jsonString)\n\t}\n\n\tvar numbers []WitNumber\n\tvar number WitNumber\n\n\terr = json.Unmarshal(jsonResponse.Outcome.Entities.RawGithub, &numbers)\n\tif err != nil {\n\t\t//log.Println(\"1 error parsing number json: \", err)\n\t\t//log.Println(\"string number object is: \", string(jsonResponse.Outcome.Entities.RawGithub))\n\t\terr = json.Unmarshal(jsonResponse.Outcome.Entities.RawGithub, &number)\n\t\tif err != nil {\n\t\t\t//log.Println(\"2 error parsing number json: \", err)\n\t\t} else {\n\t\t\tjsonResponse.Outcome.Entities.MultipleNumber = []WitNumber{number}\n\t\t}\n\n\t} else {\n\t\tjsonResponse.Outcome.Entities.MultipleNumber = numbers\n\t}\n\n\t//log.Printf(\"a: %+v\\n\\n\\n\", jsonResponse)\n\t//log.Printf(\"b: %+v\\n\\n\\n\", jsonString)\n\n\treturn jsonResponse\n\n}", "func closeBody(resp *http.Response) {\n\terr := resp.Body.Close()\n\tif err != nil {\n\t\tutil.Logger.Printf(\"error closing response body - Called by %s: %s\\n\", util.CallFuncName(), err)\n\t}\n}", "func closeBody(r *http.Response) {\n\tif r.Body != nil {\n\t\t_, _ = io.Copy(io.Discard, r.Body)\n\t\t_ = r.Body.Close()\n\t}\n}", "func decodeResponse(resp *http.Response, respJson interface{}) error {\n\tswitch resp.StatusCode {\n\tcase http.StatusOK, http.StatusCreated:\n\t\treturn json.NewDecoder(resp.Body).Decode(respJson)\n\tcase http.StatusUnauthorized, http.StatusNotFound:\n\t\treturn fmt.Errorf(\"HTTP status: %s\", http.StatusText(resp.StatusCode))\n\tcase 422: // Unprocessable Entity\n\t\tvar v map[string][]string\n\t\tif err := json.NewDecoder(resp.Body).Decode(&v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, messages := range v {\n\t\t\tfor _, msg := range messages {\n\t\t\t\t// Only return the very first error message\n\t\t\t\treturn errors.New(msg)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\treturn fmt.Errorf(\"invalid HTTP body\")\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected HTTP status: %d\", resp.StatusCode)\n\t}\n}", "func processApigeeJSON(apigeeResp []byte) apigeeJSONstr {\n\tlog.Debug(\"In processsApigeeJSON\")\n\tvar apigeeJSON apigeeJSONstr\n\tif err := json.Unmarshal(apigeeResp, &apigeeJSON); err != nil {\n\t\tpanic(fmt.Errorf(\"fatal error processing Apigee JSON: %s\", err))\n\t}\n\treturn apigeeJSON\n}", "func readBody(t *testing.T, r io.ReadCloser) *bytes.Buffer {\n\tdefer r.Close()\n\n\tvar b []byte\n\tbuf := bytes.NewBuffer(b)\n\t_, err := buf.ReadFrom(r)\n\tcheck(t, err)\n\n\treturn buf\n}", "func BodyParser(r *http.Request) []byte {\n\tbody, _ := ioutil.ReadAll(r.Body)\n\treturn body\n}", "func (ctx *serverRequestContextImpl) TryReadBody(body interface{}) (bool, error) {\n\tbuf, err := ctx.ReadBodyBytes()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tempty := len(buf) == 0\n\tif !empty {\n\t\terr = json.Unmarshal(buf, body)\n\t\tif err != nil {\n\t\t\treturn true, caerrors.NewHTTPErr(400, caerrors.ErrBadReqBody, \"Invalid request body: %s; body=%s\",\n\t\t\t\terr, string(buf))\n\t\t}\n\t}\n\treturn empty, nil\n}", "func (s *Nap) Body(body io.Reader) *Nap {\n\tif body == nil {\n\t\treturn s\n\t}\n\treturn s.BodyProvider(bodyProvider{body: body})\n}", "func (job *JOB) Process(ctx context.Context, rsp *http.Response) error {\n\tif rsp.StatusCode != http.StatusOK {\n\t\treturn errors.New(rsp.Status)\n\t}\n\tdefer rsp.Body.Close()\n\n\tvar result Result\n\tif err := json.NewDecoder(rsp.Body).Decode(&result); err != nil {\n\t\treturn errors.Annotate(err, \"json decode\")\n\t}\n\tlog.Println(\"Parks count:\", len(result.Items[0].Parks))\n\tfor _, item := range result.Items {\n\t\tfor _, park := range item.Parks {\n\t\t\tif err := job.updateParkStatus(ctx, park); err != nil {\n\t\t\t\tlog.Println(\"WARN: park status refresh failed: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *data) parseResponse(ctx context.Context, bodyReader io.ReadCloser, cond *conditions) error {\n\tpp := d.Points\n\tdataSplit := dataSplitUnaggregated\n\tif cond.aggregated {\n\t\tdataSplit = dataSplitAggregated\n\t}\n\n\t// Prevent starting parser if context is done\n\tif err := contextIsValid(ctx); err != nil {\n\t\treturn ctx.Err()\n\t}\n\n\t// Then wait if there is an active parser working\n\tselect {\n\tcase d.b <- bodyReader:\n\tcase <-ctx.Done():\n\t\treturn fmt.Errorf(\"parseResponse failed: %w\", ctx.Err())\n\t}\n\n\tvar metricID uint32\n\td.mut.Lock()\n\tdefer func() {\n\t\td.mut.Unlock()\n\t\t<-d.b\n\t}()\n\n\t// Are we still good to go?\n\tif err := contextIsValid(ctx); err != nil {\n\t\treturn fmt.Errorf(\"parseResponse failed: %w\", ctx.Err())\n\t}\n\n\tstart := time.Now()\n\tscanner := bufio.NewScanner(bodyReader)\n\tscanner.Buffer(make([]byte, 1048576), 67108864)\n\tscanner.Split(dataSplit)\n\n\tvar rowStart []byte\n\tfor scanner.Scan() {\n\t\trowStart = scanner.Bytes()\n\n\t\td.length += len(rowStart)\n\n\t\tnameLen, readBytes, err := ReadUvarint(rowStart)\n\t\tif err != nil {\n\t\t\treturn errClickHouseResponse\n\t\t}\n\n\t\trow := rowStart[int(readBytes):]\n\n\t\tname := row[:int(nameLen)]\n\t\trow = row[int(nameLen):]\n\n\t\tif cond.isReverse {\n\t\t\tmetricID = pp.MetricIDBytes(reverse.Bytes(name))\n\t\t} else {\n\t\t\tmetricID = pp.MetricIDBytes(name)\n\t\t}\n\n\t\tarrayLen, readBytes, err := ReadUvarint(row)\n\t\tif err != nil {\n\t\t\treturn errClickHouseResponse\n\t\t}\n\n\t\ttimes := make([]uint32, 0, arrayLen)\n\t\tvalues := make([]float64, 0, arrayLen)\n\n\t\trow = row[int(readBytes):]\n\t\tfor i := uint64(0); i < arrayLen; i++ {\n\t\t\ttimes = append(times, binary.LittleEndian.Uint32(row[:4]))\n\t\t\trow = row[4:]\n\t\t}\n\n\t\trow = row[int(readBytes):]\n\t\tfor i := uint64(0); i < arrayLen; i++ {\n\t\t\tvalues = append(values, math.Float64frombits(binary.LittleEndian.Uint64(row[:8])))\n\t\t\trow = row[8:]\n\t\t}\n\n\t\ttimestamps := times\n\t\tif !cond.aggregated {\n\t\t\ttimestamps = make([]uint32, 0, arrayLen)\n\t\t\trow = row[int(readBytes):]\n\t\t\tfor i := uint64(0); i < arrayLen; i++ {\n\t\t\t\ttimestamps = append(timestamps, binary.LittleEndian.Uint32(row[:4]))\n\t\t\t\trow = row[4:]\n\t\t\t}\n\t\t}\n\n\t\tfor i := range times {\n\t\t\tpp.AppendPoint(metricID, values[i], times[i], timestamps[i])\n\t\t}\n\t}\n\td.spent += time.Since(start)\n\n\terr := scanner.Err()\n\tif err != nil {\n\t\tdataErr, ok := err.(*clickhouse.ErrWithDescr)\n\t\tif ok {\n\t\t\t// format full error string, sometimes parse not failed at start orf error string\n\t\t\tdataErr.PrependDescription(string(rowStart))\n\t\t}\n\t\tbodyReader.Close()\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func responseDecodeJSON(bodyResponse io.Reader, response interface{}) error {\n\tvar body, errBody = ioutil.ReadAll(bodyResponse)\n\tif errBody != nil {\n\t\treturn errBody\n\t}\n\n\terrJSON := json.Unmarshal(body, response)\n\tif errJSON != nil {\n\t\treturn errJSON\n\t}\n\n\treturn nil\n}", "func Process(response string, lc logger.LoggingClient) map[string]interface{} {\n\trsp := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(response), &rsp)\n\tif err != nil {\n\t\tlc.Error(\"error unmarshalling response from JSON: %v\", err.Error())\n\t}\n\treturn rsp\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//fmt.Println(\"response Body:\", string(body))\n\n\t// Unmarshal the XML.\n\tif err = xml.Unmarshal(body, &out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func decodeBadRequest(r *http.Response) (err error) {\n\n\ttype badRequestResponse struct {\n\t\tErrors []string `json:\"errors\"`\n\t}\n\n\tif !strings.Contains(r.Header.Get(\"Content-Type\"), \"application/json\") {\n\t\treturn NewBadRequestError(\"bad request\")\n\t}\n\tvar e badRequestResponse\n\tif err = json.NewDecoder(r.Body).Decode(&e); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn NewBadRequestError(\"bad request\")\n\t\t}\n\t\treturn err\n\t}\n\treturn NewBadRequestError(e.Errors...)\n}", "func redactBody(ruleMatch HTTPMatch, r *http.Request) error {\n\tif r.Body == nil {\n\t\treturn nil\n\t}\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tredactedBody := []byte{}\n\tcontentType := getContentType(r)\n\n\tif contentType != \"\" {\n\t\tredactedBody, err = mapBody(ruleMatch, contentType, body)\n\t}\n\n\tcontentLength := len(redactedBody)\n\n\tr.Body = ioutil.NopCloser(bytes.NewReader(redactedBody))\n\tr.Header.Set(\"Content-Length\", strconv.Itoa(contentLength))\n\tr.ContentLength = int64(contentLength)\n\n\treturn err\n}", "func (s *Server) process(ctx context.Context, message json.RawMessage) interface{} {\n\trequests := []Request{}\n\t// parsing batch requests\n\tbatch := IsArray(message)\n\n\t// making not batch request looks like batch to simplify further code\n\tif !batch {\n\t\tmessage = append(append([]byte{'['}, message...), ']')\n\t}\n\n\t// unmarshal request(s)\n\tif err := json.Unmarshal(message, &requests); err != nil {\n\t\treturn NewResponseError(nil, ParseError, \"\", nil)\n\t}\n\n\t// if there no requests to process\n\tif len(requests) == 0 {\n\t\treturn NewResponseError(nil, InvalidRequest, \"\", nil)\n\t} else if len(requests) > s.options.BatchMaxLen {\n\t\treturn NewResponseError(nil, InvalidRequest, \"\", \"max requests length in batch exceeded\")\n\t}\n\n\t// process single request: if request single and not notification - just run it and return result\n\tif !batch && requests[0].ID != nil {\n\t\treturn s.processRequest(ctx, requests[0])\n\t}\n\n\t// process batch requests\n\tif res := s.processBatch(ctx, requests); len(res) > 0 {\n\t\treturn res\n\t}\n\n\treturn nil\n}", "func (s *BasecluListener) ExitBody(ctx *BodyContext) {}", "func (o *EmailUpdatePostReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewEmailUpdatePostNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewEmailUpdatePostDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func TestGetDataFromUrlBodyReadError(t *testing.T) {\n\tdefer gock.Off()\n\n\tapiUrl := \"http://example.com\"\n\tapiPath := \"status\"\n\n\tgock.New(apiUrl).\n\t\tGet(apiPath).\n\t\tReply(200).\n\t\tBodyString(\"\")\n\n\t_, err := getDataFromURL(apiUrl+\"/\"+apiPath, func(r io.Reader) ([]byte, error) {\n\t\treturn nil, errors.New(\"IO Reader error occurred\")\n\t})\n\n\tassert.Error(t, err)\n}", "func ReadJSONBody(writer http.ResponseWriter, request *http.Request, obj interface{}) error {\n\tb, err := ioutil.ReadAll(request.Body)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn err\n\t}\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusBadRequest)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *PostSlashingValidatorsValidatorAddrUnjailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostSlashingValidatorsValidatorAddrUnjailOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostSlashingValidatorsValidatorAddrUnjailBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostSlashingValidatorsValidatorAddrUnjailInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func getBody(resp *http.Response) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn body, err\n}", "func readDiscardBody(req *http.Request, resp *http.Response) int64 {\n\tif req.Method == http.MethodHead {\n\t\treturn 0\n\t}\n\n\tw := ioutil.Discard\n\tbytes, err := io.Copy(w, resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"reading HTTP response body: %v\", err)\n\t}\n\treturn bytes\n}", "func processAsyncResponse(client *GroupMgmtClient, body []byte) (interface{}, error) {\n\terrResp, _ := unwrapError(body)\n\tif client.WaitOnJob { // check sync flag\n\t\tunwrapMessage := &ErrorResponse{}\n\t\terr := json.Unmarshal(body, unwrapMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar jobId string\n\t\tfor _, msg := range unwrapMessage.Messages {\n\t\t\tif msg.Code == smAsyncJobId {\n\t\t\t\tjobId = msg.Arguments.JobId\n\t\t\t}\n\t\t}\n\t\tif len(jobId) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"http response error: status (202), but no job ID returned, messages: %v\", errResp)\n\t\t}\n\n\t\tid, err := waitForJobResult(jobId, client)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"http response error: status (202), messages: %v\", err.Error())\n\t\t}\n\t\treturn id, nil\n\t}\n\treturn nil, fmt.Errorf(\"http response error: status (202), messages: %v\", errResp)\n}", "func getBody(resp *http.Response) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\treturn body, err\n}", "func (dr downloadResponse) Body() io.ReadCloser {\n\treturn dr.rawResponse.Body\n}", "func process(response []byte, err error) (Response, error) {\n\tvar (\n\t\tjsonR encode.JResult\n\t\tresult Response\n\t\tstatus int\n\t)\n\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tvar objmap map[string]*json.RawMessage\n\terr = json.Unmarshal(response, &objmap)\n\n\terr = json.Unmarshal(*objmap[\"statusCode\"], &status)\n\n\tif status != 200 {\n\t\tvar r Response\n\t\t_ = json.Unmarshal(*objmap[\"statusCode\"], &r.StatusCode)\n\t\t_ = json.Unmarshal(*objmap[\"statusText\"], &r.StatusText)\n\t\treturn r, err\n\t}\n\n\terr = json.Unmarshal(response, &jsonR)\n\tif err != nil {\n\t\treturn Response{}, err\n\t}\n\n\t//Lots of work to convert {\"0\":{},\"1\":{}} to [{},{}]\n\tresult.StatusCode = jsonR.StatusCode\n\tresult.StatusText = jsonR.StatusText\n\tresult.Data.TestId = jsonR.Data.TestId\n\tresult.Data.Summary = jsonR.Data.Summary\n\tresult.Data.Label = jsonR.Data.Label\n\tresult.Data.Url = jsonR.Data.Url\n\tresult.Data.Location = jsonR.Data.Location\n\tresult.Data.Connectivity = jsonR.Data.Connectivity\n\tresult.Data.From = jsonR.Data.From\n\tresult.Data.BwDown = jsonR.Data.BwDown\n\tresult.Data.BwUp = jsonR.Data.BwUp\n\tresult.Data.Latency = jsonR.Data.Latency\n\n\t//iOS app sends int, but browsers send string\n\tswitch v := jsonR.Data.Plr.(type) {\n\tcase string:\n\t\tinf, _ := strconv.ParseInt(v, 10, 32)\n\t\tresult.Data.Plr = int32(inf)\n\tcase int64:\n\t\tresult.Data.Plr = int32(v)\n\tcase float64:\n\t\tresult.Data.Plr = int32(v)\n\tcase nil:\n\t\tresult.Data.Plr = 1\n\tdefault:\n\t\tlog.Printf(\"Failed to convert: %v\", v)\n\t}\n\tresult.Data.Completed = jsonR.Data.Completed\n\tresult.Data.SuccessfulFVRuns = jsonR.Data.SuccessfulFVRuns\n\n\tr, _ := regexp.Compile(\"^userTime.(.*)\")\n\tfor i, val := range jsonR.Data.Runs {\n\t\t_ = i\n\n\t\tval.FirstView.UserTiming = make(map[string]int)\n\n\t\tfor key, extra := range val.FirstView.Extra {\n\t\t\tif r.MatchString(key) && extra != nil {\n\t\t\t\tmetric := r.FindStringSubmatch(key)[1]\n\t\t\t\tval.FirstView.UserTiming[metric] = int(extra.(float64))\n\t\t\t}\n\t\t}\n\t\tresult.Data.Runs = append(result.Data.Runs, val)\n\t}\n\n\treturn result, err\n}", "func ParseBody(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Header.Get(\"Content-Type\") == \"application/json\" {\n\t\t\tvar jf jsonform\n\t\t\tif err := json.NewDecoder(r.Body).Decode(&jf); err != nil {\n\t\t\t\tpanic(srverror.New(err, 400, \"Unable to decode json object\"))\n\t\t\t}\n\t\t\tr.PostForm = jf.Values()\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\tpanic(srverror.New(err, 400, \"Unable to parse form values\"))\n\t\t\t}\n\t\t} else if r.Header.Get(\"Content-Type\") == \"multipart/form-data\" {\n\t\t\tif err := r.ParseMultipartForm(32 << 20); err != nil {\n\t\t\t\tpanic(srverror.New(err, 400, \"Unable to parse multipart form values\"))\n\t\t\t}\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (s *TeString) processResponse(data string, body string) int8 {\n\n\tregexMatch := regexTeStringMatch.FindAllStringSubmatch(string(body), -1)\n\tif regexMatch == nil {\n\t\tlog.Printf(\"No regex match in TE string report\")\n\t\treturn WORK_RESPONSE_ERROR\n\t}\n\n\treturn s.setRecord(data, int(util.ConvertStringToInt32(regexMatch[0][1])))\n}", "func readBody(win *acme.Win) ([]byte, error) {\n\tvar body []byte\n\tbuf := make([]byte, 8000)\n\tfor {\n\t\tn, err := win.Read(\"body\", buf)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbody = append(body, buf[0:n]...)\n\t}\n\treturn body, nil\n}", "func (o *ActOnPipelineUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewActOnPipelineUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewActOnPipelineUsingPOSTUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewActOnPipelineUsingPOSTForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewActOnPipelineUsingPOSTNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewActOnPipelineUsingPOSTInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (req *ServerHTTPRequest) UnmarshalBody(\n\tbody interface{}, rawBody []byte,\n) bool {\n\terr := req.jsonWrapper.Unmarshal(rawBody, body)\n\tif err != nil {\n\t\treq.contextLogger.WarnZ(req.Context(), \"Could not parse json\", zap.Error(err))\n\t\tif !req.parseFailed {\n\t\t\treq.res.SendError(400, \"Could not parse json: \"+err.Error(), err)\n\t\t\treq.parseFailed = true\n\t\t}\n\t\treturn false\n\t}\n\n\treturn true\n}", "func ProcessResponseError(_ context.Context, err error, w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tswitch err {\n\tcase cargo.ErrUnknown:\n\t\tw.WriteHeader(http.StatusNotFound)\n\tcase servicecommons.ErrInvalidArgument:\n\t\tw.WriteHeader(http.StatusBadRequest)\n\tdefault:\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n\tjson.NewEncoder(w).Encode(map[string]interface{}{\n\t\t\"error\": err.Error(),\n\t})\n}", "func (output *OutputStruct) fillFromResponse(response *http.Response) error {\n\toutput.responseCode = response.StatusCode\n\toutput.headers = response.Header\n\tif len(output.headers) == 0 {\n\t\toutput.headers = nil\n\t}\n\tvar err error\n\toutput.postBody, err = ioutil.ReadAll(response.Body)\n\tif len(output.postBody) == 0 {\n\t\toutput.postBody = nil\n\t}\n\treturn err\n}", "func ReadBody(request *http.Request, des interface{}, msg string) error {\n\tif kind := reflect.TypeOf(des).Kind(); kind != reflect.Ptr {\n\t\treturn errgo.Errorf(\"des should be a pointer: but got %#v\", kind)\n\t}\n\tif err := json.NewDecoder(request.Body).Decode(des); err != nil {\n\t\treturn errgo.Errorf(\"Failed to decode request body,Error: %s\", err.Error())\n\t}\n\treturn nil\n}", "func getBody(rw http.ResponseWriter, r *http.Request, requestBody *structs.Request) (error, string) {\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\trdr1 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\trdr2 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\n\t//Save the state back into the body for later use (Especially useful for getting the AOD/QOD because if the AOD has not been set a random AOD is set and the function called again)\n\tr.Body = rdr2\n\tif err := json.NewDecoder(rdr1).Decode(&requestBody); err != nil {\n\t\tlog.Printf(\"Got error when decoding: %s\", err)\n\t\terr = errors.New(\"request body is not structured correctly. Please refer to the /docs page for information on how to structure the request body\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(rw).Encode(structs.ErrorResponse{Message: err.Error()})\n\t\treturn err, \"\"\n\t}\n\treturn nil, string(buf)\n}", "func (c *Client) parseBody(body interface{}) (io.Reader, error) {\n\tvar bodyData io.Reader\n\tvar err error\n\tvar bdata []byte\n\tif body == nil {\n\t\treturn nil, nil\n\t}\n\tswitch body.(type) {\n\tcase string:\n\t\tbodyStr := body.(string)\n\t\tif len(strings.TrimSpace(bodyStr)) == 0 || bodyStr == \"\" {\n\t\t\tbodyData = nil\n\t\t} else {\n\t\t\tbodyData = strings.NewReader(bodyStr)\n\t\t}\n\t\t//json字符串\n\t\tif gjson.Valid(bodyStr) {\n\t\t\tif c.prettyQsl {\n\t\t\t\tbodyStr = string(pretty.Pretty([]byte(bodyStr)))\n\t\t\t}\n\t\t}\n\t\tlogs.Debug(\"the body data:\\n%s\", bodyStr)\n\tdefault:\n\t\tif c.prettyQsl {\n\t\t\tbdata, err = json.MarshalIndent(body, \"\", \"\\t\")\n\t\t} else {\n\t\t\tbdata, err = json.Marshal(body)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogs.Error(\"the body is decoded error:%s\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\tbodyData = bytes.NewReader(bdata)\n\t\tlogs.Debug(\"the body data:\\n%s\", string(bdata))\n\t}\n\treturn bodyData, nil\n}", "func (c *client) handleResponse(resp *http.Response, method, url string, result interface{}) error {\n\t// Read response body into memory\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn maskAny(errors.Wrapf(err, \"Failed reading response data from %s request to %s: %v\", method, url, err))\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tvar er ErrorResponse\n\t\tif err := json.Unmarshal(body, &er); err == nil {\n\t\t\treturn maskAny(StatusError{\n\t\t\t\tStatusCode: resp.StatusCode,\n\t\t\t\tmessage: er.Error,\n\t\t\t})\n\t\t}\n\t\treturn maskAny(StatusError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t})\n\t}\n\n\t// Got a success status\n\tif result != nil {\n\t\tif err := json.Unmarshal(body, result); err != nil {\n\t\t\treturn maskAny(errors.Wrapf(err, \"Failed decoding response data from %s request to %s: %v\", method, url, err))\n\t\t}\n\t}\n\treturn nil\n}", "func (runner *Runner) Batch(context interface{}, body io.Reader) []*Response {\n\trequests := make([]Request, 0)\n\terr := json.NewDecoder(body).Decode(&requests)\n\tif err != nil {\n\t\treturn []*Response{NewResponseWithError(\"\", Errors.InvalidRequest)}\n\t}\n\n\tresponses := make([]*Response, len(requests))\n\tfor index, request := range requests {\n\t\tif request.JsonRPC != \"2.0\" {\n\t\t\tresponses[index] = NewResponseWithError(request.Id, Errors.InvalidRequest)\n\t\t\tcontinue\n\t\t}\n\n\t\tfn, ok := runner.methods[request.Method]\n\t\tif !ok {\n\t\t\tresponses[index] = NewResponseWithError(request.Id, Errors.NotFound)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult, status := fn(context, request.Params)\n\t\tif status.Code != 0 {\n\t\t\tresponses[index] = NewResponseWithError(request.Id, status)\n\t\t\tcontinue\n\t\t}\n\t\tresponses[index] = NewResponse(request.Id, result)\n\t}\n\treturn responses\n}", "func exitOnResp(resp *http.Response) {\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\texitOnErr(err)\n\t}\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\texitOnErr(err)\n\t}\n\texitOnErr(\n\t\tfmt.Errorf(\"Received %s: %s\", resp.Status, string(b)))\n}", "func (r Response) UnprocessableEntity(code string, payload Payload, header ...ResponseHeader) {\n\tr.Response(code, http.UnprocessableEntity, payload, header...)\n}", "func (c *serverCodec) ReadBody(x interface{}) error {\n\t// If x!=nil and return error e:\n\t// - Write() will be called with e.Error() in r.Error\n\tif x == nil {\n\t\treturn nil\n\t}\n\tif c.req.Params == nil {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tparams []byte\n\t\terr error\n\t)\n\n\t// 在这里把请求参数json 字符串转换成了相应的struct\n\tparams = []byte(*c.req.Params)\n\t// if c.req.Method == BatchMethod {\n\t// \treturn fmt.Errorf(\"batch request is not allowed\")\n\t// \t/*\n\t// \t\targ := x.(*BatchArg)\n\t// \t\targ.srv = c.srv\n\t// \t\tif err := json.Unmarshal(*c.req.Params, &arg.reqs); err != nil {\n\t// \t\t\treturn NewError(errParams.Code, err.Error())\n\t// \t\t}\n\t// \t\tif len(arg.reqs) == 0 {\n\t// \t\t\treturn errRequest\n\t// \t\t}\n\t// \t*/\n\t// } else\n\tif err = json.Unmarshal(*c.req.Params, x); err != nil {\n\t\t// Note: if c.request.Params is nil it's not an error, it's an optional member.\n\t\t// JSON params structured object. Unmarshal to the args object.\n\n\t\tif 2 < len(params) && params[0] == '[' && params[len(params)-1] == ']' {\n\t\t\t// Clearly JSON params is not a structured object,\n\t\t\t// fallback and attempt an unmarshal with JSON params as\n\t\t\t// array value and RPC params is struct. Unmarshal into\n\t\t\t// array containing the request struct.\n\t\t\tparams := [1]interface{}{x}\n\t\t\tif err = json.Unmarshal(*c.req.Params, &params); err != nil {\n\t\t\t\treturn NewError(errParams.Code, err.Error())\n\t\t\t}\n\t\t} else {\n\t\t\treturn NewError(errParams.Code, err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (dr *RetryableDownloadResponse) Body(o RetryReaderOptions) io.ReadCloser {\n\tif o.MaxRetryRequests == 0 {\n\t\treturn dr.Response().Body\n\t}\n\n\treturn NewRetryReader(\n\t\tdr.ctx,\n\t\tdr.Response(),\n\t\tdr.info,\n\t\to,\n\t\tfunc(ctx context.Context, info HTTPGetterInfo) (*http.Response, error) {\n\t\t\tresp, err := dr.f.Download(ctx, info.Offset, info.Count, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn resp.Response(), err\n\t\t})\n}", "func (file *HgmFile) readBody(count int64, copySink *[]byte) (err error) {\n\n\tfor count != 0 {\n\t\t// Creates a sink which we are going to use as our read buffer\n\t\t// note that this is re-allocated on each loop as we may pass\n\t\t// this reference to lruCache and must avoid overwriting it afterwards\n\t\tbyteSink := make([]byte, lruBlockSize)\n\t\tif int64(len(byteSink)) > count {\n\t\t\t// shrink buffer size if we got less to read than allocated\n\t\t\tbyteSink = byteSink[:count]\n\t\t}\n\n\t\tnr := 0\n\t\tfor nr != len(byteSink) {\n\t\t\trb, re := file.bbody.Read(byteSink[nr:])\n\t\t\tnr += rb\n\n\t\t\tif re != nil {\n\t\t\t\tif rb == 0 && re == io.EOF && nr > 0 {\n\t\t\t\t\t// hide this EOF error, as we did read in previous loops\n\t\t\t\t} else {\n\t\t\t\t\terr = re\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif copySink != nil {\n\t\t\t*copySink = append(*copySink, byteSink[:nr]...)\n\t\t\tif lruCache != nil && ((nr > 0 && err == nil) || (nr == 0 && err == io.EOF)) {\n\t\t\t\t// Cache whatever we got from a lruBlockSize boundary\n\t\t\t\t// this will always be <= lruBlockSize\n\t\t\t\tevicted := lruCache.Add(file.lruKey(file.offset), byteSink[:nr])\n\t\t\t\tif evicted {\n\t\t\t\t\thgmStats.lruEvicted++\n\t\t\t\t}\n\t\t\t\thgmStats.bytesMiss += int64(nr)\n\t\t\t}\n\t\t}\n\n\t\tfile.offset += int64(nr)\n\t\tcount -= int64(nr)\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t}\n\treturn err\n}", "func unpackRequestBody(decoder *hessian.Decoder, reqObj interface{}) error {\n\tif decoder == nil {\n\t\treturn perrors.Errorf(\"@decoder is nil\")\n\t}\n\n\treq, ok := reqObj.([]interface{})\n\tif !ok {\n\t\treturn perrors.Errorf(\"@reqObj is not of type: []interface{}\")\n\t}\n\tif len(req) < 7 {\n\t\treturn perrors.New(\"length of @reqObj should be 7\")\n\t}\n\n\tvar (\n\t\terr error\n\t\tdubboVersion, target, serviceVersion, method, argsTypes interface{}\n\t\targs []interface{}\n\t)\n\n\tdubboVersion, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[0] = dubboVersion\n\n\ttarget, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[1] = target\n\n\tserviceVersion, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[2] = serviceVersion\n\n\tmethod, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[3] = method\n\n\targsTypes, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[4] = argsTypes\n\n\tats := DescRegex.FindAllString(argsTypes.(string), -1)\n\tvar arg interface{}\n\tfor i := 0; i < len(ats); i++ {\n\t\targ, err = decoder.Decode()\n\t\tif err != nil {\n\t\t\treturn perrors.WithStack(err)\n\t\t}\n\t\targs = append(args, arg)\n\t}\n\treq[5] = args\n\n\tattachments, err := decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\tif v, ok := attachments.(map[interface{}]interface{}); ok {\n\t\tv[DUBBO_VERSION_KEY] = dubboVersion\n\t\treq[6] = ToMapStringInterface(v)\n\t\treturn nil\n\t}\n\n\treturn perrors.Errorf(\"get wrong attachments: %+v\", attachments)\n}", "func (resp *Response) ReadBody() []byte {\n\tif resp.Resp != nil && resp.Resp.Body != nil {\n\t\tbody, err := ioutil.ReadAll(resp.Resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn body\n\t}\n\treturn nil\n}", "func (c *Ctx) ReadBody(out interface{}) error {\n\t// Get decoder from pool\n\tschemaDecoder := decoderPool.Get().(*schema.Decoder)\n\tdefer decoderPool.Put(schemaDecoder)\n\n\t// Get content-type\n\tctype := ToLower(BytesToString(c.Request.Header.ContentType()))\n\n\tswitch {\n\tcase strings.HasPrefix(ctype, MIMEApplicationJSON):\n\t\tschemaDecoder.SetAliasTag(\"json\")\n\t\treturn json.Unmarshal(c.Request.Body(), out)\n\tcase strings.HasPrefix(ctype, MIMEApplicationForm):\n\t\tschemaDecoder.SetAliasTag(\"form\")\n\t\tdata := make(map[string][]string)\n\t\tc.PostArgs().VisitAll(func(key []byte, val []byte) {\n\t\t\tdata[BytesToString(key)] = append(data[BytesToString(key)], BytesToString(val))\n\t\t})\n\t\treturn schemaDecoder.Decode(out, data)\n\tcase strings.HasPrefix(ctype, MIMEMultipartForm):\n\t\tschemaDecoder.SetAliasTag(\"form\")\n\t\tdata, err := c.MultipartForm()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn schemaDecoder.Decode(out, data.Value)\n\tcase strings.HasPrefix(ctype, MIMETextXML), strings.HasPrefix(ctype, MIMEApplicationXML):\n\t\tschemaDecoder.SetAliasTag(\"xml\")\n\t\treturn xml.Unmarshal(c.Request.Body(), out)\n\t}\n\t// No suitable content type found\n\treturn ErrUnprocessableEntity\n}", "func ParseBetaTestersBuildsGetToManyRelationshipResponse(rsp *http.Response) (*BetaTestersBuildsGetToManyRelationshipResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &BetaTestersBuildsGetToManyRelationshipResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest BetaTesterBuildsLinkagesResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 400:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON400 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 403:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON403 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 404:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON404 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func unmarshalApiResponse(apiResponse *RawResponse, dest interface{}) error {\n if apiResponse.StatusCode == fasthttp.StatusOK || apiResponse.StatusCode == fasthttp.StatusAccepted {\n if err := json.Unmarshal(apiResponse.Body, dest); err != nil {\n return err\n }\n return nil\n } else {\n var apiError errors.ApiError\n if err := json.Unmarshal(apiResponse.Body, &apiError); err != nil {\n return err\n }\n return apiError\n }\n}", "func DecodeReqBody(reqBody io.ReadCloser, v interface{}) error {\n\tbody, _ := ioutil.ReadAll(reqBody)\n\terr := json.Unmarshal(body, v)\n\tif err != nil {\n\t\tlog.Printf(\"Error unmarshaling request body: %s\", err)\n\t}\n\n\treqBody.Close()\n\treturn err\n}", "func ValidateFieldNoteAuthorResponseBody(body *FieldNoteAuthorResponseBody) (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.MediaURL == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"mediaUrl\", \"body\"))\n\t}\n\treturn\n}", "func readBody(msg []byte, state *readState) error {\n\tline := msg[0 : len(msg)-2]\n\tvar err error\n\tif line[0] == '$' {\n\t\t// bulk reply\n\t\tstate.bulkLen, err = strconv.ParseInt(string(line[1:]), 10, 64)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"protocol error: \" + string(msg))\n\t\t}\n\t\tif state.bulkLen <= 0 { // null bulk in multi bulks\n\t\t\tstate.args = append(state.args, []byte{})\n\t\t\tstate.bulkLen = 0\n\t\t}\n\t} else {\n\t\tstate.args = append(state.args, line)\n\t}\n\treturn nil\n}", "func (pr httpProber) ProbeForBody(req *http.Request, timeout time.Duration) (probe.Result, string, string, error) {\n\tpr.transport.DisableCompression = true // removes Accept-Encoding header\n\tclient := &http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: pr.transport,\n\t\tCheckRedirect: RedirectChecker(pr.followNonLocalRedirects),\n\t}\n\treturn DoHTTPProbe(req, client)\n}", "func (ctx *serverRequestContextImpl) ReadBody(body interface{}) error {\n\tempty, err := ctx.TryReadBody(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif empty {\n\t\treturn caerrors.NewHTTPErr(400, caerrors.ErrEmptyReqBody, \"Empty request body\")\n\t}\n\treturn nil\n}", "func (res *ServerHTTPResponse) PeekBody(\n\tkeys ...string,\n) ([]byte, jsonparser.ValueType, error) {\n\tvalue, valueType, _, err := jsonparser.Get(\n\t\tres.pendingBodyBytes, keys...,\n\t)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\n\treturn value, valueType, nil\n}", "func ReadBody(body io.ReadCloser) (string, error) {\n\tbuf := new(bytes.Buffer)\n\t_, err := buf.ReadFrom(body)\n\treturn buf.String(), err\n}", "func CollectHTTPBody(r *http.Request, g *grids.GridPacket) {\n\tcontent, ok := r.Header[\"Content-Type\"]\n\tmuxcontent := strings.Join(content, \";\")\n\twind := strings.Index(muxcontent, \"application/x-www-form-urlencode\")\n\tmind := strings.Index(muxcontent, \"multipart/form-data\")\n\tjsn := strings.Index(muxcontent, \"application/json\")\n\n\tif ok {\n\n\t\tif jsn != -1 {\n\t\t\tg.Set(\"Type\", \"json\")\n\t\t\tg.Set(\"JSON\", true)\n\t\t\tg.Set(\"Data\", true)\n\t\t}\n\n\t\tif wind != -1 {\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\tlog.Println(\"Request Read Form Error\", err)\n\t\t\t} else {\n\t\t\t\tform := r.Form\n\t\t\t\tpform := r.PostForm\n\n\t\t\t\tg.Set(\"Data\", true)\n\t\t\t\tg.Set(\"Form\", true)\n\t\t\t\tg.Set(\"Form\", form)\n\t\t\t\tg.Set(\"PostForm\", pform)\n\t\t\t}\n\t\t}\n\n\t\tif mind != -1 {\n\t\t\tif err := r.ParseMultipartForm(32 << 20); err != nil {\n\t\t\t\tlog.Println(\"Request Read MultipartForm Error\", err)\n\t\t\t} else {\n\t\t\t\tg.Set(\"Data\", true)\n\t\t\t\tg.Set(\"Form\", false)\n\t\t\t\tg.Set(\"Value\", r.MultipartForm.Value)\n\t\t\t\tg.Set(\"Body\", r.MultipartForm.File)\n\t\t\t}\n\t\t}\n\n\t\tif mind == -1 && wind == -1 && r.Body != nil {\n\n\t\t\tdata := make([]byte, r.ContentLength)\n\t\t\ttotal, err := r.Body.Read(data)\n\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tlog.Println(\"Request Read Body Error\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tg.Set(\"Data\", true)\n\t\t\tg.Set(\"Form\", false)\n\t\t\tg.Set(\"Value\", total)\n\t\t\tg.Set(\"Body\", data)\n\n\t\t}\n\t}\n}", "func Body(body, contentType, transferEncoding string, opt Options) (string, error) {\n\t// attempt to do some base64-decoding anyway\n\tif decoded, err := base64.URLEncoding.DecodeString(body); err == nil {\n\t\tbody = string(decoded)\n\t}\n\tif decoded, err := base64.StdEncoding.DecodeString(body); err == nil {\n\t\tbody = string(decoded)\n\t}\n\n\tif strings.ToLower(transferEncoding) == \"quoted-printable\" {\n\t\tb, err := ioutil.ReadAll(quotedprintable.NewReader(strings.NewReader(body)))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tbody = string(b)\n\t}\n\n\tct := strings.ToLower(contentType)\n\tif strings.Contains(ct, \"multipart/\") {\n\t\treturn parseMultipart(body, contentType, opt)\n\t}\n\n\tif !opt.SkipHTML && strings.Contains(ct, \"text/html\") {\n\t\tbody = stripHTML(body, opt)\n\t}\n\n\tbody = stripEmbedded(body, opt)\n\tif opt.LineLimit > 0 || opt.ColLimit > 0 {\n\t\tlines := strings.Split(body, \"\\n\")\n\t\tif len(lines) > opt.LineLimit {\n\t\t\tlines = lines[:opt.LineLimit]\n\t\t}\n\t\tfor kk, l := range lines {\n\t\t\tif len(l) > opt.ColLimit {\n\t\t\t\tlines[kk] = l[:opt.ColLimit]\n\t\t\t}\n\t\t}\n\t\tbody = strings.Join(lines, \"\\n\")\n\t}\n\treturn body, nil\n}" ]
[ "0.5680592", "0.56435114", "0.5631959", "0.5522728", "0.54882276", "0.5482303", "0.54751396", "0.5364349", "0.5358157", "0.53234804", "0.5321872", "0.52747655", "0.5210658", "0.51857114", "0.5130053", "0.5072723", "0.50544876", "0.5036079", "0.5028855", "0.49748597", "0.4963768", "0.4952745", "0.4938989", "0.49363086", "0.4920965", "0.4911645", "0.49109825", "0.48982882", "0.48913342", "0.48871675", "0.48425215", "0.48420122", "0.48388273", "0.48203894", "0.48093832", "0.4808277", "0.47887823", "0.47856432", "0.47812858", "0.4773805", "0.47708338", "0.47615275", "0.4748162", "0.47479904", "0.4747029", "0.47385287", "0.47291046", "0.46974552", "0.4690019", "0.4685364", "0.4672111", "0.46676952", "0.46636498", "0.46458364", "0.46446848", "0.46409777", "0.46365994", "0.4627743", "0.4626552", "0.4623899", "0.46231934", "0.46186945", "0.4613056", "0.46030784", "0.46028998", "0.45993727", "0.4597782", "0.45961374", "0.45931348", "0.45891005", "0.45874673", "0.45867157", "0.45816615", "0.45796645", "0.45739892", "0.45722306", "0.45697692", "0.45652527", "0.45640007", "0.45571062", "0.45519018", "0.454939", "0.4541909", "0.4539101", "0.45375875", "0.4534919", "0.45268714", "0.45241663", "0.4523686", "0.45182332", "0.45164788", "0.45036244", "0.45032585", "0.45026022", "0.44985098", "0.44937098", "0.4484905", "0.44847673", "0.44740582", "0.44721746" ]
0.7787903
0
NewTreeFromState initiates a Tree from state data previously written by
NewTreeFromState инициирует Tree из данных состояния, ранее записанных с помощью
func NewTreeFromState(data io.Reader) (*Tree, error) { idx := &Tree{ newBlocks: make(chan int), done: make(chan bool), blockMap: make(map[int]int), } if err := idx.loadState(data); err != nil { return nil, fmt.Errorf("Failed loading index state : %v", err) } go idx.blockAllocator() return idx, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *DB) InitStateTree(depth int) error {\n\trootNode := core.NewStateRoot(depth)\n\treturn db.Instance.Create(&rootNode).Error\n}", "func newTreeNode(parent *treeNode, move Move, state GameState, ucbC float64) *treeNode {\n\t// Construct the new node.\n\tnode := treeNode{\n\t\tparent: parent,\n\t\tmove: move,\n\t\tstate: state,\n\t\ttotalOutcome: 0.0, // No outcome yet.\n\t\tvisits: 0, // No visits yet.\n\t\tuntriedMoves: state.AvailableMoves(), // Initially the node starts with every node unexplored.\n\t\tchildren: nil, // No children yet.\n\t\tucbC: ucbC, // Whole tree uses same constant.\n\t\tselectionScore: 0.0, // No value yet.\n\t\tplayer: state.PlayerJustMoved(),\n\t}\n\n\t// We're working with pointers.\n\treturn &node\n}", "func (n *Node) createState() bytes.Buffer {\n\tstate := &struct {\n\t\tNext string\n\t\tID string\n\t\tPrev string\n\t}{\n\t\tn.fingers[0].node.IP,\n\t\tn.IP,\n\t\tn.prev.IP,\n\t}\n\tb := new(bytes.Buffer)\n\terr := json.NewEncoder(b).Encode(state)\n\tif err != nil {\n\t\tn.log.Err.Println(err)\n\t}\n\treturn *b\n}", "func NewTree(c *Config) *Tree {\n\treturn &Tree{c: c}\n}", "func NewTree() *Tree {\n\treturn &Tree{&bytes.Buffer{}}\n}", "func NewTree() *BPTree {\n\treturn &BPTree{LastAddress: 0, keyPosMap: make(map[string]int64), enabledKeyPosMap: false}\n}", "func newTree(segmentSize, maxsize, depth int, hashfunc func() hash.Hash) *tree {\n\tn := newNode(0, nil, hashfunc())\n\tprevlevel := []*node{n}\n\t// iterate over levels and creates 2^(depth-level) nodes\n\t// the 0 level is on double segment sections so we start at depth - 2\n\tcount := 2\n\tfor level := depth - 2; level >= 0; level-- {\n\t\tnodes := make([]*node, count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tparent := prevlevel[i/2]\n\t\t\tnodes[i] = newNode(i, parent, hashfunc())\n\t\t}\n\t\tprevlevel = nodes\n\t\tcount *= 2\n\t}\n\t// the datanode level is the nodes on the last level\n\treturn &tree{\n\t\tleaves: prevlevel,\n\t\tbuffer: make([]byte, maxsize),\n\t}\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\trnd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func NewObjectTree(flags byte) *ObjectTree { return new(ObjectTree).Init(flags) }", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func NewStateNode(path, hash string, nodeType uint64) *UserState {\n\tnewUserState := &UserState{\n\t\tAccountID: ZERO,\n\t\tPath: path,\n\t\tType: nodeType,\n\t}\n\tnewUserState.UpdatePath(newUserState.Path)\n\tnewUserState.Hash = hash\n\treturn newUserState\n}", "func NewTree(repo *Repository, id SHA1) *Tree {\n\treturn &Tree{\n\t\tID: id,\n\t\trepo: repo,\n\t}\n}", "func NewTree(path string, withFiles bool) Tree {\n\tfiles, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil\n\t}\n\troot := newNode(path, true, buildTree(path, files, withFiles))\n\treturn &tree{\n\t\troot: root,\n\t}\n}", "func NewTree(db *badger.Storage, root []byte) *Tree {\n\tt := &Tree{\n\t\tdb: newTreeDb(db),\n\t}\n\tt.cache = lru.NewCache(2048)\n\tvar zero [32]byte\n\tif root != nil && len(root) == int(32) && bytes.Compare(root, zero[:]) > common.Zero {\n\t\tt.root = t.mustLoadNode(root)\n\t}\n\n\tif err := FileExist(); err == nil {\n\t\tt.BackCommit()\n\t}\n\n\treturn t\n}", "func NewTree(pattern string, handlers []baa.HandlerFunc) *Tree {\n\tif pattern == \"\" {\n\t\tpanic(\"tree.new: pattern can be empty\")\n\t}\n\treturn &Tree{\n\t\tstatic: true,\n\t\talpha: pattern[0],\n\t\tpattern: pattern,\n\t\tformat: []byte(pattern),\n\t\thandlers: handlers,\n\t}\n}", "func (f *Forest) New(d *crypto.Digest, l uint32) *Tree {\n\tt := &Tree{\n\t\tleaves: l,\n\t\tdig: d,\n\t\tf: f,\n\t\tlastBlockLen: BlockSize,\n\t\tleavesComplete: make([]bool, l),\n\t}\n\tf.writeTree(t)\n\treturn t\n}", "func NewTree(n *node) (*Tree, error) {\n\treturn &Tree{\n\t\troot: n,\n\t\tvalues: map[string]*node{n.value: n},\n\t}, nil\n}", "func New(name string) *Tree {\n\treturn &Tree{name: name, root: &Node{}, mtx: &sync.RWMutex{}}\n}", "func NewTree(id string, cache storage.Cache, leaves storage.Store, hasher hashing.Hasher) *Tree {\n\n\tcacheLevels := int(math.Max(0.0, math.Floor(math.Log(float64(cache.Size()))/math.Log(2.0))))\n\tdigestLength := len(hasher([]byte(\"a test event\"))) * 8\n\n\ttree := &Tree{\n\t\t[]byte(id),\n\t\tleafHasherF(hasher),\n\t\tinteriorHasherF(hasher),\n\t\tmake([][]byte, digestLength),\n\t\tcache,\n\t\tleaves,\n\t\tnew(stats),\n\t\tnewArea(digestLength-cacheLevels, digestLength),\n\t\tdigestLength,\n\t\tnil,\n\t}\n\n\t// init default hashes cache\n\ttree.defaultHashes[0] = hasher(tree.id, Empty)\n\tfor i := 1; i < int(digestLength); i++ {\n\t\ttree.defaultHashes[i] = hasher(tree.defaultHashes[i-1], tree.defaultHashes[i-1])\n\t}\n\ttree.ops = tree.operations()\n\n\treturn tree\n}", "func New(name string) *Tree {\n\treturn &Tree{\n\t\tName: name,\n\t}\n}", "func NewFromString(s string) (*Tree, error) {\n\treturn New(strings.NewReader(s))\n}", "func NewTree() *Tree {\n\treturn &Tree{Symbol{NIL, \"NewTree holder\"}, make([]*Tree, 0, maxChildren), nil}\n}", "func NewTree(index uint8) *RBTree {\n\tvar rbTree = &RBTree{\n\t\troot: nil,\n\t\tmLeft: nil,\n\t\tmRight: nil,\n\t\tSize: 0,\n\t\tIndex: index,\n\t}\n\treturn rbTree\n}", "func NewState(e *etcd.Client, ttl time.Duration, path ...string) State {\n\trealttl := 1 * time.Second\n\tif ttl.Seconds() > realttl.Seconds() {\n\t\trealttl = ttl\n\t}\n\treturn &state{\n\t\te: e,\n\t\tkey: strings.Join(path, \"/\"),\n\t\tttl: uint64(realttl.Seconds()),\n\t}\n}", "func (l *hierLayer) updateState(cmap map[*replicationElement]string) {\n\t//go through the map and build the tree\n\tl.root = &DfsTreeElement{name: \"/\", fileType: \"dir\", path: \"\", content: \"\",parent:nil,}\n\tstack := lls.New()\n\n\n\t//policy used here is skip\n\n\tstack.Push(l.root)\n\t// untill stack empty\n\tfor !stack.Empty() {\n\t\t// \tpop stack call el\n\t\tra, _ := stack.Pop()\n\t\tel := ra.(*DfsTreeElement)\n\n\t\tif el.fileType == \"dir\" {\n\t\t\tfor _, i := range getChildren(el, cmap) {\n\t\t\t\tii := i\n\t\t\t\tstack.Push(&ii)\n\t\t\t\tel.children = append(el.children, &ii)\n\t\t\t}\n\t\t\t// fmt.Println(el.getPath(), el.children)\n\n\t\t}\n\n\t}\n\n\t//last step is to send the interface layer with update state\n\tl.updateInterface()\n\n}", "func newPageState(title string) *PageState {\n\treturn &PageState{\n\t\tTitle: title,\n\t\tTimezones: []*page.Component{},\n\t}\n}", "func New(rootHash, utxoRootHash *corecrypto.HashType, db storage.Table) (*StateDB, error) {\n\n\ttr, err := trie.New(rootHash, db)\n\tif err != nil {\n\t\tlogger.Warn(err)\n\t\treturn nil, err\n\t}\n\tutr, err := trie.New(utxoRootHash, db)\n\tif err != nil {\n\t\tlogger.Warn(err)\n\t\treturn nil, err\n\t}\n\treturn &StateDB{\n\t\tdb: db,\n\t\ttrie: tr,\n\t\tutxoTrie: utr,\n\t\tstateObjects: make(map[types.AddressHash]*stateObject),\n\t\tstateObjectsDirty: make(map[types.AddressHash]struct{}),\n\t\tlogs: make(map[corecrypto.HashType][]*types.Log),\n\t\tpreimages: make(map[corecrypto.HashType][]byte),\n\t\tjournal: newJournal(),\n\t}, nil\n}", "func New() *Tree {\n\treturn &Tree{}\n}", "func NewTree() *Tree {\n\treturn new(Tree)\n}", "func New() *Tree {\n\treturn &Tree{\n\t\tDelimiter: DefaultDelimiter,\n\t\tFormatter: SimpleFormatter,\n\t\tErrors: make(map[string]error),\n\t}\n}", "func NewTree(from []int) *Tree {\n\ttreeSize := calcTreeSize(len(from))\n\tnodes := make([]int, treeSize)\n\n\tt := &Tree{nodes, len(from)}\n\tt.build(from, 0, 0, len(from)-1)\n\n\treturn t\n}", "func createStartingState(path string, finfo os.FileInfo) (*walkerContext, *Directory) {\n\tdir := newDirectory(path, finfo)\n\tcontext := &walkerContext{\n\t\tcurrent: dir,\n\t\tbaseDir: path,\n\t\tall: make(map[string]*Directory),\n\t}\n\tcontext.all[path] = dir\n\treturn context, dir\n}", "func NewStateFromDisk() (*State, error) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgen, err := loadgen(filepath.Join(cwd, \"database\", \"gen.json\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar balances State\n\tbalances.Balances = gen.Balances\n\n\tf, err := os.OpenFile(filepath.Join(cwd, \"database\", \"block.db\"), os.O_APPEND|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\n\tstate := &State{\n\t\tBalances: balances.Balances,\n\t\ttxMempool: []Tx{},\n\t\tlatestBlockHash: Hash{},\n\t\tdbFile: f,\n\t}\n\n\tfor scanner.Scan() {\n\t\tif err := scanner.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar blockFs BlockFS\n\t\tblockFsJson := scanner.Bytes()\n\t\terr = json.Unmarshal(blockFsJson, &blockFs)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := state.applyBlock(blockFs.Value); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstate.latestBlockHash = blockFs.Key\n\t}\n\n\treturn state, nil\n}", "func NewTreeFromBS(bs *bitstream.BitStream) Tree {\n\troot := newTreeFromBS(bs)\n\treturn Tree{root: root}\n}", "func NewStateSync(root common.Hash, database trie.DatabaseReader) *trie.TrieSync {\n\tvar syncer *trie.TrieSync\n\tcallback := func(leaf []byte, parent common.Hash) error {\n\t\tvar obj Account\n\t\tif err := rlp.Decode(bytes.NewReader(leaf), &obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsyncer.AddSubTrie(obj.Root, 64, parent, nil)\n\t\tsyncer.AddRawEntry(common.BytesToHash(obj.CodeHash), 64, parent)\n\t\treturn nil\n\t}\n\tsyncer = trie.NewTrieSync(root, database, callback)\n\treturn syncer\n}", "func NewTree(n int) *Tree {\n\treturn &Tree{\n\t\tn: n,\n\t\tbit: make([]int, n+1),\n\t}\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\tBlock: *NewBlock(),\n\t\tTextStyle: Theme.Tree.Text,\n\t\tSelectedRowStyle: Theme.Tree.Text,\n\t\tWrapText: true,\n\t}\n}", "func NewTree(childs Childs) *Quadtree {\n\tqt, ok := nodeMap[childs]\n\tif ok {\n\t\tcacheHit++\n\t\treturn qt\n\t}\n\tcacheMiss++\n\tqt = &Quadtree{childs.NE.Level + 1, childs, childs.population(), nil}\n\tif qt.Population == 0 || qt.Level <= 16 {\n\t\tnodeMap[childs] = qt\n\t}\n\treturn qt\n}", "func New(opts ...TreeOption) *Tree {\n\tt := &Tree{}\n\tfor _, opt := range opts {\n\t\topt(t)\n\t}\n\tt.init()\n\treturn t\n}", "func New() *Tree {\n\treturn &Tree{root: &node{}}\n}", "func New(name string) *Tree {\n\ttr := new(Tree)\n\ttr.Name = name\n\treturn tr\n}", "func CreateNodeState(nodeId int32, money int64) string {\n\treturn fmt.Sprintf(\"node %d = %d\\n\", nodeId, money)\n}", "func MakeTree(baseDirectory string, actions []Action, dump io.Writer) error {\n\tvar ran []LogEntry\n\n\tlogRan := func(baseDirectory string, action Action) {\n\t\tran = append(ran, LogEntry{baseDirectory, action})\n\t}\n\n\tif err := doTree(baseDirectory, actions, dump, logRan); err != nil {\n\t\trollbackTree(baseDirectory, ran, dump)\n\t\treturn errors.New(\"error on making a tree: \" + err.Error())\n\t} else {\n\t\treturn nil\n\t}\n}", "func NewBuildState(config *Configuration) *BuildState {\n\tgraph := NewGraph()\n\tstate := &BuildState{\n\t\tGraph: graph,\n\t\tpendingParses: make(chan ParseTask, 10000),\n\t\tpendingActions: make(chan Task, 1000),\n\t\thashers: map[string]*fs.PathHasher{\n\t\t\t// For compatibility reasons the sha1 hasher has no suffix.\n\t\t\t\"sha1\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, sha1.New, \"sha1\"),\n\t\t\t\"sha256\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, sha256.New, \"sha256\"),\n\t\t\t\"crc32\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newCRC32, \"crc32\"),\n\t\t\t\"crc64\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newCRC64, \"crc64\"),\n\t\t\t\"blake3\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newBlake3, \"blake3\"),\n\t\t\t\"xxhash\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newXXHash, \"xxhash\"),\n\t\t},\n\t\tProcessExecutor: executorFromConfig(config),\n\t\tStartTime: startTime,\n\t\tConfig: config,\n\t\tRepoConfig: config,\n\t\tVerifyHashes: true,\n\t\tNeedBuild: true,\n\t\tXattrsSupported: config.Build.Xattrs,\n\t\tCoverage: TestCoverage{Files: map[string][]LineCoverage{}},\n\t\tTargetArch: config.Build.Arch,\n\t\tArch: cli.HostArch(),\n\t\tstats: &lockedStats{},\n\t\tprogress: &stateProgress{\n\t\t\tnumActive: 1, // One for the initial target adding on the main thread.\n\t\t\tnumPending: 1,\n\t\t\tpendingTargets: cmap.New[BuildLabel, chan struct{}](cmap.DefaultShardCount, hashBuildLabel),\n\t\t\tpendingPackages: cmap.New[packageKey, chan struct{}](cmap.DefaultShardCount, hashPackageKey),\n\t\t\tpackageWaits: cmap.New[packageKey, chan struct{}](cmap.DefaultShardCount, hashPackageKey),\n\t\t\tinternalResults: make(chan *BuildResult, 1000),\n\t\t\tcycleDetector: cycleDetector{graph: graph},\n\t\t},\n\t\tinitOnce: new(sync.Once),\n\t\tpreloadDownloadOnce: new(sync.Once),\n\t}\n\n\tstate.PathHasher = state.Hasher(config.Build.HashFunction)\n\tstate.progress.allStates = []*BuildState{state}\n\tstate.Hashes.Config = config.Hash()\n\tfor _, exp := range config.Parse.ExperimentalDir {\n\t\tstate.experimentalLabels = append(state.experimentalLabels, BuildLabel{PackageName: exp, Name: \"...\"})\n\t}\n\tgo state.forwardResults()\n\treturn state\n}", "func newTapestry(tap *tapestry.Node, zkAddr string) (*Tapestry, error) {\n\t//TODO: Setup a zookeeper connection and return a Tapestry struct\n\tconn, err := connectZk(zkAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texists, _, err := conn.Exists(\"/tapestry\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error: zookeeper fail to find target, reason is %v\", err)\n\t}\n\tif !exists {\n\t\t_, err = conn.Create(\"/tapestry\", nil, 0, zk.WorldACL(zk.PermAll))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// Tapestry register them in ZooKeeper\n\t// we will simply use file paths as unique IDs for files and directories.\n\terr = createEphSeq(conn, filepath.Join(\"/tapestry\", tap.Addr()), []byte(tap.Addr()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Tapestry{\n\t\ttap: tap,\n\t\tzk: conn,\n\t}, nil\n}", "func GitTreeState() string { return gitTreeState }", "func newObject(db *StateDB, address common.Address, data model.StateAccount) *stateObject {\n\tif data.Balance == nil {\n\t\tdata.Balance = new(big.Int)\n\t}\n\tif data.CodeHash == nil {\n\t\tdata.CodeHash = emptyCodeHash\n\t}\n\tif data.Root == (common.Hash{}) {\n\t\tdata.Root = emptyRoot\n\t}\n\treturn &stateObject{\n\t\tdb: db,\n\t\taddress: address,\n\t\taddrHash: crypto.Keccak256Hash(address[:]),\n\t\tdata: data,\n\t\toriginStorage: make(Storage),\n\t\tpendingStorage: make(Storage),\n\t\tdirtyStorage: make(Storage),\n\t}\n}", "func New() *binaryTree {\n\treturn CreateDefaultTree()\n}", "func newObject(db *StateDB, key math.Hash, data meta.Account) *StateObject {\n\treturn &StateObject{\n\t\tdb: db,\n\t\tkey: key,\n\t\tdata: data,\n\t\toriginStorage: make(Storage),\n\t\tdirtyStorage: make(Storage),\n\t}\n}", "func CreateTree(parties []int, B int, lambda int) []Node {\n\tnodes := make([]Node, (2*B)-1) //create length based on B\n\tfor i := 0; i < len(nodes); i++ {\n\t\tpath, nonces := CreatePath(parties, int(math.Pow(math.Log2(float64(lambda)), 2))) //use path for each node\n\t\tnodes[i].Path = path\n\t\tnodes[i].Nonces = nonces\n\t\t//assigns nodes\n\t}\n\tfactor := 0 //this makes the right parent index\n\tpivotNode := CalculatePivotNode(B)\n\tfor i := 0; i < pivotNode; i++ {\n\t\tnodes[i].Parent = &nodes[B+factor] //so the parent is the right node, and last is null\n\t\tif i%2 == 1 {\n\t\t\tfactor += 1\n\t\t}\n\t}\n\treturn nodes\n\n}", "func NewState() *State {\n\treturn &State{\n\t\tProblem: make(Problem),\n\t\tSolution: make(Solution),\n\t\tDependees: make(StringGraph),\n\t}\n}", "func (m *MockLogic) StateTree() tree.Tree {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateTree\")\n\tret0, _ := ret[0].(tree.Tree)\n\treturn ret0\n}", "func New(options ...TreeOpt) (*Tree, error) {\n\ttmp := tree{obj: Tree{\n\t\talgorithm: hash.Default,\n\t\tmaxLevel: defaultMaxLevel,\n\t}}\n\n\tfor _, setter := range options {\n\t\tif err := tmp.setOption(setter); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &tmp.obj, nil\n}", "func (m *MockAtomicLogic) StateTree() tree.Tree {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateTree\")\n\tret0, _ := ret[0].(tree.Tree)\n\treturn ret0\n}", "func ConstructState(store adt.Store, rootKeyAddress addr.Address) (*State, error) {\n\temptyMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"failed to create empty map: %w\", err)\n\t}\n\n\treturn &State{\n\t\tRootKey: rootKeyAddress,\n\t\tVerifiers: emptyMapCid,\n\t\tVerifiedClients: emptyMapCid,\n\t\tRemoveDataCapProposalIDs: emptyMapCid,\n\t}, nil\n}", "func NewTree(options *Options) *Tree {\n\tif options == nil {\n\t\toptions = new(Options)\n\t}\n\tsetDefaultOptions(options)\n\n\tidx := &Tree{\n\t\tnewBlocks: make(chan int),\n\t\tdone: make(chan bool),\n\t\tblockMap: make(map[int]int),\n\t\tmanager: newEpochManager(options.NumAllocators),\n\t}\n\n\tidx.allocators = make([]*Allocator, options.NumAllocators)\n\tidx.allocatorQueue = newSlots(len(idx.allocators))\n\tfor i := range idx.allocators {\n\t\tidx.allocators[i] = newAllocator(idx, i, blockSize, idx.newBlocks)\n\t}\n\tgo idx.blockAllocator()\n\treturn idx\n}", "func CreateState() *State {\n\treturn &State{\n\t\tVars: make(map[string]string),\n\t}\n}", "func NewOrderTree(orderDB *BatchDatabase, key []byte, orderBook *Orderbook) *OrderTree {\n\t// create priceTree from db for order list\n\t// orderListDBPath := path.Join(datadir, \"pricetree\")\n\t// orderDBPath := path.Join(datadir, \"order\")\n\tpriceTree := NewRedBlackTreeExtended(orderDB)\n\t// priceTree.Debug = orderDB.Debug\n\n\t// itemCache, _ := lru.New(defaultCacheLimit)\n\t// orderDB, _ := ethdb.NewLDBDatabase(orderDBPath, 0, 0)\n\n\titem := &OrderTreeItem{\n\t\tVolume: Zero(),\n\t\tNumOrders: 0,\n\t\t// Depth: 0,\n\t\tPriceTreeSize: 0,\n\t}\n\n\tslot := new(big.Int).SetBytes(key)\n\n\t// we will need a lru for cache hit, and internal cache for orderbook db to do the batch update\n\torderTree := &OrderTree{\n\t\torderDB: orderDB,\n\t\tPriceTree: priceTree,\n\t\tKey: key,\n\t\tslot: slot,\n\t\tItem: item,\n\t\torderBook: orderBook,\n\t\t// orderListCache: itemCache,\n\t}\n\n\t// must restore from db first to make sure we get corrent information\n\t// orderTree.Restore()\n\t// then update PriceTree after restore the order tree\n\n\t// update price tree\n\t// orderTree.PriceTree = priceTree\n\t// orderTree.Key = GetKeyFromBig(orderTree.slot)\n\treturn orderTree\n}", "func (bpt *BplusTree) treeNodeInit(isLeaf bool, next common.Key, prev common.Key,\n\tinitLen int) *treeNode {\n\n\tnode := defaultAlloc()\n\tnode.Children = make([]treeNodeElem, initLen, bpt.context.maxDegree)\n\tnode.IsLeaf = isLeaf\n\tnode.NextKey = next\n\tnode.PrevKey = prev\n\t// Generate a new key for the node being added.\n\tnode.NodeKey = common.Generate(bpt.context.keyType, bpt.context.pfx)\n\treturn node\n}", "func constructTreeNode(requestPathParts []string, nodePathIndex int) (*TreeNode, error) {\n\tnewNodeUUID, uuidErr := genUUID()\n\tif uuidErr != nil {\n\t\treturn nil, uuidErr\n\t}\n\ttreeNode := TreeNode{level: nodePathIndex, uuid: newNodeUUID, value: requestPathParts[nodePathIndex], parent: nil}\n\n\tif len(requestPathParts) > nodePathIndex+1 {\n\t\tchildNode, childErr := constructTreeNode(requestPathParts, nodePathIndex+1)\n\t\tif childErr != nil {\n\t\t\treturn nil, childErr\n\t\t}\n\n\t\ttreeNode.addChild(nil, childNode)\n\t}\n\n\treturn &treeNode, nil\n}", "func NewStateSync(root common.Hash, database trie.DatabaseReader) *trie.Sync {\n\tvar syncer *trie.Sync\n\tcallback := func(leaf []byte, parent common.Hash) error {\n\t\treturn nil\n\t}\n\tsyncer = trie.NewSync(root, database, callback)\n\treturn syncer\n}", "func BTreeCreate(t int) *BTree {\n\t// create null node to use as place filler\n\tnullNode := &BTreeNode{}\n\tfor i := 0; i < 2*t; i++ {\n\t\tnullNode.children = append(nullNode.children, nullNode)\n\t}\n\n\t// create the tree\n\ttree := BTree{\n\t\tt: t,\n\t\tnullNode: nullNode,\n\t}\n\n\t// create root node\n\tx := tree.AllocateNode()\n\tx.leaf = true\n\ttree.root = x\n\n\t// create null node used to auto-populate children of newly allocated nodes\n\ttree.nullNode = tree.AllocateNode()\n\n\t// *Here is where we'd write the new node to disk\n\treturn &tree\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\troot, leafs, err := buildWithContent(cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &MerkleTree{\n\t\tRoot: root,\n\t\tmerkleRoot: root.Hash,\n\t\tLeafs: leafs,\n\t}\n\treturn t, nil\n}", "func NewTree(rootName string, builder caching.TreeBuilder, updater caching.TreeUpdater,\n\tlocker caching.Locker) (*Tree, error) {\n\troot := &caching.Node{\n\t\tName: rootName,\n\t\tLeaf: false,\n\t\tSize: int64(0),\n\t\tChildren: []*caching.Node{},\n\t}\n\n\tnodes := map[string]*caching.Node{rootName: root}\n\ttree := &Tree{\n\t\tRootName: rootName,\n\t\tnodes: nodes,\n\t\tbuilder: builder,\n\t\tupdater: updater,\n\t\tlocker: locker,\n\t\tBulkUpdates: 100,\n\t\tUpdateRoutines: 10,\n\t}\n\terr := tree.AddNode(rootName, root)\n\treturn tree, err\n}", "func InitTree(symbol Symbol) (*Tree, error) {\n\thandler, err := getHandler(symbol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Tree{symbol, make([]*Tree, 0, maxChildren), handler}, nil\n}", "func newGenState() *genState {\n\treturn &genState{\n\t\t// Mark the name that is used for the binary type as a reserved name\n\t\t// within the output structs.\n\t\tdefinedGlobals: map[string]bool{\n\t\t\tygot.BinaryTypeName: true,\n\t\t\tygot.EmptyTypeName: true,\n\t\t},\n\t\tuniqueDirectoryNames: make(map[string]string),\n\t\tuniqueEnumeratedTypedefNames: make(map[string]string),\n\t\tuniqueIdentityNames: make(map[string]string),\n\t\tuniqueEnumeratedLeafNames: make(map[string]string),\n\t\tuniqueProtoMsgNames: make(map[string]map[string]bool),\n\t\tuniqueProtoPackages: make(map[string]string),\n\t\tgeneratedUnions: make(map[string]bool),\n\t}\n}", "func New() *VersionTree {\n\treturn &VersionTree{}\n}", "func (t *Tree) NewTreeNode(parent *TreeNode, step Step, pass bool, side Value, first bool) *TreeNode {\n\te := &TreeNode{\n\t\tt: t,\n\t\tside: side,\n\t\tstep: step,\n\t\tpass: pass,\n\t\tparent: parent,\n\t\tpolicy: policyPool.Get().([]float32),\n\t\tfirst: first,\n\t}\n\treturn e\n}", "func (tree *Tree23) initializeTree(capacity int) {\n\n\ttree.root = 0\n\n\ttree.oneElemTreeList = []TreeNodeIndex{-1}\n\ttree.twoElemTreeList = []TreeNodeIndex{-1, -1}\n\ttree.threeElemTreeList = []TreeNodeIndex{-1, -1, -1}\n\ttree.nineElemTreeList = []TreeNodeIndex{-1, -1, -1, -1, -1, -1, -1, -1, -1}\n\n\ttree.treeNodes = make([]treeNode, capacity, capacity)\n\tfor i := 0; i < len(tree.treeNodes); i++ {\n\t\tvar a [3]treeLink\n\t\ttree.treeNodes[i] = treeNode{a, 0, nil, -1, -1}\n\t}\n\ttree.treeNodesFirstFreePos = 1\n\ttree.treeNodesFreePositions = make(stack, 0, 0)\n}", "func newAlohaTree(t *testing.T, db dbm.DB) (*iavl.MutableTree, types.CommitID) {\n\tt.Helper()\n\ttree := iavl.NewMutableTree(db, cacheSize, false, log.NewNopLogger())\n\n\tfor k, v := range treeData {\n\t\t_, err := tree.Set([]byte(k), []byte(v))\n\t\trequire.NoError(t, err)\n\t}\n\n\tfor i := 0; i < nMoreData; i++ {\n\t\tkey := randBytes(12)\n\t\tvalue := randBytes(50)\n\t\t_, err := tree.Set(key, value)\n\t\trequire.NoError(t, err)\n\t}\n\n\thash, ver, err := tree.SaveVersion()\n\trequire.Nil(t, err)\n\n\treturn tree, types.CommitID{Version: ver, Hash: hash}\n}", "func TreeStoreNew(types ...glib.Type) *TreeStore {\n\tgtypes := C.alloc_types(C.int(len(types)))\n\tfor n, val := range types {\n\t\tC.set_type(gtypes, C.int(n), C.GType(val))\n\t}\n\tdefer C.g_free(C.gpointer(gtypes))\n\tc := C.gtk_tree_store_newv(C.gint(len(types)), gtypes)\n\treturn wrapTreeStore(unsafe.Pointer(c))\n}", "func NewTree(width int, company string) *Tree {\n\theight := width / 2\n\n\tleaves := make([][]string, height)\n\n\tfor i := 0; i < height; i++ {\n\t\tleaves[i] = newLevelLeaves(width, \" \")\n\t\tif i == 0 {\n\t\t\tleaves[i][width/2] = \"★\"\n\t\t\tcontinue\n\t\t}\n\n\t\tleaves[i][height-i] = \"/\"\n\t\tleaves[i][height+i] = \"\\\\\"\n\t\tfor j := (height - i + 1); j < height+i; j++ {\n\t\t\tleaves[i][j] = leafContent()\n\t\t}\n\t}\n\n\tleaves = append(leaves, bottomLeaves(width, \"^\"), bottomLeaves(width, \" \"))\n\n\treturn &Tree{\n\t\tleaves: leaves,\n\t\tcompany: company,\n\t}\n}", "func NewState(username string) *State {\n\treturn &State{\n\t\tUsername: username,\n\t\tURL: fmt.Sprintf(\"https://aggr.md/@%s.json\", username),\n\t}\n}", "func createNewState(state int, at map[int]map[uint8]int) {\n at[state] = make(map[uint8]int)\n if debugMode==true {\n fmt.Printf(\"\\ncreated state %d\", state)\n }\n}", "func newState(digest string, blob remote.Blob) *state {\n\treturn &state{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tstatFile: &statFile{\n\t\t\tNode: nodefs.NewDefaultNode(),\n\t\t\tname: digest + \".json\",\n\t\t\tstatJSON: statJSON{\n\t\t\t\tDigest: digest,\n\t\t\t\tSize: blob.Size(),\n\t\t\t},\n\t\t\tblob: blob,\n\t\t},\n\t}\n}", "func (tp *Trie) NewState() *State {\n\ts := &State{\n\t\tID: tp.StatesCount,\n\t\tSuccess: map[rune]*State{},\n\t}\n\ttp.StatesCount++\n\treturn s\n}", "func New() Tree {\n\treturn &Node{Value: \".\"}\n}", "func (treeNode *TreeNode) New(node Item) (*TreeNode, error) {\n\tif treeNode != nil {\n\t\treturn nil, errors.New(\"treeNode must be nil\")\n\t}\n\ttreeNode = &TreeNode{\n\t\tLeft: nil,\n\t\tRight: nil,\n\t\tValue: node,\n\t}\n\treturn treeNode, nil\n}", "func NewString() *Tree {\n\ttree := &Tree{\n\t\tdatatype: containers.StringContainer(\"A\"),\n\t}\n\t// The below handling is required to achieve method overriding.\n\t// Refer: https://stackoverflow.com/questions/38123911/golang-method-override\n\ttree.TreeOperations = interface{}(tree).(binarytrees.TreeOperations)\n\treturn tree\n}", "func (dTreeOp DirTreeOp) New() DirTreeOp {\n newDTreeOp := DirTreeOp{}\n newDTreeOp.ErrReturns = make([]error, 0, 100)\n return newDTreeOp\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\tvar defaultHashStrategy = \"sha256\"\n\tt := &MerkleTree{\n\t\tHashStrategy: defaultHashStrategy,\n\t}\n\troot, leafs, err := buildWithContent(cs, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Root = root\n\tt.Leafs = leafs\n\tt.MerkleRoot = root.Hash\n\treturn t, nil\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func NewBST() *BSTree {\n\treturn &BSTree{nil}\n}", "func newDemoTree() TreeRoot {\n\tn1 := newNode(1)\n\n\tn2 := newNode(2)\n\tn1.Left = n2\n\n\tn3 := newNode(3)\n\tn1.Right = n3\n\n\tn4 := newNode(4)\n\tn2.Left = n4\n\n\tn5 := newNode(5)\n\tn2.Right = n5\n\n\tn6 := newNode(6)\n\tn3.Left = n6\n\n\tn7 := newNode(7)\n\tn3.Right = n7\n\n\tn8 := newNode(8)\n\tn4.Left = n8\n\n\tn9 := newNode(9)\n\tn4.Right = n9\n\n\tn10 := newNode(10)\n\tn5.Left = n10\n\n\tn11 := newNode(11)\n\tn5.Right = n11\n\n\tn12 := newNode(12)\n\tn6.Left = n12\n\n\tn13 := newNode(13)\n\tn6.Right = n13\n\n\tn14 := newNode(14)\n\tn7.Left = n14\n\n\tn15 := newNode(15)\n\tn7.Right = n15\n\n\tn16 := newNode(16)\n\tn14.Left = n16\n\n\tn17 := newNode(17)\n\tn14.Right = n17\n\n\treturn n1\n}", "func New(ctx context.Context, client *http.Client, projectName string) (*tree.FS, error) {\n\tp, err := newGithubProject(ctx, client, projectName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstart := time.Now()\n\tt, err := p.getTree(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"Loaded project with %d files in %.1fs\", len(t), time.Now().Sub(start).Seconds())\n\treturn tree.NewFS(t), nil\n}", "func MigrateStateTree(ctx context.Context, store cbor.IpldStore, stateRootIn cid.Cid) (cid.Cid, error) {\n\t// Setup input and output state tree helpers\n\tadtStore := adt.WrapStore(ctx, store)\n\tactorsIn, err := states0.LoadTree(adtStore, stateRootIn)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tstateRootOut, err := adt.MakeEmptyMap(adtStore).Root()\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tactorsOut, err := states.LoadTree(adtStore, stateRootOut)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\t// Extra setup\n\t// miner\n\tvar p phoenix\n\tif err := p.load(ctx, actorsIn); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\t// power\n\tpm := migrations[builtin0.StoragePowerActorCodeID].StateMigration.(*powerMigrator)\n\tpm.actorsIn = actorsIn\n\n\t// Iterate all actors in old state root\n\t// Set new state root actors as we go\n\tif err = actorsIn.ForEach(func(addr address.Address, actorIn *states.Actor) error {\n\t\tmigration := migrations[actorIn.Code]\n\n\t\t// This will be migrated at the end\n\t\tif actorIn.Code == builtin0.VerifiedRegistryActorCodeID {\n\t\t\treturn nil\n\t\t}\n\t\theadOut, transfer, err := migration.StateMigration.MigrateState(ctx, store, actorIn.Head, actorIn.Balance)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"state migration error on %s actor at addr %s: %w\", builtin.ActorNameByCode(migration.OutCodeCID), addr, err)\n\t\t}\n\n\t\t// set up new state root with the migrated state\n\t\tactorOut := states.Actor{\n\t\t\tCode: migration.OutCodeCID,\n\t\t\tHead: headOut,\n\t\t\tCallSeqNum: actorIn.CallSeqNum,\n\t\t\tBalance: big.Add(actorIn.Balance, transfer),\n\t\t}\n\t\tif err = p.transfer(transfer); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn actorsOut.SetActor(addr, &actorOut)\n\t}); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\t// // Migrate verified registry\n\tvm := migrations[builtin0.VerifiedRegistryActorCodeID].StateMigration.(*verifregMigrator)\n\tvm.actorsOut = actorsOut\n\tverifRegActorIn, found, err := actorsIn.GetActor(builtin0.VerifiedRegistryActorAddr)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tif !found {\n\t\treturn cid.Undef, xerrors.Errorf(\"could not find verifreg actor in state\")\n\t}\n\tverifRegHeadOut, transfer, err := vm.MigrateState(ctx, store, verifRegActorIn.Head, verifRegActorIn.Balance)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tverifRegActorOut := states.Actor{\n\t\tCode: builtin.VerifiedRegistryActorCodeID,\n\t\tHead: verifRegHeadOut,\n\t\tCallSeqNum: verifRegActorIn.CallSeqNum,\n\t\tBalance: big.Add(verifRegActorIn.Balance, transfer),\n\t}\n\tif err = p.transfer(transfer); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tif err := actorsOut.SetActor(builtin.VerifiedRegistryActorAddr, &verifRegActorOut); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\t// Track deductions to burntFunds actor's balance\n\tif err := p.flush(ctx, actorsOut); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\treturn actorsOut.Flush()\n}", "func NewTree(depth int) *Tree {\n\tif depth > 0 {\n\t\treturn &Tree{Left: NewTree(depth - 1), Right: NewTree(depth - 1)}\n\t} else {\n\t\treturn &Tree{}\n\t}\n}", "func createBinaryTree(rootAddress **BinaryTreeNode) {\n\troot := newBinaryTreeNode(4)\n\troot.Left = newBinaryTreeNode(2)\n\troot.Left.Left = newBinaryTreeNode(1)\n\troot.Left.Right = newBinaryTreeNode(3)\n\troot.Right = newBinaryTreeNode(6)\n\troot.Right.Left = newBinaryTreeNode(5)\n\troot.Right.Right = newBinaryTreeNode(8)\n\troot.Left.Left.Left = newBinaryTreeNode(0)\n\troot.Right.Right.Left = newBinaryTreeNode(7)\n\n\t*rootAddress = root\n}", "func NewTree(fs []SymbolFreq) Tree {\n\t// Sort frequencies\n\tsort.Sort(byFreq(fs))\n\n\twrkList := []node{}\n\tfor _, f := range fs {\n\t\twrkList = append(wrkList, f)\n\t}\n\n\tfor {\n\t\tif len(wrkList) < 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tnewNode := makeNewNode(wrkList[0], wrkList[1])\n\n\t\twrkList = insertItem(wrkList[2:], newNode)\n\t}\n\n\treturn Tree{wrkList[0]}\n}", "func NewTree(r RuleHandle) (*Tree, error) {\n\tif r.Detection == nil {\n\t\treturn nil, ErrMissingDetection{}\n\t}\n\texpr, ok := r.Detection[\"condition\"].(string)\n\tif !ok {\n\t\treturn nil, ErrMissingCondition{}\n\t}\n\n\tp := &parser{\n\t\tlex: lex(expr),\n\t\tcondition: expr,\n\t\tsigma: r.Detection,\n\t\tnoCollapseWS: r.NoCollapseWS,\n\t}\n\tif err := p.run(); err != nil {\n\t\treturn nil, err\n\t}\n\tt := &Tree{\n\t\tRoot: p.result,\n\t\tRule: &r,\n\t}\n\treturn t, nil\n}", "func newStudentState(content *Content) *studentState {\n\tstate := &studentState{content: content}\n\tstate.reset()\n\treturn state\n}", "func (p *Contentity) st2b_BuildIntoTree() *Contentity {\n\tif p.HasError() {\n\t\treturn p\n\t}\n\tvar e error\n\tp.GTree, e = gtree.NewGTreeFromGTags(p.GTags)\n\tif e != nil {\n\t\tprintln(\"==> mcfl.st2b: Error!:\", e.Error())\n\t\tp.WrapError(\"NewGTreeFromGTags\", e)\n\t\treturn p\n\t}\n\tif p.GTree == nil {\n\t\tprintln(\"==> mcfl.st2b: got nil Gtree: %s\", e.Error())\n\t\tp.WrapError(\"nil tree from NewGTreeFromGTags\", e)\n\t}\n\tif p.GTree != nil && p.GTreeWriter != nil &&\n\t\tp.GTreeWriter != io.Discard {\n\t\tgtoken.DumpTo(p.GTokens, p.GTreeWriter)\n\t} else {\n\t\tgtoken.DumpTo(p.GTokens, os.Stdout)\n\t}\n\treturn p\n}", "func New(dgree int, ctx interface{}) *BTree {\n\treturn NewWithFreeList(degree, NewFreeList(DefaultFreeListSize), ctx)\n}", "func newt(terms []string) Tree {\n\tkvs := make([]kv, 0, len(terms))\n\tfor i, k := range terms {\n\t\tkvs = append(kvs, kv{[]byte(k), i})\n\t}\n\tsort.Slice(kvs, func(i, j int) bool {\n\t\ta, b := kvs[i].k, kvs[j].k\n\t\tfor i := 0; i < len(a) && i < len(b); i++ {\n\t\t\tif a[i] == b[i] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn a[i] < b[i]\n\t\t}\n\t\treturn len(a) < len(b)\n\t})\n\n\tt := Tree{node{next: 1}}\n\n\tt = t.construct(kvs, 0, 0)\n\treturn t\n}", "func New() Tree {\n\treturn &binarySearchTree{}\n}", "func buildTree(preorder []int, inorder []int) *TreeNode {\n\t// 先判断长度,返回空的情况\n\tif len(preorder) == 0 || len(inorder) == 0 {\n\t\treturn nil\n\t}\n\t// 从preorder里面找到根节点的坐标,然后做拆分\n\tidx := getIdx(inorder, preorder[0])\n\n\t// 递归构造树\n\troot := &TreeNode{\n\t\tVal: preorder[0],\n\t\tLeft: buildTree(preorder[1:idx+1], inorder[:idx]),\n\t\tRight: buildTree(preorder[idx+1:], inorder[idx+1:]),\n\t}\n\treturn root\n}", "func NewTreeNode(d int) *TreeNode {\n\treturn &TreeNode{\n\t\tdata: d,\n\t\tsize: 1,\n\t}\n}", "func NewBSTree() *BSTree {\n\tb := &BSTree{\n\t\tleft: &BSTree{},\n\t\tright: &BSTree{},\n\t}\n\treturn b\n}", "func (pm *PathMap) _createTree(path []string) *PathMap {\n\ttree := pm\n\tfor _, component := range path {\n\t\tsubtree, ok := tree.dirs[component]\n\t\tif ok {\n\t\t\t// The component already exists. Unshare it so that\n\t\t\t// it can be modified without messing with other PathMaps\n\t\t\tsubtree = subtree._unshare()\n\t\t} else {\n\t\t\t// Create the component as a directory\n\t\t\tsubtree = newPathMap()\n\t\t}\n\t\t// Put the new or snapshot tree in place, and go down a level\n\t\ttree.dirs[component] = subtree\n\t\ttree = subtree\n\t}\n\treturn tree\n}" ]
[ "0.6912023", "0.6191913", "0.6073148", "0.60606235", "0.6037155", "0.59091216", "0.58979636", "0.58852684", "0.5877665", "0.5856578", "0.583802", "0.5774494", "0.5756803", "0.57559043", "0.5738696", "0.5727683", "0.5727124", "0.5712563", "0.5702321", "0.56940013", "0.5655744", "0.56385726", "0.56345934", "0.56321985", "0.5622304", "0.56064886", "0.56003165", "0.5597568", "0.5590963", "0.5575393", "0.5561368", "0.5539236", "0.5537224", "0.5513302", "0.54868394", "0.5485376", "0.5480623", "0.54600066", "0.5451722", "0.5449684", "0.54488575", "0.5421222", "0.54113716", "0.54060936", "0.5401457", "0.5393409", "0.53910464", "0.5380275", "0.5362926", "0.53515744", "0.53482693", "0.5323391", "0.5316233", "0.53147906", "0.52998525", "0.5297487", "0.52868015", "0.52810615", "0.5279192", "0.52777797", "0.5265121", "0.52641", "0.5260487", "0.52574235", "0.52524614", "0.5248247", "0.5245588", "0.5229439", "0.52266645", "0.5224337", "0.5210951", "0.51858914", "0.5185389", "0.5179666", "0.5179659", "0.51763254", "0.5174438", "0.51735127", "0.51676667", "0.5164829", "0.51591676", "0.51559013", "0.5141789", "0.51385206", "0.5137637", "0.5136117", "0.51336616", "0.5129997", "0.5123709", "0.5117777", "0.51100326", "0.51096815", "0.5109246", "0.5088807", "0.50872225", "0.50785553", "0.5072015", "0.50713056", "0.5065567", "0.5056995" ]
0.8084078
0
Len returns the current number of items in the tree It needs to query all allocators for their counters, so it will block if an allocator is constantly reserved...
Len возвращает текущее количество элементов в дереве. Для этого ему необходимо запросить у всех аллокаторов их счётчики, поэтому он будет блокироваться, если аллокатор постоянно зарезервирован...
func (idx *Tree) Len() (count int) { idx.Stop() count = int(idx.liveObjects) for _, a := range idx.allocators { count += int(a.itemCounter) } idx.Start() return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Tree) Len() int { return t.Count }", "func (s *Pool) Len() int { return int(atomic.LoadUint32(&s.avail)) }", "func (t *BinaryTree) Size() int { return t.count }", "func (t *Tree) Len() int {\n\treturn t.Count\n}", "func (h ReqHeap) Len() int { return len(h) }", "func (p NodePools) Len() int { return len(p) }", "func (r *Root) Len() uint64 {\n\treturn r.count\n}", "func (this *Manager) GetNodesLen() int {\n\treturn len(this.nodes)\n}", "func (s *orderedSynchronizer) Len() int {\n\treturn len(s.heap)\n}", "func (h PerformanceHeap) Len() int { return len(h.items) }", "func (h *Heap) Len() int { return len(h.slice) }", "func (n Nodes) Len() int", "func (buf *queueBuffer) Len() uint64 {\n\treturn buf.depth\n}", "func (r *RlogcHeap) Len() int { return r.queue.Len() }", "func (o *OrderedSynchronizer) Len() int {\n\treturn len(o.heap)\n}", "func (tree *BTree) Length() int {\n\tif tree.isset {\n\t\tif tree.length == 0 {\n\t\t\ttree.length = tree.uncachedLength()\n\t\t}\n\t\treturn tree.length\n\t}\n\treturn 0\n}", "func (b *BTree) Len() int {\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\treturn int(b.rootNod.GetLength())\n}", "func (t *Trie) Len() uint32 {\n\tif t.root == nil {\n\t\treturn 0\n\t}\n\treturn t.root.count\n}", "func (t *Tree) Size() uint {\n\tif t.Safe {\n\t\tdefer t.mtx.RUnlock()\n\t\tt.mtx.RLock()\n\t}\n\n\treturn t.size + 1\n}", "func (v ResourceNodes) Len() int {\n\treturn len(v)\n}", "func (em *eventManager) Len() int {\n\treturn len(em.heap)\n}", "func (bt *Tree) Length() int {\n\treturn bt.length\n}", "func (ri *rawItemList) len() int { return len(ri.cumSize) }", "func (bh blockHeap) Len() int {\n\treturn bh.impl.Len()\n}", "func (tree *RedBlack[K, V]) Len() int {\n\treturn tree.size\n}", "func (l *LRU) Len() int {\n\tl.lazyInit()\n\tvar len int\n\tfor i := 0; i < l.nshards; i++ {\n\t\tlen += l.shards[i].Len()\n\t}\n\treturn len\n}", "func (n *TreeBuilderNode) Size() uint64 { return n.size }", "func (c *Cache) Len() int {\n\tif c == nil {\n\t\treturn 0\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.lru.Len() + c.mfa.Len()\n}", "func (h tHeap) Len() int { return len(h) }", "func (t *RbTree[K, V]) Size() int {\n\treturn t.size\n}", "func (n nodes) Len() int { return len(n) }", "func (qi *Items) Len() int {\n\tqi.RLock()\n\tc := qi.Length\n\tlog.Printf(\"queue length: %d\\n\", c)\n\tqi.RUnlock()\n\treturn c\n}", "func (rb *RingBuffer[T]) Len() int {\n\tif rb == nil {\n\t\treturn 0\n\t}\n\trb.mu.Lock()\n\tdefer rb.mu.Unlock()\n\treturn len(rb.buf)\n}", "func (pool GenePool) Len() int {\n return len(pool)\n}", "func (tr *Tree) Len() int {\n\treturn tr.len\n}", "func (t *TrieNode) Len() int {\n\tt.mx.RLock()\n\tdefer t.mx.RUnlock()\n\treturn t.LenHelper()\n}", "func (fib *Fib) Len() int {\n\treturn fib.tree.CountEntries()\n}", "func (seq *Sequence) Len() int { return len(seq.Nodes) }", "func (q *Queue) Len() int {\n\tlength := 0\n\n\tfor _, current := range q.Items {\n\t\tif !current.IsReserved() {\n\t\t\tlength++\n\t\t}\n\t}\n\n\treturn length\n}", "func (ms *memoryStore) Len() int {\n\treturn len(ms.namespaces)\n}", "func (ac *AuthContext) Len() int {\n\tl := 1\n\tif ac.Parent != nil {\n\t\tl += ac.Parent.Len()\n\t}\n\treturn l\n}", "func (m *SplitNode_Children) Len() int {\n\tif m.Dense != nil {\n\t\tn := 0\n\t\tm.ForEach(func(_ int, _ int64) bool { n++; return true })\n\t\treturn n\n\t}\n\treturn len(m.Sparse)\n}", "func (l *semaphoreList) length() int {\n\tl.RLock()\n\tdefer l.RUnlock()\n\tlength := len(l.list)\n\treturn length\n}", "func (this *List) Len() int {\n this.lock.RLock()\n this.lock.RUnlock()\n\n return len(this.counters)\n}", "func (t Tree) Size() int {\n\tif t.Symbol.Kind == NIL {\n\t\treturn 0\n\t}\n\n\tcount := 1\n\tfor _, child := range t.Children {\n\t\tif child != nil {\n\t\t\tcount += child.Size()\n\t\t}\n\t}\n\n\treturn count\n}", "func (c *Cache) len() int {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.evictList.Len()\n}", "func (r *KeyRing) Len() int {\n\treturn len(r.entities)\n}", "func (h minHeap) Len() int { return len(h) }", "func (c *LRU) Len() int {\n\treturn c.evictList.Len()\n}", "func (d *Dtrie) Size() (size int) {\n\tfor _ = range iterate(d.root, nil) {\n\t\tsize++\n\t}\n\treturn size\n}", "func (c *LruCache) Len() int {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.evictList.Len()\n}", "func (lc *LruCache) Len() uint {\n\treturn lc.LruStore.Len()\n}", "func (s *Store) Len(ctx context.Context) (int64, error) {\n\tvar nb int64\n\tif err := s.List(ctx, \"\", func(string) error {\n\t\tnb++\n\t\treturn nil\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\treturn nb, nil\n}", "func AllocatorSize() (size uint32) {\n\t// size of freeBuddiesList\n\tsize += MaxOrder * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// size of bigPagesBitmap\n\tsize += nMaps(_nBigPages) * 4\n\n\t// size of individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tsize += nMaps(nBuddies) * 4\n\t}\n\n\t// size of node pool\n\tsize += nodePoolSize()\n\n\treturn\n}", "func (h MaxHeap) Len() int { return len(h) }", "func (queue PriorityQueue) Len() int {\n\treturn queue.heap.Len()\n}", "func (r *RingT[T]) Len() int {\n\treturn int((r.head - r.tail) & r.mask)\n}", "func (p *Pool) AllocCount() int {\n\tp.RLock()\n\tdefer p.RUnlock()\n\treturn len(p.allocated)\n}", "func (t *AATree) Size() int {\n\tif t.root == nil {\n\t\treturn 0\n\t}\n\t// return t.root\n\treturn 0\n}", "func (c *LRU) Len() int {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.ll.Len()\n}", "func (tree *UTree) Size() int {\r\n\treturn tree.size\r\n}", "func (blt Bolt) Length() int {\n\tvar len int\n\tblt.db.View(func(tx *b.Tx) error { //nolint:errcheck\n\t\tlen = tx.Bucket(blt.Bucket).Stats().KeyN\n\t\treturn nil\n\t})\n\treturn len\n}", "func (lm *LevelMetadata) Len() int {\n\treturn lm.tree.Count()\n}", "func (lru *KeyLRU) Len() int {\n\treturn len(lru.m)\n}", "func (p Pool) Len() int { return len(p) }", "func (m *Manager) Len() int {\n\treturn m.hub.len()\n}", "func (ne nodeEntries) Len() int { return len(ne) }", "func (c *LRU) Len() int {\n\tc.RLock()\n\tresult := c.evictList.Len()\n\tc.RUnlock()\n\treturn result\n}", "func (nc *NvmeController) Capacity() (tb uint64) {\n\tif nc == nil {\n\t\treturn 0\n\t}\n\tfor _, n := range nc.Namespaces {\n\t\ttb += n.Size\n\t}\n\treturn\n}", "func (c *RingBuffer) Len() int {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\treturn c.len\n}", "func (s *scope) len() int {\n\tl := 0\n\tfor _, level := range s.levels {\n\t\tl += len(level.named) + len(level.init)\n\t}\n\treturn l\n}", "func (candidates *LookupCandidates) Len() int {\n\treturn len(candidates.Nodelist)\n}", "func (candidates *LookupCandidates) Len() int {\n\treturn len(candidates.Nodelist)\n}", "func (a nodesInRequestOrder) Len() int { return len(a) }", "func alloc() uint64 {\n\tvar stats runtime.MemStats\n\truntime.GC()\n\truntime.ReadMemStats(&stats)\n\t// return stats.Alloc - uint64(unsafe.Sizeof(hs[0]))*uint64(cap(hs))\n\treturn stats.Alloc\n}", "func (sm safeMap) Len() int {\n\treply := make(chan interface{})\n\tsm <- commandData{action: COUNT, result: reply}\n\treturn (<-reply).(int)\n}", "func (c *Cache) Len() int {\n\tvar len int\n\tfor _, shard := range c.shards {\n\t\tlen += shard.policy.Len()\n\t}\n\n\treturn len\n}", "func (rb *RingBuffer) Len() int {\n\trb.lock.RLock()\n\tdefer rb.lock.RUnlock()\n\tif n := len(rb.data); rb.seq < uint64(n) {\n\t\treturn int(rb.seq)\n\t} else {\n\t\treturn n\n\t}\n}", "func (q *Stack) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\treturn q.count\n}", "func (s *Stack) Len() int {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn s.count\n}", "func (ms *multiSorter) Len() int {\n\treturn len(ms.Nodes)\n}", "func (sr *Stackers) Length() int {\n\tvar l int\n\tsr.ro.Lock()\n\t{\n\t\tl = len(sr.stacks)\n\t\tsr.ro.Unlock()\n\t}\n\treturn l\n}", "func (h MinHeap) Len() int { return len(h) }", "func (sc *Scavenger) Len() int {\n\tsc.mu.Lock()\n\tn := len(sc.entries)\n\tsc.mu.Unlock()\n\treturn n\n}", "func (db *MemoryCache) Len() int {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\treturn len(db.db)\n}", "func (s *nodeSorter) Len() int {\n\treturn len(s.nodes)\n}", "func (s *stackImpl) Len() int {\n\treturn len(s.items)\n}", "func (t *BinarySearchTree) Size() int {\n\treturn 0\n}", "func (c *UnlimitedCache) Len() int {\n\treturn len(c.m)\n}", "func (q *wantConnQueue) len() int {\n\treturn len(q.head) - q.headPos + len(q.tail)\n}", "func (storage *Storage) Len() (n int) {\n\tstorage.mutex.Lock()\n\tn = storage.lruList.Len()\n\tstorage.mutex.Unlock()\n\treturn\n}", "func (node *Node) Len() int {\n\treturn node.buf.Len()\n}", "func (md MinQueue) Len() int { return len(md) }", "func (h *Heap) Len() int {\n\treturn len(h.data.queue)\n}", "func (t *TrieNode) LenHelper() int {\n\tentryCount := len(t.values)\n\tfor child := range t.children {\n\t\tentryCount += t.children[child].LenHelper()\n\t}\n\treturn entryCount\n}", "func (n *NodeSorter) Len() int {\n\treturn len(n.nodes)\n}", "func (h *hashRing) Size() int {\n\treturn len(h.nodes)\n}", "func (c Containers) Length() int {\n\treturn len(c)\n}", "func (q *queue) Len() int {\n\tq.lock.RLock()\n\tdefer q.lock.RUnlock()\n\tc := q.tail - q.head\n\tif c < 0 {\n\t\tc = 0\n\t}\n\n\treturn c\n}", "func (t *MCTS) alloc() Naughty {\n\tt.Lock()\n\tdefer t.Unlock()\n\tl := len(t.freelist)\n\tif l == 0 {\n\t\tN := Node{\n\t\t\tlock: sync.Mutex{},\n\t\t\ttree: ptrFromTree(t),\n\t\t\tid: Naughty(len(t.nodes)),\n\t\t\thasChildren: false,\n\t\t}\n\t\tt.nodes = append(t.nodes, N)\n\t\tt.children = append(t.children, make([]Naughty, 0, t.current.ActionSpace()))\n\t\tn := Naughty(len(t.nodes) - 1)\n\t\treturn n\n\t}\n\n\ti := t.freelist[l-1]\n\tt.freelist = t.freelist[:l-1]\n\treturn i\n}" ]
[ "0.6939439", "0.6840272", "0.6690427", "0.6655519", "0.6647418", "0.66106826", "0.64596206", "0.6438696", "0.64009213", "0.6397146", "0.6384905", "0.6336007", "0.6332157", "0.6309753", "0.6295182", "0.62948596", "0.62872094", "0.6268528", "0.6266187", "0.62337065", "0.6231077", "0.62103856", "0.620677", "0.61662656", "0.61635333", "0.6145804", "0.61448765", "0.6140936", "0.6130743", "0.6129027", "0.61256754", "0.6116637", "0.61157215", "0.6114252", "0.60936993", "0.60863984", "0.6082177", "0.6051007", "0.6035896", "0.60289747", "0.60203236", "0.60142094", "0.6006133", "0.6003219", "0.59928966", "0.59878474", "0.59788406", "0.59749025", "0.59655935", "0.5957082", "0.59501815", "0.5949283", "0.59476954", "0.59433067", "0.59377", "0.5921969", "0.5916688", "0.5915226", "0.59064347", "0.59056205", "0.59021556", "0.5897286", "0.5883292", "0.5881635", "0.5879257", "0.58736646", "0.58731294", "0.5866175", "0.58581936", "0.5858064", "0.5857676", "0.58573294", "0.58573294", "0.5855873", "0.5855465", "0.58548427", "0.58541745", "0.5852701", "0.5848677", "0.58457965", "0.5840112", "0.5838294", "0.5836919", "0.58256626", "0.58233106", "0.5822644", "0.5813346", "0.5812319", "0.5811154", "0.5810775", "0.5810448", "0.58101815", "0.58079267", "0.57980293", "0.5794227", "0.57879823", "0.57846475", "0.5784435", "0.5782686", "0.57822335" ]
0.8014996
0
Stop withdraws all allocators to prevent any more write or reads. It will blocks until it gets all allocators. If already stopped, it returns silently.
Stop останавливает все аллоциаторы, чтобы предотвратить любые дальнейшие записи или чтения. Он блокируется до тех пор, пока не получит все аллоциаторы. Если уже остановлен, он возвращается без вывода.
func (idx *Tree) Stop() { if !atomic.CompareAndSwapInt32(&idx.stopped, 0, 1) { return } for i := 0; i < len(idx.allocators); i++ { _ = idx.allocatorQueue.get() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (fetchers Fetchers) Stop() {\n\tfor _, fetcher := range fetchers {\n\t\tfetcher.Stop()\n\t}\n}", "func (r *reducer) stop() {\n\tfor _, m := range r.mappers {\n\t\tm.stop()\n\t}\n\tsyncClose(r.done)\n}", "func exitAllocRunner(runners ...AllocRunner) {\n\tfor _, ar := range runners {\n\t\tterminalAlloc := ar.Alloc().Copy()\n\t\tterminalAlloc.DesiredStatus = structs.AllocDesiredStatusStop\n\t\tar.Update(terminalAlloc)\n\t}\n}", "func (it *messageIterator) stop() {\n\tit.cancel()\n\tit.mu.Lock()\n\tit.checkDrained()\n\tit.mu.Unlock()\n\tit.wg.Wait()\n}", "func (c *ResourceSemaphore) stop() {\n\tcount := 0\n\n\tfor {\n\t\tselect {\n\t\tcase d := <-c.received: // wait for all resource released\n\t\t\tc.storage <- d\n\t\tcase <-c.storage:\n\t\t\tcount += 1\n\t\t\tif count == c.size {\n\t\t\t\tclose(c.endChan) // all resource released\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *Pacer) Stop() {\n\tclose(p.gate)\n}", "func (c *Context) watchStop(walker *ContextGraphWalker) (chan struct{}, <-chan struct{}) {\n\tstop := make(chan struct{})\n\twait := make(chan struct{})\n\n\t// get the runContext cancellation channel now, because releaseRun will\n\t// write to the runContext field.\n\tdone := c.runContext.Done()\n\n\tgo func() {\n\t\tdefer close(wait)\n\t\t// Wait for a stop or completion\n\t\tselect {\n\t\tcase <-done:\n\t\t\t// done means the context was canceled, so we need to try and stop\n\t\t\t// providers.\n\t\tcase <-stop:\n\t\t\t// our own stop channel was closed.\n\t\t\treturn\n\t\t}\n\n\t\t// If we're here, we're stopped, trigger the call.\n\n\t\t{\n\t\t\t// Copy the providers so that a misbehaved blocking Stop doesn't\n\t\t\t// completely hang Terraform.\n\t\t\twalker.providerLock.Lock()\n\t\t\tps := make([]ResourceProvider, 0, len(walker.providerCache))\n\t\t\tfor _, p := range walker.providerCache {\n\t\t\t\tps = append(ps, p)\n\t\t\t}\n\t\t\tdefer walker.providerLock.Unlock()\n\n\t\t\tfor _, p := range ps {\n\t\t\t\t// We ignore the error for now since there isn't any reasonable\n\t\t\t\t// action to take if there is an error here, since the stop is still\n\t\t\t\t// advisory: Terraform will exit once the graph node completes.\n\t\t\t\tp.Stop()\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\t// Call stop on all the provisioners\n\t\t\twalker.provisionerLock.Lock()\n\t\t\tps := make([]ResourceProvisioner, 0, len(walker.provisionerCache))\n\t\t\tfor _, p := range walker.provisionerCache {\n\t\t\t\tps = append(ps, p)\n\t\t\t}\n\t\t\tdefer walker.provisionerLock.Unlock()\n\n\t\t\tfor _, p := range ps {\n\t\t\t\t// We ignore the error for now since there isn't any reasonable\n\t\t\t\t// action to take if there is an error here, since the stop is still\n\t\t\t\t// advisory: Terraform will exit once the graph node completes.\n\t\t\t\tp.Stop()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn stop, wait\n}", "func (m *mapper) stop() { syncClose(m.done) }", "func (p *hardwareProfiler) Stop() error {\n\tvar err error\n\tfor _, profiler := range p.profilers {\n\t\terr = multierr.Append(err, profiler.Stop())\n\t}\n\treturn err\n}", "func Stop() {\n\tclose(configReloaderStopCh)\n\tconfigReloaderWG.Wait()\n\n\tfor _, rwctx := range rwctxsDefault {\n\t\trwctx.MustStop()\n\t}\n\trwctxsDefault = nil\n\n\t// There is no need in locking rwctxsMapLock here, since nobody should call Push during the Stop call.\n\tfor _, rwctxs := range rwctxsMap {\n\t\tfor _, rwctx := range rwctxs {\n\t\t\trwctx.MustStop()\n\t\t}\n\t}\n\trwctxsMap = nil\n\n\tif sl := hourlySeriesLimiter; sl != nil {\n\t\tsl.MustStop()\n\t}\n\tif sl := dailySeriesLimiter; sl != nil {\n\t\tsl.MustStop()\n\t}\n}", "func (collection *Collection) Stop() {\n\tfor _, c := range collection.collectors {\n\t\tc.Stop()\n\t\tcollection.wg.Done()\n\t}\n}", "func (ps *rateLimiter) Stop() { close(ps.exit) }", "func (csrl *CoalescingSerializingRateLimiter) Stop() {\n\tcsrl.lock.Lock()\n\tcsrl.stopped = true\n\tcsrl.lock.Unlock()\n\n\tfor csrl.isHandlerRunning() {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n}", "func (it *Iterator) Stop() {\n\tit.mu.Lock()\n\tdefer it.mu.Unlock()\n\n\tselect {\n\tcase <-it.closed:\n\t\t// Cleanup has already been performed.\n\t\treturn\n\tdefault:\n\t}\n\n\t// We close this channel before calling it.puller.Stop to ensure that we\n\t// reliably return Done from Next.\n\tclose(it.closed)\n\n\t// Stop the puller. Once this completes, no more messages will be added\n\t// to it.ka.\n\tit.puller.Stop()\n\n\t// Start acking messages as they arrive, ignoring ackTicker. This will\n\t// result in it.ka.Stop, below, returning as soon as possible.\n\tit.acker.FastMode()\n\n\t// This will block until\n\t// (a) it.ka.Ctx is done, or\n\t// (b) all messages have been removed from keepAlive.\n\t// (b) will happen once all outstanding messages have been either ACKed or NACKed.\n\tit.ka.Stop()\n\n\t// There are no more live messages, so kill off the acker.\n\tit.acker.Stop()\n\n\tit.kaTicker.Stop()\n\tit.ackTicker.Stop()\n}", "func (cm *CertMan) Stop() {\n\tcm.watching <- false\n}", "func (l *Launcher) Stop() {\n\tl.stop <- struct{}{}\n\tstopper := startstop.NewParallelStopper()\n\tfor identifier, tailer := range l.tailers {\n\t\tstopper.Add(tailer)\n\t\tdelete(l.tailers, identifier)\n\t}\n\tstopper.Stop()\n}", "func (b *Blinker) Stop() {\n\tclose(b.stop)\n}", "func (p *literalProcessor) stop() { syncClose(p.done) }", "func (r *reaper) stop() {\n\tr.stopCh <- struct{}{}\n}", "func (m *Manager) Stop() {\n\tclose(m.stop)\n\t<-m.stopDone\n}", "func (a *Acceptor) Stop() {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.stop <- 0\n\n}", "func (b *blocksProviderImpl) Stop() {\n\tatomic.StoreInt32(&b.done, 1)\n\tb.client.CloseSend()\n}", "func (tCertPool *tCertPoolSingleThreadImpl) Stop() (err error) {\n\n\ttCertPool.m.Lock()\n\tdefer tCertPool.m.Unlock()\n\n\tfor k := range tCertPool.tcblMap {\n\t\tcertList := tCertPool.tcblMap[k]\n\t\ttCertPool.client.ks.storeUnusedTCerts(certList.GetUnusedTCertBlocks())\n\t}\n\n\ttCertPool.client.Debug(\"Store unused TCerts...done!\")\n\n\treturn\n}", "func (sp *scrapePool) stop() {\n\tsp.mtx.Lock()\n\tdefer sp.mtx.Unlock()\n\tsp.cancel()\n\tsp.targetMtx.Lock()\n\tvar wg sync.WaitGroup\n\twg.Add(len(sp.loops))\n\tfor fp, l := range sp.loops {\n\t\tgo func(l *scrapeLoop) {\n\t\t\tl.stop()\n\t\t\twg.Done()\n\t\t}(l)\n\t\tdelete(sp.loops, fp)\n\t\tdelete(sp.activeTargets, fp)\n\t}\n\tsp.targetMtx.Unlock()\n\twg.Wait()\n\tsp.client.CloseIdleConnections()\n}", "func (m *Manager) Stop() {\n\tfor _, bot := range m.bots {\n\t\tbot.Close()\n\t}\n\n\tm.running = false\n}", "func (p *Pool) Stop() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tp.cancel()\n\tfor _, routine := range p.routines {\n\t\troutine.stop <- true\n\t}\n\tp.waitGroup.Wait()\n\tfor _, routine := range p.routines {\n\t\tclose(routine.stop)\n\t}\n}", "func (s *stateManager) Stop() {\n\tfor _, c := range s.stopChan {\n\t\tc <- true\n\t}\n\ts.cli.Close()\n}", "func (s *BufferedWriteSyncer) Stop() (err error) {\n\tvar stopped bool\n\n\t// Critical section.\n\tfunc() {\n\t\ts.mu.Lock()\n\t\tdefer s.mu.Unlock()\n\n\t\tif !s.initialized {\n\t\t\treturn\n\t\t}\n\n\t\tstopped = s.stopped\n\t\tif stopped {\n\t\t\treturn\n\t\t}\n\t\ts.stopped = true\n\n\t\ts.ticker.Stop()\n\t\tclose(s.stop) // tell flushLoop to stop\n\t\t// close(s.flush) // close flush chan\n\t\t<-s.done // and wait until it has\n\t}()\n\n\t// Don't call Sync on consecutive Stops.\n\tif !stopped {\n\t\terr = s.Sync()\n\t}\n\n\treturn err\n}", "func (dt *discoveryTool) stop() {\n\tclose(dt.done)\n\n\t//Shutdown timer\n\ttimer := time.NewTimer(time.Second * 3)\n\tdefer timer.Stop()\nL:\n\tfor { //Unblock go routine by reading from dt.dataChan\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tbreak L\n\t\tcase <-dt.dataChan:\n\t\t}\n\t}\n\n\tdt.wg.Wait()\n}", "func (rp *ResolverPool) Stop() error {\n\trp.hasBeenStopped = true\n\n\tfor _, r := range rp.Resolvers {\n\t\tr.Stop()\n\t}\n\n\trp.Resolvers = []Resolver{}\n\treturn nil\n}", "func (margelet *Margelet) Stop() {\n\tmargelet.running = false\n}", "func (w *StatsWriter) Stop() {\n\tw.stop <- struct{}{}\n\t<-w.stop\n\tstopSenders(w.senders)\n}", "func (d *Dispatcher) Stop(){\n\tfor _, w := range d.Workers {\n\t\tw.Stop()\n\t}\n}", "func (v *vtStopCrawler) stop() {\n\tfor _, worker := range v.workers {\n\t\tworker.stop()\n\t}\n\tclose(v.done)\n}", "func (wp *WorkerPool[T]) Stop() {\n\twp.mutex.Lock()\n\tif !wp.started {\n\t\twp.mutex.Unlock()\n\t\treturn\n\t}\n\n\tif !wp.stopped {\n\n\t\tfor i := 0; i < wp.numShards; i++ {\n\t\t\tshard := wp.shards[i]\n\t\t\tshard.mutex.Lock()\n\t\t\tshard.stopped = true\n\t\t\tfor j := 0; j < len(shard.idleWorkerList); j++ {\n\t\t\t\tif !shard.idleWorkerList[j].isDeleted {\n\t\t\t\t\tshard.idleWorkerList[j].isDeleted = true\n\t\t\t\t\tclose(shard.idleWorkerList[j].taskChan)\n\t\t\t\t}\n\t\t\t}\n\t\t\tshard.mutex.Unlock()\n\t\t}\n\t}\n\twp.stopped = true\n\twp.mutex.Unlock()\n}", "func (p *GoroutinePool) Stop() {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tif !p.running {\n\t\treturn\n\t}\n\tfor _, w := range p.allWorkers {\n\t\tw.stop <- struct{}{}\n\t}\n\n\tp.Wait()\n\n\tclose(p.workers)\n\tp.running = false\n}", "func (p *Pool) Stop() {\n\tfor _, worker := range p.Workers {\n\t\tworker.Stop()\n\t}\n\tp.RunningBackground <-true\n}", "func (a *appsec) stop() {\n\ta.unregisterWAF()\n\ta.limiter.Stop()\n}", "func (m *ProbeManager) Stop() {\n\tclose(m.done)\n}", "func (l *Learner) Stop() {\n\t// TODO(student): distributed implementation\n\tl.stop <- struct{}{}\n}", "func (s *Bgmchain) Stop() error {\n\tif s.stopDbUpgrade != nil {\n\t\ts.stopDbUpgrade()\n\t}\n\ts.bloomIndexer.Close()\n\ts.blockchain.Stop()\n\ts.protocolManager.Stop()\n\tif s.lesServer != nil {\n\t\ts.lesServer.Stop()\n\t}\n\ts.txPool.Stop()\n\ts.miner.Stop()\n\ts.eventMux.Stop()\n\n\ts.chainDbPtr.Close()\n\tclose(s.shutdownChan)\n\n\treturn nil\n}", "func (c *ZKCluster) Stop() {\n\tif c.checkerdone != nil {\n\t\tclose(c.checkerdone)\n\t\tclose(c.updates)\n\t\tc.checkerdone = nil\n\t}\n}", "func (c *Cache) Stop() {\n\tclose(c.promotables)\n\t<-c.donec\n}", "func (phStats *passwordHasherStats) stopAccumulating() {\n\tclose(phStats.queue)\n}", "func (c *Concentrator) Stop() {\n\tclose(c.exit)\n\tc.exitWG.Wait()\n}", "func (ab *Buffer) Stop() error {\n\tif !ab.Latch.CanStop() {\n\t\treturn ex.New(async.ErrCannotStop)\n\t}\n\t// stop the interval worker\n\tab.intervalWorker.WaitStopped()\n\n\t// stop the running dispatch loop\n\tab.Latch.WaitStopped()\n\n\ttimeoutContext, cancel := context.WithTimeout(ab.Background(), ab.ShutdownGracePeriod)\n\tdefer cancel()\n\n\tab.contentsMu.Lock()\n\tdefer ab.contentsMu.Unlock()\n\tif ab.contents.Len() > 0 {\n\t\tab.flushes <- Flush{\n\t\t\tContext: timeoutContext,\n\t\t\tContents: ab.contents.Drain(),\n\t\t}\n\t}\n\n\tif remainingFlushes := len(ab.flushes); remainingFlushes > 0 {\n\t\tlogger.MaybeDebugf(ab.Log, \"%d flushes remaining\", remainingFlushes)\n\t\tvar flushWorker *async.Worker\n\t\tvar flush Flush\n\t\tfor x := 0; x < remainingFlushes; x++ {\n\t\t\tselect {\n\t\t\tcase <-timeoutContext.Done():\n\t\t\t\tlogger.MaybeDebugf(ab.Log, \"stop timed out\")\n\t\t\t\treturn nil\n\t\t\tcase flush = <-ab.flushes:\n\t\t\t\tselect {\n\t\t\t\tcase <-timeoutContext.Done():\n\t\t\t\t\tlogger.MaybeDebugf(ab.Log, \"stop timed out\")\n\t\t\t\t\treturn nil\n\t\t\t\tcase flushWorker = <-ab.flushWorkersReady:\n\t\t\t\t\tflushWorker.Work <- flush\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tworkersStopped := make(chan struct{})\n\tgo func() {\n\t\tdefer close(workersStopped)\n\t\twg := sync.WaitGroup{}\n\t\twg.Add(len(ab.flushWorkers))\n\t\tfor index, worker := range ab.flushWorkers {\n\t\t\tgo func(i int, w *async.Worker) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tlogger.MaybeDebugf(ab.Log, \"draining worker %d\", i)\n\t\t\t\tw.StopContext(timeoutContext)\n\t\t\t}(index, worker)\n\t\t}\n\t\twg.Wait()\n\t}()\n\n\tselect {\n\tcase <-timeoutContext.Done():\n\t\tlogger.MaybeDebugf(ab.Log, \"stop timed out\")\n\t\treturn nil\n\tcase <-workersStopped:\n\t\treturn nil\n\t}\n}", "func (s *Spooler) Stop() {\n\tlogp.Info(\"Stopping spooler\")\n\n\t// Signal to the run method that it should stop.\n\tclose(s.exit)\n\n\t// Stop accepting writes. Any events in the channel will be flushed.\n\tclose(s.Channel)\n\n\t// Wait for the flush to complete.\n\ts.wg.Wait()\n\tdebugf(\"Spooler has stopped\")\n}", "func stopWatchHeapOps() {\n\tquitChan <- true\n}", "func (l *Learner) Stop() {\n\tl.stop <- true\n}", "func (a *Appender) Stop() {\n\tif !a.started {\n\t\treturn\n\t}\n\ta.started = false\n\tclose(a.finish)\n\ta.wg.Wait()\n\t// all channels can be closed now, but then users can not start this\n\t// appender again.\n}", "func (g *GRPC) Stop() {\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tif g == nil {\n\t\treturn\n\t}\n\n\tfor _, cancel := range g.cancelFuncs {\n\t\tcancel()\n\t}\n\n\tg.serv.GracefulStop()\n\n\tg.lis = nil\n}", "func (c *collector) Stop() {\n\tclose(c.stop)\n}", "func (g *Group) Stop() {\n\tif g.Total > len(g.threads) {\n\t\tdefer close(g.chanStop)\n\t\tg.chanStop <- true\n\t}\n\n\tfor _, ok := range g.threads {\n\t\tok.Stop()\n\t}\n}", "func (s *samplerBackendRateCounter) Stop() {\n\tclose(s.exit)\n\t<-s.stopped\n}", "func (w *Watch) stop() {\n\tw.done <- struct{}{}\n}", "func (l *Learner) Stop() {\n\t//TODO(student): Task 3 - distributed implementation\n}", "func (a *Acceptor) Stop() {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.stopChan <- 0\n}", "func (d *Dispatcher) Stop() {\n\td.rwMutex.Lock()\n\tdefer d.rwMutex.Unlock()\n\td.asyncWG.Wait()\n}", "func (rp *ResolverPool) Stop() error {\n\tif rp.hasBeenStopped {\n\t\treturn nil\n\t}\n\trp.hasBeenStopped = true\n\tclose(rp.Done)\n\n\tfor _, r := range rp.Resolvers {\n\t\tr.Stop()\n\t}\n\n\trp.Resolvers = []Resolver{}\n\treturn nil\n}", "func (f *flushDaemon) stop() {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tif f.stopC == nil { // daemon not running\n\t\treturn\n\t}\n\n\tf.stopC <- struct{}{}\n\t<-f.stopDone\n\n\tf.stopC = nil\n\tf.stopDone = nil\n}", "func (s *Scanner) Stop() {\n\ts.stop <- struct{}{}\n}", "func (is *idleSweep) Stop() {\n\tif !is.started {\n\t\treturn\n\t}\n\n\tis.started = false\n\tis.ch.log.Info(\"Stopping idle connections poller.\")\n\tclose(is.stopCh)\n}", "func (c *NsqConsumer) Stop() {\n\tfor _, h := range c.handlers {\n\t\th.Stop()\n\t}\n\tif c.C != nil {\n\t\tclose(c.C)\n\t}\n}", "func (b *breachArbiter) Stop() error {\n\tif !atomic.CompareAndSwapUint32(&b.stopped, 0, 1) {\n\t\treturn nil\n\t}\n\n\tbrarLog.Infof(\"Breach arbiter shutting down\")\n\n\tclose(b.quit)\n\tb.wg.Wait()\n\n\treturn nil\n}", "func (e *binaryExprEvaluator) stop() {\n\te.lhs.stop()\n\te.rhs.stop()\n\tsyncClose(e.done)\n}", "func (d *Dispatcher) Stop() error {\n\tfor _, w := range d.Workers {\n\t\tw.Stop()\n\t}\n\treturn nil\n}", "func StopAll() {\n\tfor {\n\t\tglobal.Lock()\n\t\tfor _, pool := range global.pools {\n\t\t\tgo pool.Stop()\n\t\t}\n\t\tglobal.Unlock()\n\t}\n}", "func (recBuf *recBuf) lockedStopLinger() {\n\tif recBuf.lingering != nil {\n\t\trecBuf.lingering.Stop()\n\t\trecBuf.lingering = nil\n\t}\n}", "func (b *Bootstrapper) Stop() {\n\tif b.cancel != nil {\n\t\tb.cancel()\n\t}\n}", "func (c *KeyCertBundleRotator) Stop() {\n\tc.stoppedMutex.Lock()\n\tif !c.stopped {\n\t\tc.stopped = true\n\t\tc.stopCh <- true\n\t}\n\tc.stoppedMutex.Unlock()\n}", "func (s *Stopper) Stop(ctx context.Context) {\n\ts.mu.Lock()\n\tstopCalled := s.mu.stopping\n\ts.mu.stopping = true\n\ts.mu.Unlock()\n\n\tif stopCalled {\n\t\t// Wait for the concurrent Stop() to complete.\n\t\t<-s.stopped\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\ts.Recover(ctx)\n\t\tunregister(s)\n\t\tclose(s.stopped)\n\t}()\n\n\t// Don't bother doing stuff cleanly if we're panicking, that would likely\n\t// block. Instead, best effort only. This cleans up the stack traces,\n\t// avoids stalls and helps some tests in `./cli` finish cleanly (where\n\t// panics happen on purpose).\n\tif r := recover(); r != nil {\n\t\tgo s.Quiesce(ctx)\n\t\ts.mu.Lock()\n\t\tfor _, c := range s.mu.closers {\n\t\t\tgo c.Close()\n\t\t}\n\t\ts.mu.Unlock()\n\t\tpanic(r)\n\t}\n\n\ts.Quiesce(ctx)\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, c := range s.mu.closers {\n\t\tc.Close()\n\t}\n}", "func (p *Provider) Stop() {\n\tclose(p.stop)\n\t<-p.stopDone\n}", "func (er *BufferedExchangeReporter) Stop() {\n\n}", "func (_m *MockCompactionPlanContext) stop() {\n\t_m.Called()\n}", "func (gc *GC) Stop() {\n\tgc.mu.Lock()\n\tdefer gc.mu.Unlock()\n\tif gc.ticker == nil {\n\t\treturn // not started\n\t}\n\tgc.ticker.Stop()\n\tgc.ticker = nil\n}", "func (ab *AutoflushBuffer) Stop() error {\n\tif !ab.Latch.CanStop() {\n\t\treturn ex.New(ErrCannotStop)\n\t}\n\tab.Latch.Stopping()\n\t<-ab.Latch.NotifyStopped()\n\treturn nil\n}", "func stop() error {\n\tif spammerInstance == nil {\n\t\treturn ErrSpammerDisabled\n\t}\n\n\tspammerLock.Lock()\n\tdefer spammerLock.Unlock()\n\n\tstopWithoutLocking()\n\n\tisRunning = false\n\n\treturn nil\n}", "func (_m *Manager) WaitStop() {\n\t_m.Called()\n}", "func (sl *ReceiverLoop) stop() {\n\tsl.cancel()\n\t<-sl.stopped\n}", "func (b *Bootstrapper) Stop() error {\n\treturn nil\n}", "func (b *Bootstrapper) Stop() error {\n\treturn nil\n}", "func (br *Broker) Stop() error {\n\tif br.metaWatcher != nil {\n\t\tbr.metaWatcher.Stop()\n\t\tbr.metaWatcher = nil\n\t}\n\n\t// cancel routine context\n\tbr.ctxCancelFunc()\n\n\t// close the rpc clients\n\tfor idx, rc := range br.rpcClients {\n\t\trc.Close()\n\t\tdelete(br.rpcClients, idx)\n\t}\n\n\treturn nil\n}", "func Stop() {\n\tfor _, d := range daemons {\n\t\td.Close()\n\t}\n\tpeers = nil\n\tdaemons = nil\n}", "func (collector *Collector) Stop() {\n\t// Stop the underlying Prospector (this should block until all workers shutdown)\n\tcollector.prospector.Stop()\n\n\t// Signal our internal processing to stop as well. It's probably safer to do this\n\t// after we've stopped the prospector just to make sure we handle as much data as possible\n\tclose(collector.Done)\n\t// Wait for our collector to tell us its finished shutting down.\n\t<-collector.Stopped\n\n\tif collector.ticker != nil {\n\t\tcollector.ticker.Stop()\n\t}\n}", "func (p *Proposer) Stop() {\n\tp.stop <- struct{}{}\n}", "func (it *OracleMgrUnpauseIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func Stop() {\n\tstopRunning <- true\n\n}", "func (d *drainer) Stop() {\n\tif !d.lifecycle.Stop() {\n\t\tlog.Warn(\"drainer is already stopped, no\" +\n\t\t\t\" action will be performed\")\n\t\treturn\n\t}\n\t// Wait for drainer to be stopped\n\td.lifecycle.Wait()\n\tlog.Info(\"drainer stopped\")\n}", "func (m *MemoryStorer) StopCleaner() {\n\tclose(m.quit)\n\tm.wg.Wait()\n}", "func (s *Stopper) Stop(ctx context.Context) {\n\tdefer s.Recover(ctx)\n\tdefer unregister(s)\n\n\tif log.V(1) {\n\t\tfile, line, _ := caller.Lookup(1)\n\t\tlog.Infof(ctx,\n\t\t\t\"stop has been called from %s:%d, stopping or quiescing all running tasks\", file, line)\n\t}\n\t// Don't bother doing stuff cleanly if we're panicking, that would likely\n\t// block. Instead, best effort only. This cleans up the stack traces,\n\t// avoids stalls and helps some tests in `./cli` finish cleanly (where\n\t// panics happen on purpose).\n\tif r := recover(); r != nil {\n\t\tgo s.Quiesce(ctx)\n\t\tclose(s.stopper)\n\t\tclose(s.stopped)\n\t\ts.mu.Lock()\n\t\tfor _, c := range s.mu.closers {\n\t\t\tgo c.Close()\n\t\t}\n\t\ts.mu.Unlock()\n\t\tpanic(r)\n\t}\n\n\ts.Quiesce(ctx)\n\ts.mu.Lock()\n\tfor _, cancel := range s.mu.sCancels {\n\t\tcancel()\n\t}\n\tclose(s.stopper)\n\ts.mu.Unlock()\n\n\ts.stop.Wait()\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, c := range s.mu.closers {\n\t\tc.Close()\n\t}\n\tclose(s.stopped)\n}", "func (dw *DirWatcher) Stop() {\n\tdw.qrun <- false\n}", "func (se *StateEngine) Stop() {\n\tse.mgrLock.Lock()\n\tdefer se.mgrLock.Unlock()\n\tif se.stopped {\n\t\treturn\n\t}\n\tfor _, m := range se.managers {\n\t\tif stopper, ok := m.(StateStopper); ok {\n\t\t\tstopper.Stop()\n\t\t}\n\t}\n\tse.stopped = true\n}", "func (a *Agent) Stop() {\n\tclose(a.stopping)\n\ta.wg.Wait()\n}", "func (t *traverser) Stop() error {\n\t// Don't do anything if the traverser has already been stopped or suspended.\n\tt.stopMux.Lock()\n\tdefer t.stopMux.Unlock()\n\tif t.stopped {\n\t\treturn nil\n\t} else if t.suspended {\n\t\treturn ErrShuttingDown\n\t}\n\tclose(t.stopChan)\n\tt.stopped = true\n\tt.logger.Infof(\"stopping traverser and all jobs\")\n\n\t// Stop the runningReaper and start the stoppedReaper which saves jobs' states\n\t// but doesn't enqueue any more jobs to run. It sends the chain's final state\n\t// to the RM when all jobs have stopped running.\n\tt.reaper.Stop() // blocks until runningReaper stops\n\tstoppedReaperChan := make(chan struct{})\n\tt.reaper = t.reaperFactory.MakeStopped() // t.reaper = stoppedReaper\n\tgo func() {\n\t\tdefer close(stoppedReaperChan)\n\t\tt.reaper.Run()\n\t}()\n\n\t// Stop all job runners in the runner repo. Do this after switching to the\n\t// stopped reaper so that when the jobs finish and are sent on doneJobChan,\n\t// they are reaped correctly.\n\ttimeout := time.After(t.stopTimeout)\n\terr := t.stopRunningJobs(timeout)\n\tif err != nil {\n\t\t// Don't return the error yet - we still want to wait for the stop\n\t\t// reaper to be done.\n\t\terr = fmt.Errorf(\"traverser was stopped, but encountered an error in the process: %s\", err)\n\t}\n\n\t// Wait for the stopped reaper to finish. If it takes too long, some jobs\n\t// haven't respond quickly to being stopped. Stop waiting for these jobs by\n\t// stopping the stopped reaper.\n\tselect {\n\tcase <-stoppedReaperChan:\n\tcase <-timeout:\n\t\tt.logger.Warnf(\"timed out waiting for jobs to stop - stopping reaper\")\n\t\tt.reaper.Stop()\n\t}\n\tclose(t.doneChan)\n\treturn err\n}", "func (cMap *MyStruct) Stop(){\n\tcMap.stop <- true\n}", "func (s *TXPoolServer) Stop() {\n\tfor _, v := range s.actors {\n\t\tv.Stop()\n\t}\n\t//Stop worker\n\tfor i := 0; i < len(s.workers); i++ {\n\t\ts.workers[i].stop()\n\t}\n\ts.wg.Wait()\n\n\tif s.slots != nil {\n\t\tclose(s.slots)\n\t}\n}", "func (t *gRPCTransport) stop() {\n\t// Stop Communicate RPC and sendLoop\n\tt.grpcServer.Stop()\n\tfor i := 1; i <= 2; i++ {\n\t\tt.stopChan <- struct{}{}\n\t}\n\t// Close connections to peers.\n\tfor _, p := range t.peers {\n\t\tp.stop()\n\t}\n}", "func (rcw *RemoteClusterConfigWatcher) Stop() {\n\trcw.Lock()\n\tdefer rcw.Unlock()\n\tfor _, watcher := range rcw.clusterWatchers {\n\t\twatcher.Stop(false)\n\t}\n}", "func (p *Pipe) Stop() {\n\tif !p.stoppable {\n\t\treturn\n\t}\n\tPipeRegistry().Delete(p.registryID)\n\tclose(p.terminate)\n\tgo func() {\n\t\tp.listenerMU.RLock()\n\t\tif p.listener != nil {\n\t\t\tp.listener.Close()\n\t\t}\n\t\tp.listenerMU.RUnlock()\n\n\t\t// close all clients connections\n\t\tp.clientsMapMU.Lock()\n\t\tfor k, v := range p.clientsMap {\n\t\t\tv.Close()\n\t\t\tdelete(p.clientsMap, k)\n\t\t}\n\t\tp.clientsMapMU.Unlock()\n\t}()\n}", "func (s *Builder) Stop() {\n\tif s.stop {\n\t\treturn\n\t}\n\ts.stop = true\n}" ]
[ "0.6062398", "0.6048799", "0.59177333", "0.58795786", "0.5779963", "0.5743292", "0.5741704", "0.5685443", "0.56540674", "0.5640358", "0.56347626", "0.56151617", "0.5592923", "0.5573741", "0.55554795", "0.5539427", "0.55270153", "0.5490114", "0.5471471", "0.5466442", "0.5453796", "0.5442172", "0.5435045", "0.5409717", "0.53787017", "0.53772897", "0.53502905", "0.5347786", "0.53369284", "0.53311336", "0.5330833", "0.5329055", "0.5328833", "0.5319902", "0.53190815", "0.53187096", "0.5309235", "0.5305718", "0.5304798", "0.53012556", "0.52936524", "0.52819264", "0.52668977", "0.52593005", "0.5256755", "0.5244483", "0.524171", "0.523256", "0.52293205", "0.5213084", "0.52021533", "0.5199965", "0.51961327", "0.51912165", "0.5189871", "0.5185161", "0.5177055", "0.5176868", "0.5173233", "0.51705223", "0.5166221", "0.5162779", "0.5159641", "0.5144035", "0.5142461", "0.5139246", "0.5138475", "0.51360756", "0.51318973", "0.51298213", "0.5128819", "0.5127992", "0.51251066", "0.5112824", "0.5111493", "0.5109696", "0.5109526", "0.5108793", "0.5097686", "0.5076717", "0.5076717", "0.5074939", "0.50725025", "0.50673157", "0.5066114", "0.5064622", "0.50584006", "0.50557536", "0.50511837", "0.5044308", "0.50381655", "0.5037935", "0.50328046", "0.5030212", "0.5028484", "0.5026554", "0.5026159", "0.5013047", "0.5012364", "0.5010185" ]
0.7085047
0
allocateNode returns the new node and its data block, position at start
allocateNode возвращает новый узел и его блок данных, позиционируясь в начале
func (idx *Tree) allocateNode(a *Allocator, count int, prefixLen int) (n uint64, data []uint64) { prefixSlots := (prefixLen + 7) >> 3 if prefixLen >= 255 { prefixSlots++ } count += prefixSlots n = a.newNode(count) block := int(n >> blockSlotsShift) offset := int(n & blockSlotsOffsetMask) data = idx.blocks[block].data[offset:] return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *BTree) AllocateNode() *BTreeNode {\n\tx := BTreeNode{}\n\tfor i := 0; i < 2*t.t; i++ {\n\t\tx.children = append(x.children, t.nullNode)\n\t}\n\tfor i := 0; i < 2*t.t-1; i++ {\n\t\tx.keys = append(x.keys, -1)\n\t}\n\treturn &x\n}", "func (idx *Tree) allocateNodeWithPrefix(a *Allocator, count int, prefix []byte) (n uint64, data []uint64) {\n\tprefixLen := len(prefix)\n\tprefixSlots := (prefixLen + 7) >> 3\n\tif prefixLen >= 255 {\n\t\tprefixSlots++\n\t}\n\tcount += prefixSlots\n\tn = a.newNode(count)\n\tblock := int(n >> blockSlotsShift)\n\toffset := int(n & blockSlotsOffsetMask)\n\tdata = idx.blocks[block].data[offset:]\n\tif prefixLen > 0 {\n\t\tstorePrefix(data, prefix)\n\t\tdata = data[prefixSlots:]\n\t}\n\treturn\n}", "func (allc *Allocator) makeNode(truncatedSize uint32) uint32 {\n\t// Calculate the amount of actual memory required for this node.\n\t// Depending on the height of the node, size might be truncated.\n\tsize := defaultNodeSize - truncatedSize\n\t/*padding := size % cacheLineSize\n\tif padding < paddingLimit {\n\t\tsize += padding\n\t}*/\n\treturn allc.new(size)\n}", "func (b *nodeBuilder) createNode(rng Range, kind AstNodeKind, scope ScopePosition) NodePosition {\n\t// maybe we should handle here the capacity of the node arrays ?\n\tl := NodePosition(len(b.nodes))\n\tb.nodes = append(b.nodes, AstNode{Kind: kind, Range: rng, Scope: scope})\n\treturn l\n}", "func (t *BPTree) newNode() *Node {\n\tnode := &Node{\n\t\tKeys: make([][]byte, order-1),\n\t\tpointers: make([]interface{}, order),\n\t\tisLeaf: false,\n\t\tparent: nil,\n\t\tKeysNum: 0,\n\t\tAddress: t.LastAddress,\n\t}\n\tsize := getBinaryNodeSize()\n\tt.LastAddress += size\n\n\treturn node\n}", "func (t *Btree) newNode() *Node {\n\t*t.NodeCount++\n\tid := t.genrateID()\n\tnode := &Node{\n\t\tNodeRecordMetaData: NodeRecordMetaData{\n\t\t\tId: proto.Int64(id),\n\t\t\tIsDirt: proto.Int32(0),\n\t\t},\n\t}\n\tt.nodes[id] = node\n\treturn node\n}", "func NewNode(host string, size int) Node {\n\treturn node{host: host, size: size}\n}", "func (t *MCTS) alloc() naughty {\n\tt.Lock()\n\tl := len(t.freelist)\n\tif l == 0 {\n\t\tN := Node{\n\t\t\ttree: ptrFromTree(t),\n\t\t\tid: naughty(len(t.nodes)),\n\n\t\t\tminPSARatioChildren: defaultMinPsaRatio,\n\t\t}\n\t\tt.nodes = append(t.nodes, N)\n\t\tt.children = append(t.children, make([]naughty, 0, t.M*t.N+1))\n\t\tt.childLock = append(t.childLock, sync.Mutex{})\n\t\tn := naughty(len(t.nodes) - 1)\n\t\tt.Unlock()\n\t\treturn n\n\t}\n\n\ti := t.freelist[l-1]\n\tt.freelist = t.freelist[:l-1]\n\tt.Unlock()\n\treturn naughty(i)\n}", "func createNewEmptyNode() Node {\n\tnextNewId--\n\treturn Node{\n\t\tId: nextNewId,\n\t\tVisible: true,\n\t\tTimestamp: time.Now().Format(\"2006-01-02T15:04:05Z\"),\n\t\tVersion: \"1\",\n\t}\n}", "func newNode(parent *node, entry *nodeEntry) *node {\n\treturn &node{\n\t\tparent: parent,\n\t\toccupied: true,\n\t\tevalTotal: entry.eval,\n\t\tcount: 1,\n\t\tentry: entry,\n\t}\n}", "func (b *BTree) newNode() *memNode {\n\tfget := b.freeList.Get()\n\tvar n *Node\n\tif fget != nil {\n\t\tn = fget.(*Node)\n\t\tn.Reset()\n\t} else {\n\t\tn = &Node{}\n\t}\n\n\t// var parentIdx int\n\tvar depth int // parent == nil -> depth=0 root\n\n\tmn := &memNode{\n\t\tid: b.opCtx.GetNextID(),\n\t\tdepth: depth,\n\t\tnode: n,\n\t}\n\tb.opCtx.PushDirtyNode(mn)\n\treturn mn\n}", "func newNode(cluster *Cluster, nv *nodeValidator) *Node {\n\treturn &Node{\n\t\tcluster: cluster,\n\t\tname: nv.name,\n\t\taliases: nv.aliases,\n\t\taddress: nv.address,\n\t\tuseNewInfo: nv.useNewInfo,\n\n\t\t// Assign host to first IP alias because the server identifies nodes\n\t\t// by IP address (not hostname).\n\t\thost: nv.aliases[0],\n\t\tconnections: NewAtomicQueue(cluster.clientPolicy.ConnectionQueueSize),\n\t\tconnectionCount: NewAtomicInt(0),\n\t\thealth: NewAtomicInt(_FULL_HEALTH),\n\t\tpartitionGeneration: NewAtomicInt(-1),\n\t\treferenceCount: NewAtomicInt(0),\n\t\trefreshCount: NewAtomicInt(0),\n\t\tresponded: NewAtomicBool(false),\n\t\tactive: NewAtomicBool(true),\n\n\t\tsupportsFloat: NewAtomicBool(nv.supportsFloat),\n\t\tsupportsBatchIndex: NewAtomicBool(nv.supportsBatchIndex),\n\t\tsupportsReplicasAll: NewAtomicBool(nv.supportsReplicasAll),\n\t\tsupportsGeo: NewAtomicBool(nv.supportsGeo),\n\t}\n}", "func createNewNode(ctx context.Context, nodeName string, virtual bool, clientset kubernetes.Interface) (*corev1.Node, error) {\n\tresources := corev1.ResourceList{}\n\tresources[corev1.ResourceCPU] = *resource.NewScaledQuantity(5000, resource.Milli)\n\tresources[corev1.ResourceMemory] = *resource.NewScaledQuantity(5, resource.Mega)\n\tnode := &corev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: nodeName,\n\t\t},\n\t}\n\tif virtual {\n\t\tnode.Labels = map[string]string{\n\t\t\tconsts.TypeLabel: consts.TypeNode,\n\t\t}\n\t}\n\tnode.Status = corev1.NodeStatus{\n\t\tCapacity: resources,\n\t\tAllocatable: resources,\n\t\tConditions: []corev1.NodeCondition{\n\t\t\t0: {\n\t\t\t\tType: corev1.NodeReady,\n\t\t\t\tStatus: corev1.ConditionTrue,\n\t\t\t},\n\t\t},\n\t}\n\tnode, err := clientset.CoreV1().Nodes().Create(ctx, node, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn node, nil\n}", "func (t *MCTS) alloc() Naughty {\n\tt.Lock()\n\tdefer t.Unlock()\n\tl := len(t.freelist)\n\tif l == 0 {\n\t\tN := Node{\n\t\t\tlock: sync.Mutex{},\n\t\t\ttree: ptrFromTree(t),\n\t\t\tid: Naughty(len(t.nodes)),\n\t\t\thasChildren: false,\n\t\t}\n\t\tt.nodes = append(t.nodes, N)\n\t\tt.children = append(t.children, make([]Naughty, 0, t.current.ActionSpace()))\n\t\tn := Naughty(len(t.nodes) - 1)\n\t\treturn n\n\t}\n\n\ti := t.freelist[l-1]\n\tt.freelist = t.freelist[:l-1]\n\treturn i\n}", "func NewNode(data int) *Node {\n\treturn &Node{\n\t\tNext: nil,\n\t\tData: data,\n\t}\n}", "func NewNode(data int) *Node {\n\treturn &Node{\n\t\tData: data,\n\t\tNext: nil,\n\t}\n}", "func (bpt *BplusTree) treeNodeInit(isLeaf bool, next common.Key, prev common.Key,\n\tinitLen int) *treeNode {\n\n\tnode := defaultAlloc()\n\tnode.Children = make([]treeNodeElem, initLen, bpt.context.maxDegree)\n\tnode.IsLeaf = isLeaf\n\tnode.NextKey = next\n\tnode.PrevKey = prev\n\t// Generate a new key for the node being added.\n\tnode.NodeKey = common.Generate(bpt.context.keyType, bpt.context.pfx)\n\treturn node\n}", "func newNode() *node {\n\treturn &node{}\n}", "func NewNode(p string) *MyNode {\n\taddr := getLocalAddress()\n\n\treturn &MyNode{\n\t\tAddr: addr,\n\t\tPort: p,\n\t\tID: HashString(fmt.Sprintf(\"%v:%v\", addr, p)),\n\t\tData: make(map[string]string),\n\t\tbuf: new(bytes.Buffer),\n\t}\n}", "func Regalloc(n *Node, t *Type, o *Node)", "func (_BaseFactory *BaseFactoryTransactor) CreateNode(opts *bind.TransactOpts, _owner common.Address) (*types.Transaction, error) {\n\treturn _BaseFactory.contract.Transact(opts, \"createNode\", _owner)\n}", "func newNode(nodePath string) Node {\n\treturn &nodeImpl{nodePath: nodePath}\n}", "func newNode() *node {\n\treturn &node{\n\t\tvalue: nil,\n\t\tchildren: map[string]*node{},\n\t}\n}", "func NewNode(cnf *Config, joinNode *api.Node) (*Node, error) {\n\tvar nodeID string\n\n\tnode := &Node{\n\t\tNode: new(api.Node),\n\t\tshutdownCh: make(chan struct{}),\n\t\tcnf: cnf,\n\t\tstorage: NewMapStore(cnf.Hash),\n\t}\n\tif cnf.Id != \"\" {\n\t\tnodeID = cnf.Id\n\t} else {\n\t\tnodeID = cnf.Addr\n\t}\n\n\tid, err := node.hashKey(nodeID)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taInt := (&big.Int{}).SetBytes(id) // treating id as bytes of a big-endian unsigned integer, return the integer it represents\n\tlog.Printf(aurora.Sprintf(aurora.Yellow(\"New Node ID = %d, \\n\"), aInt))\n\tnode.Node.Id = id\n\tnode.Node.Addr = cnf.Addr\n\t// Populate finger table (by anotating itself to be in charge of all possible hashes at the moment)\n\tnode.fingerTable = newFingerTable(node.Node, cnf.HashSize)\n\n\t// Start RPC server (start listening function, )\n\t// transport is a struct that contains grpc server and supplementary attributes (like timeout etc)\n\ttransport, err := NewGrpcTransport(cnf)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode.transport = transport\n\n\tapi.RegisterChordServer(transport.server, node)\n\tnode.transport.Start()\n\n\t// find the closest node clockwise from the id of this node (i.e. successor node)\n\t// adds successor to the 'successor' attribute of the node\n\tnodeJoinErr := node.join(joinNode)\n\n\tif nodeJoinErr != nil {\n\t\tlog.Printf(\"Error joining node\")\n\t\treturn nil, err\n\t}\n\n\t// run routines\n\t// Fix fingers every 500 ms\n\tgo node.fixFingerRoutine(500)\n\n\t// Stablize every 1000ms\n\tgo node.stabilizeRoutine(1000)\n\t// Check predecessor fail every 5000 ms\n\tgo node.checkPredecessorRoutine(2000)\n\n\treturn node, nil\n}", "func NewNode(id uint64) *Node { return &Node{Id: id} }", "func createLocalNode() {\n\t// Initialize the internal table\n\tinternalTable = NewTable(config.maxKey)\n\n\t// Set the variables of this node.\n\tvar err error\n\tcaller, err = NewNodeCaller(config.callerPort)\n\tif err != nil {\n\t\tpanic(\"rpcCaller failed to initialize\")\n\t}\n\terr = initNodeCallee(config.calleePort)\n\tif err != nil {\n\t\tpanic(\"rpcCallee failed to initialize\")\n\t}\n\n\tmy.address = fmt.Sprintf(\"%s:%d\", config.addr, config.calleePort)\n\n\tmy.key = Hash(my.address, config.maxKey)\n\tlog.Printf(\"[NODE %d] Keyspace position %d was derived from address %s\\n\", my.key, my.key, my.address)\n\n\tpredecessor = nil\n\tsuccessor = &RemoteNode{\n\t\tAddress: my.address,\n\t\tKey: my.key,\n\t}\n\t// Initialize the finger table for the solo ring configuration\n\tfingers = make([]*RemoteNode, config.numFingers)\n\tlog.Printf(\"[NODE %d] Finger table size %d was derived from the keyspace size\\n\", my.key, config.numFingers)\n\tfor i := uint64(0); i < config.numFingers; i++ {\n\t\tfingers[i] = successor\n\t}\n}", "func newNode(index int, parent *node, hasher hash.Hash) *node {\n\treturn &node{\n\t\tparent: parent,\n\t\tisLeft: index%2 == 0,\n\t\thasher: hasher,\n\t}\n}", "func newNode() *Node {\n\tn := &Node{}\n\treturn n\n}", "func newNode(val int) *node {\n\treturn &node{val, nil, nil}\n}", "func (tree *Tree23) newNode() TreeNodeIndex {\n\n\t// Recycle a deleted node.\n\tif tree.treeNodesFreePositions.len() > 0 {\n\t\tnode := TreeNodeIndex(tree.treeNodesFreePositions.pop())\n\t\treturn node\n\t}\n\n\t// Resize the cache and get more memory.\n\t// Resize our cache by 2x or 1.25x of the previous length. This is in accordance to slice append resizing.\n\tl := len(tree.treeNodes)\n\tif tree.treeNodesFirstFreePos >= l {\n\t\tappendSize := int(float64(l) * 1.25)\n\t\tif l < 1000 {\n\t\t\tappendSize = l * 2\n\t\t}\n\t\ttree.treeNodes = append(tree.treeNodes, make([]treeNode, appendSize)...)\n\t}\n\n\t// Get node from cached memory.\n\ttree.treeNodesFirstFreePos++\n\treturn TreeNodeIndex(tree.treeNodesFirstFreePos - 1)\n}", "func (nh *NodeHost) RequestAddNode(clusterID uint64,\n\tnodeID uint64, address string, configChangeIndex uint64,\n\ttimeout time.Duration) (*RequestState, error) {\n\tv, ok := nh.getCluster(clusterID)\n\tif !ok {\n\t\treturn nil, ErrClusterNotFound\n\t}\n\treq, err := v.requestAddNodeWithOrderID(nodeID,\n\t\taddress, configChangeIndex, timeout)\n\tnh.execEngine.setNodeReady(clusterID)\n\treturn req, err\n}", "func createNodeRoute(w http.ResponseWriter, r *http.Request) {\n\troute := \"CreateNode\"\n\n\tquery := r.URL.Query()\n\tnodeID, initAmount := query.Get(\"nodeID\"), query.Get(\"initAmount\")\n\n\thandleRoute(route, nodeID, initAmount)\n}", "func NewNode(cache *Cache, path string, parent *Node) *Node {\n\tdepth := 0\n\tif parent != nil {\n\t\tdepth = parent.depth + 1\n\t}\n\treturn &Node{\n\t\tcache: cache,\n\t\tstate: NodeStatePending,\n\t\tparent: parent,\n\t\tpath: path,\n\t\tchildren: make(map[string]*Node),\n\t\tdepth: depth,\n\t}\n}", "func StartNewNode(\n\tconfig *Config,\n\tinitialNetworkState *pb.NetworkState,\n\tinitialCheckpointValue []byte,\n) (*Node, error) {\n\treturn RestartNode(\n\t\tconfig,\n\t\t&dummyWAL{\n\t\t\tinitialNetworkState: initialNetworkState,\n\t\t\tinitialCheckpointValue: initialCheckpointValue,\n\t\t},\n\t)\n}", "func NewNode(data int) *Node {\n\treturn &Node{\n\t\tData: data,\n\t\tLeft: nil,\n\t\tRight: nil,\n\t}\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func newCbsNode(region string, volumeAttachLimit int64) (*cbsNode, error) {\n\tsecretID, secretKey, token, _ := util.GetSercet()\n\tcred := &common.Credential{\n\t\tSecretId: secretID,\n\t\tSecretKey: secretKey,\n\t\tToken: token,\n\t}\n\n\tclient, err := cbs.NewClient(cred, region, profile.NewClientProfile())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode := cbsNode{\n\t\tmetadataClient: metadata.NewMetaData(http.DefaultClient),\n\t\tcbsClient: client,\n\t\tmounter: mount.SafeFormatAndMount{\n\t\t\tInterface: mount.New(\"\"),\n\t\t\tExec: exec.New(),\n\t\t},\n\t\tidempotent: util.NewIdempotent(),\n\t\tvolumeAttachLimit: volumeAttachLimit,\n\t}\n\treturn &node, nil\n}", "func (allc *Allocator) getNode(offset uint32) *node {\n\tif offset == nilAllocatorOffset {\n\t\treturn nil\n\t}\n\treturn (*node)(unsafe.Pointer(&allc.mem[offset]))\n}", "func NewSampleNodeAllocate() NodeAllocate {\n\treturn NodeAllocate{\n\t\tKubeReservedCPU: \"1\",\n\t\tSysReservedCPU: \"1\",\n\t\tKubeMemory: \"500Mi\",\n\t\tSysMemory: \"500Mi\",\n\t\tKubeStorage: \"10Gi\",\n\t\tSysStorage: \"10Gi\",\n\t\tEvictionMemory: \"500Mi\",\n\t\tEvictionNodefs: \"10%\",\n\t}\n}", "func nodeCreator(inputValue int64) *Node {\n\n\t// instantiate the node pointer\n\tnode := new(Node)\n\n\t// add the value\n\tnode.value = inputValue\n\n\t// return a pointer to a node\n\treturn node\n}", "func newNode(allc *Allocator, valAllc *Allocator, height uint8, key []byte, val []byte) (*node, uint32) {\n\ttruncatedSize := (DefaultMaxHeight - int(height)) * LayerSize\n\tkeyOffset := allc.putBytes(key)\n\tnodeOffset := allc.makeNode(uint32(truncatedSize))\n\tvalOffset := valAllc.putBytes(val)\n\tnode := allc.getNode(nodeOffset)\n\tnode.height = height\n\tnode.keyOffset = keyOffset\n\t// TODO key length should not exceed uint16 size, assert.\n\tnode.keySize = uint16(len(key))\n\tnode.encodeValue(valOffset, uint32(len(val)))\n\treturn node, nodeOffset\n}", "func (a API) AddNode(cmd *btcjson.AddNodeCmd) (e error) {\n\tRPCHandlers[\"addnode\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func NewNode(name string, tcpAddr string, job JobType) Node {\n\t// resolve ip\n\tn := util.NewNodeFromTCPAddr(tcpAddr, session.NodeTypeReplica /*dummy field*/)\n\treturn Node{\n\t\tJob: job,\n\t\tName: name,\n\t\tIPPort: n.TCPAddr(),\n\t\tHostname: n.Hostname,\n\t\tAttrs: map[string]interface{}{},\n\t}\n}", "func (bfs *BlockFilesystem) allocate(ctx context.Context) (uint64, error) {\n\tstate, err := bfs.store.State(ctx)\n\tif err != nil {\n\t\treturn nilPtr, err\n\t} else if state.TrashPtr == nilPtr {\n\t\tnext := state.NextPtr\n\t\tstate.NextPtr += 1\n\t\treturn next, nil\n\t}\n\n\tb := &block{parent: bfs}\n\tif bfs.splitPtrs {\n\t\trawPtrs, err := bfs.store.Get(ctx, p(state.TrashPtr))\n\t\tif err != nil {\n\t\t\treturn nilPtr, err\n\t\t} else if err := b.UnmarshalPtrs(rawPtrs); err != nil {\n\t\t\treturn nilPtr, fmt.Errorf(\"blockfs: failed to parse block %x: %v\", state.TrashPtr, err)\n\t\t}\n\t} else {\n\t\traw, err := bfs.store.Get(ctx, state.TrashPtr)\n\t\tif err != nil {\n\t\t\treturn nilPtr, err\n\t\t} else if err := b.Unmarshal(raw); err != nil {\n\t\t\treturn nilPtr, fmt.Errorf(\"blockfs: failed to parse block %x: %v\", state.TrashPtr, err)\n\t\t}\n\t}\n\n\ttrash := state.TrashPtr\n\tstate.TrashPtr = b.ptrs[0]\n\treturn trash, nil\n}", "func (_BaseContentSpace *BaseContentSpaceTransactor) AddNode(opts *bind.TransactOpts, _nodeAddr common.Address, _locator []byte) (*types.Transaction, error) {\n\treturn _BaseContentSpace.contract.Transact(opts, \"addNode\", _nodeAddr, _locator)\n}", "func NewNode(port int) dhtNode {\n\t// Todo: create a node and then return it.\n\treturn dht.NewSurface(port)\n}", "func NewNode(key int) *Node {\n\tp := int(rand.Int31n(math.MaxInt32))\n\treturn &Node{key: key, p: p, size: 1}\n}", "func createNode(cfg *meta.ClusterConfig, nodeUUID, nodeURL string) (*meta.Watcher, *meta.Node, *rpckit.RPCServer, error) {\n\t// create watcher\n\tw, err := meta.NewWatcher(nodeUUID, cfg)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Start a rpc server\n\trpcSrv, err := rpckit.NewRPCServer(fmt.Sprintf(\"datanode-%s\", nodeUUID), nodeURL, rpckit.WithLoggerEnabled(false))\n\tif err != nil {\n\t\tlog.Errorf(\"failed to listen to %s: Err %v\", nodeURL, err)\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// register RPC handlers\n\ttproto.RegisterDataNodeServer(rpcSrv.GrpcServer, &fakeDataNode{nodeUUID: nodeUUID})\n\trpcSrv.Start()\n\ttime.Sleep(time.Millisecond * 50)\n\n\t// create node\n\tnd, err := meta.NewNode(cfg, nodeUUID, nodeURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn w, nd, rpcSrv, nil\n}", "func NewNode(name string) TreeNode {\n\treturn TreeNode{\n\t\tname: name,\n\t\tsize: 0,\n\t\tfiles: make(map[string]Entry),\n\t}\n}", "func createNode(addr string, nodeStmts map[string]ast.Stmt) *ast.Node {\n\tnID := \"n\" + strings.Replace(addr, \".\", \"\", -1)\n\tnID = strings.Replace(nID, \":\", \"\", -1)\n\tn := &ast.Node{ID: nID}\n\tnodeStmts[n.ID] = &ast.NodeStmt{\n\t\tNode: n,\n\t\tAttrs: []*ast.Attr{\n\t\t\t{\n\t\t\t\tKey: \"label\",\n\t\t\t\tVal: fmt.Sprintf(`\"%s\"`, addr),\n\t\t\t},\n\t\t},\n\t}\n\treturn n\n}", "func (l *Libvirt) NodeAllocPages(PageSizes []uint32, PageCounts []uint64, StartCell int32, CellCount uint32, Flags NodeAllocPagesFlags) (rRet int32, err error) {\n\tvar buf []byte\n\n\targs := NodeAllocPagesArgs {\n\t\tPageSizes: PageSizes,\n\t\tPageCounts: PageCounts,\n\t\tStartCell: StartCell,\n\t\tCellCount: CellCount,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(347, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Ret: int32\n\t_, err = dec.Decode(&rRet)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func NewNode(tcpAddr *net.TCPAddr) *Node {\n\tn := new(Node)\n\tn.TcpAddr = tcpAddr\n\tn.btcNet = wire.MainNet\n\tn.doneC = make(chan struct{}, 1)\n\n\treturn n\n}", "func (r *root) newNode(view *View) (n *node) {\n\tif r.freeNode == nil {\n\t\tn = &node{view: *view, disposable: true}\n\t} else {\n\t\tn = r.freeNode\n\t\tr.freeNode = n.nextFree\n\t\tn.view = *view\n\t}\n\tr.newLeaves(view, &n.children)\n\treturn\n}", "func alloc(size uintptr, layout unsafe.Pointer) unsafe.Pointer", "func (p *pool) AllocateBlock(ctx context.Context, nodeName, requestUID string) (*coilv2.AddressBlock, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tnextIndex, ok := p.allocated.NextClear(0)\n\tif !ok {\n\t\tnextIndex = p.allocated.Len()\n\t}\n\n\tap := &coilv2.AddressPool{}\n\terr := p.client.Get(ctx, client.ObjectKey{Name: p.name}, ap)\n\tif err != nil {\n\t\tp.log.Error(err, \"failed to get AddressPool\")\n\t\treturn nil, err\n\t}\n\tif ap.DeletionTimestamp != nil {\n\t\tp.log.Info(\"unable to curve out a block because pool is under deletion\")\n\t\treturn nil, ErrNoBlock\n\t}\n\n\tvar currentIndex uint\n\tfor _, ss := range ap.Spec.Subnets {\n\t\tvar ones, bits int\n\t\tif ss.IPv4 != nil {\n\t\t\t_, n, _ := net.ParseCIDR(*ss.IPv4) // ss was validated\n\t\t\tones, bits = n.Mask.Size()\n\t\t} else {\n\t\t\t_, n, _ := net.ParseCIDR(*ss.IPv6) // ss was validated\n\t\t\tones, bits = n.Mask.Size()\n\t\t}\n\t\tsize := uint(1) << (bits - ones - int(ap.Spec.BlockSizeBits))\n\t\tif nextIndex >= (currentIndex + size) {\n\t\t\tcurrentIndex += size\n\t\t\tcontinue\n\t\t}\n\n\t\tipv4, ipv6 := ss.GetBlock(nextIndex-currentIndex, int(ap.Spec.BlockSizeBits))\n\n\t\tr := &coilv2.AddressBlock{}\n\t\tr.Name = fmt.Sprintf(\"%s-%d\", p.name, nextIndex)\n\t\tif err := controllerutil.SetControllerReference(ap, r, p.scheme); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.Labels = map[string]string{\n\t\t\tconstants.LabelPool: p.name,\n\t\t\tconstants.LabelNode: nodeName,\n\t\t\tconstants.LabelRequest: requestUID,\n\t\t}\n\t\tcontrollerutil.AddFinalizer(r, constants.FinCoil)\n\t\tr.Index = int32(nextIndex)\n\t\tif ipv4 != nil {\n\t\t\ts := ipv4.String()\n\t\t\tr.IPv4 = &s\n\t\t}\n\t\tif ipv6 != nil {\n\t\t\ts := ipv6.String()\n\t\t\tr.IPv6 = &s\n\t\t}\n\t\tif err := p.client.Create(ctx, r); err != nil {\n\t\t\tp.log.Error(err, \"failed to create AddressBlock\", \"index\", nextIndex, \"node\", nodeName)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tp.log.Info(\"created AddressBlock\", \"index\", nextIndex, \"node\", nodeName)\n\t\tp.allocated.Set(nextIndex)\n\t\tp.allocatedBlocks.Inc()\n\t\treturn r, nil\n\t}\n\n\tp.log.Error(ErrNoBlock, \"no available blocks\")\n\treturn nil, ErrNoBlock\n}", "func (g *Graph) AppendNode(content []byte, predecessors ...ObjectID) (*Object, error) {\n\tvar buf = make([]byte, 0)\n\n\tfor _, predecessor := range predecessors {\n\t\tbuf = append(buf, predecessor[:]...)\n\t}\n\tbuf = append(buf, content...)\n\n\th := ObjectID{}\n\t// Compute a 64-byte hash of buf and put it in h.\n\tsha3.ShakeSum128(h[:], buf)\n\tvar obj = Object{}\n\tobj.ID = h\n\tobj.Content = content\n\tobj.PredecessorIDs = append([]ObjectID{}, predecessors...)\n\n\tg.ObjectAdapter.WriteObject(obj)\n\n\treturn &obj, nil\n}", "func createList(numNodes int) (*Node) {\n var startNode, curNode *Node\n\n // create last linked\n lastNode := Node{nil, numNodes}\n\n // handle edge cases.\n if numNodes < 0 {\n return nil \n } else if numNodes == 1 {\n return &lastNode\n }\n\n // create n-1 other node.\n for i := 0 ; i<numNodes ; i++ {\n //fmt.Println(\"i\", i)\n // handle init case.\n if i == 0 {\n curNode = &lastNode\n }\n\n // setup new node.\n newNode := Node{nil, numNodes-(i+1)}\n\n // link node.\n curNode = addLink(&newNode, curNode)\n\n // update start node\n startNode = curNode\n }\n\n return startNode\n}", "func NewNode(node ast.Node) Node {\n\treturn creator(baseNode{node: node})\n}", "func NewNode(cnf *Config, joinNode *models.Node) (*Node, error) {\n\tif err := cnf.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tnode := &Node{\n\t\tNode: new(models.Node),\n\t\tshutdownCh: make(chan struct{}),\n\t\tcnf: cnf,\n\t\tstorage: NewMapStore(cnf.Hash),\n\t}\n\n\tvar nID string\n\tif cnf.Id != \"\" {\n\t\tnID = cnf.Id\n\t} else {\n\t\tnID = cnf.Addr\n\t}\n\tid, err := node.hashKey(nID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taInt := (&big.Int{}).SetBytes(id)\n\n\tfmt.Printf(\"new node id %d, \\n\", aInt)\n\n\tnode.Node.Id = id\n\tnode.Node.Addr = cnf.Addr\n\n\t// Populate finger table\n\tnode.fingerTable = newFingerTable(node.Node, cnf.HashSize)\n\n\t// Start RPC server\n\ttransport, err := NewGrpcTransport(cnf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode.transport = transport\n\n\tmodels.RegisterChordServer(transport.server, node)\n\n\tnode.transport.Start()\n\n\tif err := node.join(joinNode); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Peridoically stabilize the node.\n\tgo func() {\n\t\tticker := time.NewTicker(1 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tnode.stabilize()\n\t\t\tcase <-node.shutdownCh:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Peridoically fix finger tables.\n\tgo func() {\n\t\tnext := 0\n\t\tticker := time.NewTicker(100 * time.Millisecond)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tnext = node.fixFinger(next)\n\t\t\tcase <-node.shutdownCh:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Peridoically checkes whether predecessor has failed.\n\n\tgo func() {\n\t\tticker := time.NewTicker(10 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tnode.checkPredecessor()\n\t\t\tcase <-node.shutdownCh:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn node, nil\n}", "func NewNode(val int) *Node {\n\tn := &Node{}\n\tn.val = val\n\tn.next = nil\n\tn.prev = nil\n\treturn n\n}", "func Node(i Index, r Layer) (p Pos) {\n\tp.i = i\n\tp.r = r\n\tp.assertValid()\n\treturn\n}", "func NewNode(key, value interface{}) *Node {\n\tvar node Node\n\tnode.value = value\n\tnode.key = key\n\tnode.next = nil\n\treturn &node\n}", "func defaultAlloc() *treeNode {\n\treturn &treeNode{}\n}", "func (_PermInterface *PermInterfaceTransactor) AddNode(opts *bind.TransactOpts, _orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addNode\", _orgId, _enodeId, _ip, _port, _raftport)\n}", "func (c *CAPI) AddNode(req *btcjson.AddNodeCmd, resp None) (e error) {\n\tnrh := RPCHandlers\n\tres := nrh[\"addnode\"].Result()\n\tres.Params = req\n\tnrh[\"addnode\"].Call <- res\n\tselect {\n\tcase resp = <-res.Ch.(chan None):\n\tcase <-time.After(c.Timeout):\n\tcase <-c.quit.Wait():\n\t} \n\treturn \n}", "func (c *Client) CreateDataNode(httpAddr, tcpAddr string) (*NodeInfo, error) {\n\tcmd := &internal.CreateDataNodeCommand{\n\t\tHTTPAddr: proto.String(httpAddr),\n\t\tTCPAddr: proto.String(tcpAddr),\n\t}\n\n\tif err := c.retryUntilExec(internal.Command_CreateDataNodeCommand, internal.E_CreateDataNodeCommand_Command, cmd); err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := c.DataNodeByTCPHost(tcpAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.nodeID = n.ID\n\n\treturn n, nil\n}", "func (s *DHT) addNode(node *Node) *Node {\n\t// the bucket index for the node\n\tindex := s.ht.bucketIndex(s.ht.self.ID, node.ID)\n\n\t// 1. if the node is existed, refresh the node to the end of bucket\n\tif s.ht.hasBucketNode(index, node.ID) {\n\t\ts.ht.refreshNode(node.ID)\n\t\treturn nil\n\t}\n\n\ts.ht.mutex.Lock()\n\tdefer s.ht.mutex.Unlock()\n\n\t// 2. if the bucket is full, ping the first node\n\tbucket := s.ht.routeTable[index]\n\tif len(bucket) == K {\n\t\tfirst := bucket[0]\n\n\t\t// new a ping request message\n\t\trequest := s.newMessage(Ping, first, nil)\n\t\t// new a context with timeout\n\t\tctx, cancel := context.WithTimeout(context.Background(), defaultPingTime)\n\t\tdefer cancel()\n\n\t\t// invoke the request and handle the response\n\t\tresponse, err := s.network.Call(ctx, request)\n\t\tif err != nil {\n\t\t\t// the node is down, remove the node from bucket\n\t\t\tbucket = append(bucket, node)\n\t\t\tbucket = bucket[1:]\n\n\t\t\t// need to reset the route table with the bucket\n\t\t\ts.ht.routeTable[index] = bucket\n\n\t\t\tlog.WithContext(ctx).Debugf(\"bucket: %d, network call: %v: %v\", index, request, err)\n\t\t\treturn first\n\t\t}\n\t\tlog.WithContext(ctx).Debugf(\"ping response: %v\", response.String())\n\n\t\t// refresh the node to the end of bucket\n\t\tbucket = bucket[1:]\n\t\tbucket = append(bucket, node)\n\t} else {\n\t\t// 3. append the node to the end of the bucket\n\t\tbucket = append(bucket, node)\n\t}\n\n\t// need to update the route table with the bucket\n\ts.ht.routeTable[index] = bucket\n\n\treturn nil\n}", "func NodeAllocatableRoot(cgroupRoot string, cgroupsPerQOS bool, cgroupDriver string) string {\n\treturn \"\"\n}", "func (root *DSSRoot) newNode(state int, sym lr.Symbol) *DSSNode {\n\tvar node *DSSNode\n\tn, ok := root.reservoir.Get(0)\n\tif ok {\n\t\troot.reservoir.Remove(0)\n\t\tnode = n.(*DSSNode)\n\t\tnode.State = state\n\t\tnode.Sym = sym\n\t} else {\n\t\tnode = newDSSNode(state, sym)\n\t}\n\treturn node\n}", "func (s *Arena) putNode(height int) uint32 {\n\t// Compute the amount of the tower that will never be used, since the height\n\t// is less than maxHeight.\n\tunusedSize := (maxHeight - height) * offsetSize\n\n\t// Pad the allocation with enough bytes to ensure pointer alignment.\n\tl := uint32(MaxNodeSize - unusedSize + nodeAlign)\n\tn := s.allocate(l)\n\n\t// Return the aligned offset.\n\tm := (n - l + uint32(nodeAlign)) & ^uint32(nodeAlign)\n\treturn m\n}", "func NewNode(key int, value string) *Node {\n\treturn &Node{1, nil, nil, key, value}\n}", "func NewNode() *Node {\n\treturn &Node{}\n}", "func NewNode(data string) *Node {\n\tnode := &Node{}\n\tnode.data = data\n\treturn node\n}", "func nextNode(X [][]float64, indicies []int, d int) *Node {\n\txCols := len(X[0])\n\n\tvar c float64\n\tif len(indicies) > 1 {\n\t\tc = computeC(float64(len(indicies)))\n\t}\n\n\tif len(indicies) <= 1 || d >= MaxDepth {\n\t\treturn &Node{External: true, Size: len(indicies), C: c}\n\t}\n\n\tatt := findAttribute(xCols)\n\tsplit := findSplit(X, indicies, att)\n\n\tnewNode := &Node{Attribute: att, Split: split, External: false, Size: len(indicies), C: c}\n\n\tindiciesSmaller, indiciesBigger := splitMatrix(X, split, att, indicies)\n\tnewNode.Left = nextNode(X, indiciesSmaller, d+1)\n\n\tnewNode.Right = nextNode(X, indiciesBigger, d+1)\n\n\treturn newNode\n\n}", "func newNode() *node {\n\tvar leafs [8]octant\n\tfor i := 0; i < 8; i++ {\n\t\tleafs[i] = newLeaf(nil)\n\t}\n\treturn &node{\n\t\tleafs: &leafs,\n\t}\n}", "func newnode(id byte, name string, value string) *xmlx.Node {\n\tnode := xmlx.NewNode(id)\n\tif name != \"\" {\n\t\tnode.Name = xml.Name{\n\t\t\tLocal: name,\n\t\t}\n\t}\n\tif value != \"\" {\n\t\tnode.Value = value\n\t}\n\treturn node\n}", "func (fs *fsMutable) createNode(lk []byte, parentINode fuseops.InodeID, childName string,\n\tentry *fuseops.ChildInodeEntry, nodeType fuseutil.DirentType, isRoot bool) error {\n\n\t// Create lookup key if not already created.\n\tif lk == nil {\n\t\tlk = formLookupKey(parentINode, childName)\n\t}\n\n\tvar iNodeID fuseops.InodeID\n\tif !isRoot {\n\t\tiNodeID = fs.iNodeGenerator.allocINode()\n\t} else {\n\t\tiNodeID = parentINode\n\t}\n\n\t// lookup\n\tfs.lookupTree, _, _ = fs.lookupTree.Insert(lk, lookupEntry{iNode: iNodeID})\n\n\t// Default to common case of create file\n\tvar linkCount = fileLinkCount\n\tvar defaultMode os.FileMode = fileDefaultMode\n\tvar defaultSize uint64\n\n\tif nodeType == fuseutil.DT_Directory {\n\t\tlinkCount = dirLinkCount\n\t\tdefaultMode = dirDefaultMode\n\t\tdefaultSize = dirInitialSize\n\t\tfs.readDirMap[iNodeID] = make(map[fuseops.InodeID]*fuseutil.Dirent)\n\t} else {\n\t\t// dont return error as open file will retry this.\n\t\tfile, err := fs.localCache.Create(fmt.Sprint(iNodeID))\n\t\tif err == nil {\n\t\t\tfs.backingFiles[iNodeID] = &file\n\t\t} else {\n\t\t\tfs.l.Warn(\"failed to create backing file: open file will retry this\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.String(\"child\", childName),\n\t\t\t\tzap.String(\"localfs\", fs.localCache.Name()),\n\t\t\t\tzap.Uint64(\"parent\", uint64(parentINode)))\n\t\t}\n\t}\n\n\td := &fuseutil.Dirent{\n\t\tInode: iNodeID,\n\t\tName: childName,\n\t\tType: nodeType,\n\t}\n\tif !isRoot {\n\t\tfs.insertReadDirEntry(parentINode, d)\n\t}\n\n\tts := time.Now()\n\tattr := fuseops.InodeAttributes{\n\t\tSize: defaultSize,\n\t\tNlink: linkCount,\n\t\tMode: defaultMode,\n\t\tAtime: ts,\n\t\tMtime: ts,\n\t\tCtime: ts,\n\t\tCrtime: ts,\n\t\tUid: defaultGID,\n\t\tGid: defaultUID,\n\t}\n\n\t// iNode Store\n\tfs.iNodeStore, _, _ = fs.iNodeStore.Insert(formKey(iNodeID), &nodeEntry{\n\t\tlock: sync.Mutex{},\n\t\trefCount: 1, // As per spec CreateFileOp\n\t\tpathToBackingFile: getPathToBackingFile(iNodeID),\n\t\tattr: attr,\n\t})\n\n\tif nodeType == fuseutil.DT_Directory {\n\t\t// Increment parent ref count.\n\t\tp, _ := fs.iNodeStore.Get(formKey(parentINode))\n\t\tparentNodeEntry := p.(*nodeEntry)\n\t\tparentNodeEntry.attr.Nlink++\n\t}\n\n\t// If return is expected\n\tif entry != nil {\n\t\tentry.Attributes = attr\n\t\tentry.EntryExpiration = time.Now().Add(cacheYearLong)\n\t\tentry.AttributesExpiration = time.Now().Add(cacheYearLong)\n\t\tentry.Child = iNodeID\n\t}\n\treturn nil\n}", "func checkNodeAllocatableTest(f *framework.Framework) {\n\n\tnodeMem := getNodeMemory(f)\n\tframework.Logf(\"nodeMem says: %+v\", nodeMem)\n\n\t// calculate the allocatable mem based on capacity - reserved amounts\n\tcalculatedNodeAlloc := nodeMem.capacity.Copy()\n\tcalculatedNodeAlloc.Sub(nodeMem.systemReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.kubeReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.softEviction)\n\tcalculatedNodeAlloc.Sub(nodeMem.hardEviction)\n\n\tginkgo.By(fmt.Sprintf(\"Checking stated allocatable memory %v against calculated allocatable memory %v\", &nodeMem.allocatable, calculatedNodeAlloc))\n\n\t// sanity check against stated allocatable\n\tgomega.Expect(calculatedNodeAlloc.Cmp(nodeMem.allocatable)).To(gomega.Equal(0))\n}", "func newNode(k collection.Comparer, v interface{}, h int) *node {\n\tn := &node{K: k, V: v, H: h, C: make([]*node, 2)}\n\treturn n\n}", "func InitNode(ipfsAPIendpoint string) (*Node, error) {\n\n\t// use the API endpoint at the specified port\n\tnewNode := &Node{\n\t\tsh: ipfs.NewShell(ipfsAPIendpoint),\n\t\tallowNetwork: true,\n\t\tidentity: \"\",\n\t}\n\n\t// check it's online\n\tif !newNode.IsOnline() {\n\t\treturn nil, ErrOffline\n\t}\n\n\treturn newNode, nil\n}", "func (_NodeSpace *NodeSpaceTransactor) AddNode(opts *bind.TransactOpts, _nodeAddr common.Address, _locator []byte) (*types.Transaction, error) {\n\treturn _NodeSpace.contract.Transact(opts, \"addNode\", _nodeAddr, _locator)\n}", "func newNode(hash string) Node {\n\treturn Node{hash: hash, parent: nil}\n}", "func (p *Pacemaker) AddNode(rid uint64, cli TiKVClient) {\n\tlg.Debug(\"add tikv client to txn\", zap.Uint64(\"txnid\", p.txnid))\n\tp.Lock()\n\tif _, ok := p.kvnodes[rid]; !ok {\n\t\tp.kvnodes[rid] = cli\n\t}\n\tp.Unlock()\n}", "func NewNode(name string, w Worker) *Node {\n\tid := getID()\n\tn := &Node{id: id, w: w, name: name}\n\tn.chained = make(map[string]struct{})\n\tn.close = make(chan struct{})\n\treturn n\n}", "func (c *Client) CreateNode(config *peer.NodeConfig) (string, error) {\n\tnode := \"\"\n\treturn node, c.Post(\"/nodes\", config, node)\n}", "func (cc *ContrailCommand) CreateNode(host vcenter.ESXIHost) error {\n\tlog.Debug(\"Create Node:\", cc.AuthToken)\n\tnodeResource := contrailCommandNodeSync{\n\t\tResources: []*nodeResources{\n\t\t\t{\n\t\t\t\tKind: \"node\",\n\t\t\t\tData: &nodeData{\n\t\t\t\t\tNodeType: \"esxi\",\n\t\t\t\t\tUUID: host.UUID,\n\t\t\t\t\tHostname: host.Hostname,\n\t\t\t\t\tFqName: []string{\"default-global-system-config\", host.Hostname},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(nodeResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Sending Request\")\n\tresp, _, err := cc.sendRequest(\"/sync\", string(jsonData), \"POST\") //nolint: bodyclose\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Got status : \", resp.StatusCode)\n\tswitch resp.StatusCode {\n\tdefault:\n\t\treturn fmt.Errorf(\"resource creation failed, %d\", resp.StatusCode)\n\tcase 200, 201:\n\t}\n\treturn nil\n}", "func CreateNewRootNode(table *Table, rightNodePageNum uint32) {\n\t// Handle splitting the root.\n\t// Old root copied to new page, becomes left child.\n\t// Address of right child passed in.\n\t// Re-initialize root page to contain the new root node.\n\t// New root node points to two children.\n\tvar rootPage *Page = GetPage(table.Pager, table.RootPageNum)\n\tvar rightPage *Page = GetPage(table.Pager, rightNodePageNum)\n\tvar leftNodePageNum uint32 = GetUnallocatedPageNum(table.Pager)\n\tvar leftPage *Page = GetPage(table.Pager, leftNodePageNum)\n\n\t// The old root page is copied to the left node so we can reuse the root page\n\t// Left child has data copied from old root\n\tif copy(leftPage.Mem[:], rootPage.Mem[:]) != PageSize {\n\t\tos.Exit(util.ExitFailure)\n\t}\n\tSetRootNode(leftPage.Mem[:], false)\n\n\t// Finally we initialize the root page as a new internal node with two children.\n\t// Root node is a new internal node with one key and two children\n\tInitializeInternalNode(rootPage.Mem[:])\n\tSetRootNode(rootPage.Mem[:], true)\n\t*InternalNodeNumKeys(rootPage.Mem[:]) = 1\n\t*InternalNodeChild(rootPage.Mem[:], 0) = leftNodePageNum\n\tvar leftChildMaxKey uint32 = GetNodeMaxKeys(leftPage.Mem[:])\n\t*InternalNodeKey(rootPage.Mem[:], 0) = leftChildMaxKey\n\t*internalNodeRightChildPtr(rootPage.Mem[:]) = rightNodePageNum\n\n\t// Update Parent node to root node page\n\t*ParentNode(leftPage.Mem[:]) = table.RootPageNum\n\t*ParentNode(rightPage.Mem[:]) = table.RootPageNum\n}", "func AddNode(namespace string, clusterName string, req *app.NodeReq) (*model.NodeList, error) {\n\n\t// validate namespace\n\tif err := verifyNamespace(namespace); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get a cluster-entity\n\tcluster := model.NewCluster(namespace, clusterName)\n\tif exists, err := cluster.Select(); err != nil {\n\t\treturn nil, err\n\t} else if exists == false {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Could not be found a cluster '%s'. (namespace=%s)\", clusterName, namespace))\n\t} else if cluster.Status.Phase != model.ClusterPhaseProvisioned {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Unable to add a node. status is '%s'.\", cluster.Status.Phase))\n\t}\n\n\t// get a MCIS\n\tmcis := tumblebug.NewMCIS(namespace, cluster.MCIS)\n\tif exists, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t} else if !exists {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Can't be found a MCIS '%s'.\", cluster.MCIS))\n\t}\n\tlogger.Infof(\"[%s.%s] The inquiry has been completed..\", namespace, clusterName)\n\n\tmcisName := cluster.MCIS\n\n\tif cluster.ServiceType == app.ST_SINGLE {\n\t\tif len(mcis.VMs) > 0 {\n\t\t\tconnection := mcis.VMs[0].Config\n\t\t\tfor _, worker := range req.Worker {\n\t\t\t\tif worker.Connection != connection {\n\t\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"The new node must be the same connection config. (connection=%s)\", worker.Connection))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"There is no VMs. (cluster=%s)\", clusterName))\n\t\t}\n\t}\n\n\t// get a provisioner\n\tprovisioner := provision.NewProvisioner(cluster)\n\n\t/*\n\t\tif err := provisioner.BuildAllMachines(); err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to build provisioner's map: %v\", err))\n\t\t}\n\t*/\n\n\t// get join command\n\tworkerJoinCmd, err := provisioner.NewWorkerJoinCommand()\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to get join-command (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Worker join-command inquiry has been completed. (command=%s)\", namespace, clusterName, workerJoinCmd)\n\n\tvar workerCSP app.CSP\n\n\t// create a MCIR & MCIS-vm\n\tidx := cluster.NextNodeIndex(app.WORKER)\n\tvar vmgroupid []string\n\tfor _, worker := range req.Worker {\n\t\tmcir := NewMCIR(namespace, app.WORKER, *worker)\n\t\treason, msg := mcir.CreateIfNotExist()\n\t\tif reason != \"\" {\n\t\t\treturn nil, errors.New(msg)\n\t\t} else {\n\t\t\tfor i := 0; i < mcir.vmCount; i++ {\n\t\t\t\tname := lang.GenerateNewNodeName(string(app.WORKER), idx)\n\t\t\t\tif i == 0 {\n\t\t\t\t\tworkerCSP = mcir.csp\n\t\t\t\t}\n\t\t\t\tvm := mcir.NewVM(namespace, name, mcisName, \"\", worker.RootDisk.Type, worker.RootDisk.Size)\n\t\t\t\tif err := vm.POST(); err != nil {\n\t\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvmgroupid = append(vmgroupid, name)\n\t\t\t\tprovisioner.AppendWorkerNodeMachine(name+\"-1\", mcir.csp, mcir.region, mcir.zone, mcir.credential)\n\t\t\t\tidx = idx + 1\n\t\t\t}\n\t\t}\n\t}\n\t// Pull out the added VMlist\n\tif _, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t}\n\tvms := []tumblebug.VM{}\n\tfor _, mcisvm := range mcis.VMs {\n\t\tfor _, grupid := range vmgroupid {\n\t\t\tif mcisvm.VmGroupId == grupid {\n\t\t\t\tmcisvm.Namespace = namespace\n\t\t\t\tmcisvm.McisName = mcisName\n\t\t\t\tvms = append(vms, mcisvm)\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] MCIS(vm) creation has been completed. (len=%d)\", namespace, clusterName, len(vms))\n\n\t// save nodes metadata\n\tif nodes, err := provisioner.BindVM(vms); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcluster.Nodes = append(cluster.Nodes, nodes...)\n\t\tif err := cluster.PutStore(); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t\t}\n\t}\n\n\t// kubernetes provisioning : bootstrap\n\ttime.Sleep(2 * time.Second)\n\tif err := provisioner.Bootstrap(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Bootstrap failed. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Bootstrap has been completed.\", namespace, clusterName)\n\n\t// kubernetes provisioning : worker node join\n\tfor _, machine := range provisioner.WorkerNodeMachines {\n\t\tif err := machine.JoinWorker(&workerJoinCmd); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Fail to worker-node join. (node=%s)\", machine.Name))\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] Woker-nodes join has been completed.\", namespace, clusterName)\n\n\t/* FIXME: after joining, check the worker is ready */\n\n\t// assign node labels (topology.cloud-barista.github.io/csp , topology.kubernetes.io/region, topology.kubernetes.io/zone)\n\tif err = provisioner.AssignNodeLabelAnnotation(); err != nil {\n\t\tlogger.Warnf(\"[%s.%s] Failed to assign node labels (cause='%v')\", namespace, clusterName, err)\n\t} else {\n\t\tlogger.Infof(\"[%s.%s] Node label assignment has been completed.\", namespace, clusterName)\n\t}\n\n\t// kubernetes provisioning : add some actions for cloud-controller-manager\n\tif provisioner.Cluster.ServiceType == app.ST_SINGLE {\n\t\tif workerCSP == app.CSP_AWS {\n\t\t\t// check whether AWS IAM roles exists and are same\n\t\t\tvar bFail bool = false\n\t\t\tvar bEmptyOrDiff bool = false\n\t\t\tvar msgError string\n\t\t\tvar awsWorkerRole string\n\n\t\t\tawsWorkerRole = req.Worker[0].Role\n\t\t\tif awsWorkerRole == \"\" {\n\t\t\t\tbEmptyOrDiff = true\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == false {\n\t\t\t\tfor _, worker := range req.Worker {\n\t\t\t\t\tif awsWorkerRole != worker.Role {\n\t\t\t\t\t\tbEmptyOrDiff = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == true {\n\t\t\t\tbFail = true\n\t\t\t\tmsgError = \"Role should be assigned\"\n\t\t\t} else {\n\t\t\t\tif err := awsPrepareCCM(req.Worker[0].Connection, clusterName, vms, provisioner, \"\", awsWorkerRole); err != nil {\n\t\t\t\t\tbFail = true\n\t\t\t\t\tmsgError = \"Failed to prepare cloud-controller-manager\"\n\t\t\t\t} else {\n\t\t\t\t\t// Success\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bFail == true {\n\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity: %v)\", msgError))\n\t\t\t} else {\n\t\t\t\t// Success\n\t\t\t\tlogger.Infof(\"[%s.%s] CCM ready has been completed.\", namespace, clusterName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// save nodes metadata & update status\n\tfor _, node := range cluster.Nodes {\n\t\tnode.CreatedTime = lang.GetNowUTC()\n\t}\n\tif err := cluster.PutStore(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Nodes creation has been completed.\", namespace, clusterName)\n\n\tnodes := model.NewNodeList(namespace, clusterName)\n\tnodes.Items = cluster.Nodes\n\treturn nodes, nil\n}", "func NewNode(n *pb.Node) *Node {\n\treturn &Node{\n\t\tX: int(n.X),\n\t\tY: int(n.Y),\n\t\tPlayer: int(n.Player),\n\t}\n}", "func (gortn *goroutine) AddNode(node sesstype.Node) {\n\tif gortn.leaf == nil {\n\t\tpanic(\"AddNode: leaf cannot be nil\")\n\t}\n\n\tnewLeaf := (*gortn.leaf).Append(node)\n\tgortn.leaf = &newLeaf\n}", "func NewNode(weightInitializer WeightInitializer, activationFunction ActivationFunction, derivativeActivation DerivativeActivation, nodeIndex int, learningRate FloatXX, layerIndex int, derivativeError DerivativeError, nodeType NodeType) *Node {\n\treturn &Node{\n\t\tinputNodes: nil,\n\t\toutputNodes: nil,\n\t\tweightInitializer: weightInitializer,\n\t\tactivation: activationFunction,\n\t\tderivativeActivation: derivativeActivation,\n\t\tmyIndex: nodeIndex,\n\t\tlearningRate: learningRate,\n\t\tlayerIndex: layerIndex,\n\t\tderivativeError: derivativeError,\n\t\tweights: []FloatXX{},\n\t\tmyType: nodeType,\n\t\tinputValue: FloatXX(0.0),\n\t\tlabel: FloatXX(0.0),\n\t\tmyErr: FloatXX(0.0),\n\t\tdEdW: []FloatXX{},\n\t\tmyoutCached: false,\n\t\tmyout: FloatXX(0.0),\n\t\tbackCached: false,\n\t\tinputs: []FloatXX{},\n\t\tdEdOut: FloatXX(0.0),\n\t\tdOutdIn: FloatXX(0.0),\n\t\tdIndW: []FloatXX{},\n\t}\n}", "func CreateNode(value int) *Node {\n\treturn &Node{Value: value}\n}", "func (s *Arena) getNode(offset uint32) *node {\n\tif offset == 0 {\n\t\treturn nil\n\t}\n\treturn (*node)(unsafe.Pointer(&s.data[offset]))\n}", "func (vns *VirtualNetworkService) Allocate(ctx context.Context, vnBlueprint blueprint.Interface,\n\tcluster resources.Cluster) (*resources.VirtualNetwork, error) {\n\tclusterID, err := cluster.ID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblueprintText, err := vnBlueprint.Render()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresArr, err := vns.call(ctx, \"one.vn.allocate\", blueprintText, clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vns.RetrieveInfo(ctx, int(resArr[resultIndex].ResultInt()))\n}", "func (m *InstancesManager) CreateNode(obj *v2.CiliumNode, n *ipam.Node) ipam.NodeOperations {\n\treturn &Node{manager: m, node: n}\n}", "func (c *HashRing) AddNode(ip string, weight int) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tif weight <= 0 {\n\t\tweight = 1\n\t}\n\tfor i := 0; i < c.numberOfCubes*weight; i++ {\n\t\tc.ring[c.generateHash(c.generateKey(ip, i))] = ip\n\t}\n\tc.members[ip] = true\n\tc.weights[ip] = weight\n\n\tc.updateSortedRing()\n}", "func NewNode(tr Transaction, id string) *Node {\n\tif tr == nil {\n\t\tpanic(\"transaction may not be nil\")\n\t}\n\tif id == \"\" {\n\t\tid = uuid.NewV4().String()\n\t}\n\n\tn := &Node{\n\t\tTransaction: tr,\n\t\tId: id,\n\t}\n\n\tn.Reset()\n\treturn n\n\n\t/*\n\t\tpos := strings.Index(id, \"-\")\n\t\tif pos == -1 {\n\t\t\tn.Shard = id\n\t\t\tn.UUID = uuid.NewV4().String()\n\t\t} else {\n\t\t\tn.UUID = id[pos+1:]\n\t\t\tn.Shard = id[:pos]\n\t\t}\n\t*/\n\t// return n\n}", "func (rg *ResourceGroup) assignNode(id int64, deltaCapacity int) error {\n\tif rg.containsNode(id) {\n\t\treturn ErrNodeAlreadyAssign\n\t}\n\n\trg.nodes.Insert(id)\n\trg.capacity += deltaCapacity\n\n\treturn nil\n}", "func (np *NodePool) Node(id PolyRef, state uint8) *Node {\n\tbucket := hashRef(id) & uint32(np.hashSize-1)\n\n\tvar i NodeIndex\n\ti = np.first[bucket]\n\tvar node *Node\n\tfor i != nullIdx {\n\t\tif np.nodes[i].ID == id && np.nodes[i].State == state {\n\t\t\treturn &np.nodes[i]\n\t\t}\n\t\ti = np.next[i]\n\t}\n\n\tif np.nodeCount >= np.maxNodes {\n\t\treturn nil\n\t}\n\n\ti = NodeIndex(np.nodeCount)\n\tnp.nodeCount++\n\n\t// Init node\n\tnode = &np.nodes[i]\n\tnode.PIdx = 0\n\tnode.Cost = 0\n\tnode.Total = 0\n\tnode.ID = id\n\tnode.State = state\n\tnode.Flags = 0\n\n\tnp.next[i] = np.first[bucket]\n\tnp.first[bucket] = i\n\n\treturn node\n}", "func (sc *PintaCache) addNode(node *v1.Node) error {\n\tif sc.Nodes[node.Name] != nil {\n\t\tsc.Nodes[node.Name].SetNode(node)\n\t} else {\n\t\tsc.Nodes[node.Name] = info.NewNodeInfo(node)\n\t}\n\treturn nil\n}" ]
[ "0.67350614", "0.66224706", "0.6255893", "0.62361896", "0.58610564", "0.5856234", "0.573066", "0.57271", "0.5717261", "0.5710908", "0.5661831", "0.5650009", "0.56370544", "0.56184864", "0.55880314", "0.55836654", "0.5574136", "0.55566436", "0.5539488", "0.5515493", "0.5494545", "0.5443041", "0.5438003", "0.54197145", "0.54180825", "0.54082316", "0.5400205", "0.5396748", "0.53891194", "0.5387387", "0.5375944", "0.53731114", "0.53660923", "0.5357034", "0.53536665", "0.53452986", "0.5331645", "0.53309566", "0.5315522", "0.53130025", "0.53126055", "0.5306062", "0.52965873", "0.5279149", "0.5265667", "0.52564824", "0.5254148", "0.52520114", "0.5247065", "0.52242184", "0.522266", "0.5211909", "0.52113104", "0.519732", "0.51722234", "0.5168419", "0.5149499", "0.5149497", "0.5146446", "0.51349646", "0.51304334", "0.5124903", "0.51245993", "0.51087844", "0.510837", "0.51032794", "0.5099727", "0.5093389", "0.5092464", "0.5087179", "0.50827783", "0.50814945", "0.50690055", "0.506779", "0.5064144", "0.5060852", "0.5053305", "0.5052487", "0.50520873", "0.50489783", "0.5048548", "0.5046828", "0.5042017", "0.5039781", "0.50397503", "0.50346947", "0.50313133", "0.5028596", "0.502488", "0.5011302", "0.5007563", "0.49956995", "0.49949658", "0.49920753", "0.49918693", "0.4991561", "0.49888897", "0.49859947", "0.49856767", "0.49785948" ]
0.7961014
0
allocateNodeWithPrefix returns the new node and its data block, positioned after the prefix
allocateNodeWithPrefix возвращает новый узел и его данные, расположенные после префикса
func (idx *Tree) allocateNodeWithPrefix(a *Allocator, count int, prefix []byte) (n uint64, data []uint64) { prefixLen := len(prefix) prefixSlots := (prefixLen + 7) >> 3 if prefixLen >= 255 { prefixSlots++ } count += prefixSlots n = a.newNode(count) block := int(n >> blockSlotsShift) offset := int(n & blockSlotsOffsetMask) data = idx.blocks[block].data[offset:] if prefixLen > 0 { storePrefix(data, prefix) data = data[prefixSlots:] } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (idx *Tree) allocateNode(a *Allocator, count int, prefixLen int) (n uint64, data []uint64) {\n\tprefixSlots := (prefixLen + 7) >> 3\n\tif prefixLen >= 255 {\n\t\tprefixSlots++\n\t}\n\tcount += prefixSlots\n\tn = a.newNode(count)\n\tblock := int(n >> blockSlotsShift)\n\toffset := int(n & blockSlotsOffsetMask)\n\tdata = idx.blocks[block].data[offset:]\n\treturn\n}", "func (n *nodeHeader) setPrefix(p []byte) {\n\tpLen, pBytes := n.prefixFields()\n\n\t// Write to the byte array and set the length field to the num bytes copied\n\t*pLen = uint16(copy(pBytes, p))\n}", "func (n *nodeHeader) prefix() []byte {\n\tpLen, pBytes := n.prefixFields()\n\n\tif *pLen <= maxPrefixLen {\n\t\t// We have the whole prefix from the node\n\t\treturn pBytes[0:*pLen]\n\t}\n\n\t// Prefix is too long for node, we have to go find it from the leaf\n\tminLeaf := n.minChild().leafNode()\n\treturn minLeaf.key[0:*pLen]\n}", "func (t *Trie) getNodeAtPrefix(prefix string) (*Node, error) {\n\trunner := t.Root\n\n\tfor _, currChar := range prefix {\n\t\tif _, ok := runner.Children[currChar]; !ok {\n\t\t\treturn nil, errors.New(\"prefix not found\")\n\t\t}\n\t\trunner = runner.Children[currChar]\n\t}\n\n\treturn runner, nil\n}", "func (n Node) generatePrefix() string {\n\tindicator := \"├── \"\n\tif n.isLastElement() {\n\t\tindicator = \"└── \"\n\t}\n\n\treturn n.getPrefixes() + indicator\n}", "func (f *MemKv) newPrefixWatcher(ctx context.Context, prefix string, fromVersion string) (*watcher, error) {\n\tif !strings.HasSuffix(prefix, \"/\") {\n\t\tprefix += \"/\"\n\t}\n\treturn f.watch(ctx, prefix, fromVersion, true)\n}", "func generateKeyPrefixData(prefix []byte) []byte {\n\treturn append(prefix, []byte(\":data\")...)\n}", "func resourceNetboxIpamPrefixCreate(d *schema.ResourceData, meta interface{}) error {\n\tnetboxClient := meta.(*ProviderNetboxClient).client\n\n\tprefix := d.Get(\"prefix\").(string)\n\tdescription := d.Get(\"description\").(string)\n\tvrfID := int64(d.Get(\"vrf_id\").(int))\n\tisPool := d.Get(\"is_pool\").(bool)\n\t//status := d.Get(\"status\").(string)\n\ttenantID := int64(d.Get(\"tenant_id\").(int))\n\n\tvar parm = ipam.NewIPAMPrefixesCreateParams().WithData(\n\t\t&models.PrefixCreateUpdate{\n\t\t\tPrefix: &prefix,\n\t\t\tDescription: description,\n\t\t\tIsPool: isPool,\n\t\t\tTags: []string{},\n\t\t\tVrf: vrfID,\n\t\t\tTenant: tenantID,\n\t\t},\n\t)\n\n\tlog.Debugf(\"Executing IPAMPrefixesCreate against Netbox: %v\", parm)\n\n\tout, err := netboxClient.IPAM.IPAMPrefixesCreate(parm, nil)\n\n\tif err != nil {\n\t\tlog.Debugf(\"Failed to execute IPAMPrefixesCreate: %v\", err)\n\n\t\treturn err\n\t}\n\n\t// TODO Probably a better way to parse this ID\n\td.SetId(fmt.Sprintf(\"ipam/prefix/%d\", out.Payload.ID))\n\td.Set(\"prefix_id\", out.Payload.ID)\n\n\tlog.Debugf(\"Done Executing IPAMPrefixesCreate: %v\", out)\n\n\treturn nil\n}", "func newPrefix(targetPrefix []string) (prefixes []models.Prefix, err error) {\n\tprefixes = make([]models.Prefix, len(targetPrefix))\n\tfor i, cidr := range targetPrefix {\n\t\tprefix, err := models.NewPrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprefixes[i] = prefix\n\t}\n\treturn\n}", "func (list *List) PrependToBeginning(data int) {\n // 1. Create a new node\n newNode := &Node{data: data, next: nil}\n\n // 2. Point the new node's next to current head\n newNode.next = list.Head()\n\n // 3. Update the list's head as the new node\n list.head = newNode\n\n // 4. Increment the list size\n list.size++\n}", "func (db *MemoryCache) NewIteratorWithPrefix(prefix []byte) Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tvar (\n\t\tpr = string(prefix)\n\t\tkeys = make([]string, 0, len(db.db))\n\t\tvalues = make([][]byte, 0, len(db.db))\n\t)\n\t// Collect the keys from the memory database corresponding to the given prefix\n\tfor key := range db.db {\n\t\tif strings.HasPrefix(key, pr) {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\t// Sort the items and retrieve the associated values\n\tsort.Strings(keys)\n\tfor _, key := range keys {\n\t\tvalues = append(values, db.db[key])\n\t}\n\treturn &iterator{\n\t\tkeys: keys,\n\t\tvalues: values,\n\t}\n}", "func NewPrefix(addrString string) (p Prefix, err error) {\n\t_, ipNet, err := net.ParseCIDR(addrString)\n\tif err != nil {\n\t\treturn\n\t}\n\tsz, _ := ipNet.Mask.Size()\n\tp = Prefix{ipNet, ipNet.IP.String(), sz}\n\n\treturn\n}", "func (addr DevAddr) WithPrefix(prefix DevAddrPrefix) (prefixed DevAddr) {\n\tk := uint(prefix.Length)\n\tfor i := 0; i < 4; i++ {\n\t\tif k >= 8 {\n\t\t\tprefixed[i] = prefix.DevAddr[i] & 0xff\n\t\t\tk -= 8\n\t\t\tcontinue\n\t\t}\n\t\tprefixed[i] = (prefix.DevAddr[i] & ^byte(0xff>>k)) | (addr[i] & byte(0xff>>k))\n\t\tk = 0\n\t}\n\treturn\n}", "func (defintion *IndexDefinition) AddPrefix(prefix string) (outDef *IndexDefinition) {\n\toutDef = defintion\n\toutDef.Prefix = append(outDef.Prefix, prefix)\n\treturn\n}", "func (creator *metricCreatorBase) AddOrGetPrefix(prefix string, labelNames []string, labelValues []string) MetricCreator {\n\tfullPrefix, allLabelNames, allLabelValues := creator.concatNameAndLabels(prefix, labelNames, labelValues)\n\n\tcreator.root.mapLock.Lock()\n\tdefer creator.root.mapLock.Unlock()\n\n\treturn &metricCreatorBase{\n\t\tfullPrefix: fullPrefix,\n\t\tfixedLabelNames: allLabelNames,\n\t\tfixedLabelValues: allLabelValues,\n\t\tlogger: creator.logger.WithFields(logger.Fields{\n\t\t\t\"prefix\": fullPrefix,\n\t\t\t\"labelNames\": labelNames,\n\t\t\t\"labelValues\": labelValues,\n\t\t}),\n\t\troot: creator.root,\n\t}\n}", "func NewPrefix(p string) *Prefix {\n\tif len(p) > 0 && p[0] == '_' {\n\t\tp = p[1:]\n\t}\n\tpp := Prefix(p)\n\treturn &pp\n}", "func (rad *Radix) Prefix(prefix string) *list.List {\n\trad.lock.Lock()\n\tdefer rad.lock.Unlock()\n\tl := list.New()\n\tn, _ := rad.root.lookup([]rune(prefix))\n\tif n == nil {\n\t\treturn l\n\t}\n\tn.addToList(l)\n\treturn l\n}", "func add_section_name(\npar int32,/* parent of new node */\nc int,/* right or left? */\nname[]rune,/* section name */\nispref bool/* are we adding a prefix or a full name? */)int32{\np:=int32(len(name_dir))/* new node */\nname_dir= append(name_dir,name_info{})\nname_dir[p].llink= -1\ninit_node(p)\nif ispref{\nname_dir= append(name_dir,name_info{})\nname_dir[p+1].llink= -1\ninit_node(p+1)\n}\nname_dir[p].ispref= ispref\nname_dir[p].name= append(name_dir[p].name,int32(len(name)))/* length of section name */\nname_dir[p].name= append(name_dir[p].name,name...)\nname_dir[p].llink= -1\nname_dir[p].rlink= -1\ninit_node(p)\nif par==-1{\nname_root= p\n}else{\nif c==less{\nname_dir[par].llink= p\n}else{\nname_dir[par].rlink= p\n}\n}\nreturn p\n}", "func (p *Periph) StorePREFIX(n int, prefix uint32) {\n\tp.prefix[n].Store(prefix)\n}", "func NewPrefix(v string) Value {\n\treturn prefixValue(v)\n}", "func (c Node) NamePrefix() string {\n\treturn fmt.Sprintf(\"bpm-%s-\", c.ID)\n}", "func (n *Node) HasPrefix(prefix string) (*Node, error) {\n\tletters := []rune(prefix)\n\tcurrent := n\n\tfor i := 0; current != nil && i < len(letters); i++ {\n\t\tcurrent = current.GetChild(letters[i])\n\t}\n\tif current == nil {\n\t\terr := fmt.Errorf(\"%s not found\", prefix)\n\t\treturn nil, err\n\t}\n\treturn current, nil\n}", "func (tbl RecordTable) WithPrefix(pfx string) RecordTable {\n\ttbl.name.Prefix = pfx\n\treturn tbl\n}", "func (tx *remoteTx) ForPrefix(bucket string, prefix []byte, walker func(k, v []byte) error) error {\n\tc, err := tx.Cursor(bucket)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Close()\n\n\tfor k, v, err := c.Seek(prefix); k != nil; k, v, err = c.Next() {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !bytes.HasPrefix(k, prefix) {\n\t\t\tbreak\n\t\t}\n\t\tif err := walker(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tswitch {\n\tcase db.db == nil:\n\t\treturn &nodb.Iterator{Err: database.ErrClosed}\n\tcase db.corrupted():\n\t\treturn &nodb.Iterator{Err: database.ErrAvoidCorruption}\n\t}\n\n\tit := db.db.NewIterator(db.iteratorOptions)\n\tif it == nil {\n\t\treturn &nodb.Iterator{Err: errFailedToCreateIterator}\n\t}\n\tit.Seek(prefix)\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t\tprefix: prefix,\n\t}\n}", "func (ms *memoryStore) Add(prefix, base string) (*NameSpace, error) {\n\tns, err := ms.GetWithPrefix(prefix)\n\tif err != nil {\n\t\tif err != ErrNameSpaceNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ns != nil {\n\t\terr = ns.AddBase(base)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ns, nil\n\t}\n\n\tns, err = ms.GetWithBase(base)\n\tif err != nil {\n\t\tif err != ErrNameSpaceNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ns != nil {\n\t\terr = ns.AddPrefix(prefix)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ns, nil\n\n\t}\n\n\tns = &NameSpace{\n\t\tPrefix: prefix,\n\t\tBase: base,\n\t}\n\terr = ms.Set(ns)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ns, nil\n}", "func SpawnPrefix(props *Props, prefix string) *PID {\n\treturn EmptyRootContext.SpawnPrefix(props, prefix)\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.searchPrefix(prefix)\n \n return node != nil\n}", "func prefixIndex(addr uint8, prefixLen int) int {\n\t// the prefixIndex of addr/prefixLen is the prefixLen most significant bits\n\t// of addr, with a 1 tacked onto the left-hand side. For example:\n\t//\n\t// - 0/0 is 1: 0 bits of the addr, with a 1 tacked on\n\t// - 42/8 is 1_00101010 (298): all bits of 42, with a 1 tacked on\n\t// - 48/4 is 1_0011 (19): 4 most-significant bits of 48, with a 1 tacked on\n\treturn (int(addr) >> (8 - prefixLen)) + (1 << prefixLen)\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func (allc *Allocator) makeNode(truncatedSize uint32) uint32 {\n\t// Calculate the amount of actual memory required for this node.\n\t// Depending on the height of the node, size might be truncated.\n\tsize := defaultNodeSize - truncatedSize\n\t/*padding := size % cacheLineSize\n\tif padding < paddingLimit {\n\t\tsize += padding\n\t}*/\n\treturn allc.new(size)\n}", "func NewWithPrefix(pool *redis.Pool, prefix string) *RedisStore {\n\treturn &RedisStore{\n\t\tpool: pool,\n\t\tprefix: prefix,\n\t}\n}", "func (o InventoryDestinationBucketPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InventoryDestinationBucket) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func NewTree(prefix, delimiter string) *Node {\n\treturn &Node{\n\t\tname: prefix,\n\t\tdelimiter: delimiter,\n\t\tnodes: make(map[string]*Node),\n\t}\n}", "func ReserveHasPrefix(v string) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldReserve), v))\n\t})\n}", "func (ms *memoryStore) GetWithPrefix(prefix string) (*NameSpace, error) {\n\tms.RLock()\n\tdefer ms.RUnlock()\n\tns, ok := ms.prefix2base[prefix]\n\tif !ok {\n\t\treturn nil, ErrNameSpaceNotFound\n\t}\n\treturn ns, nil\n}", "func (tbl DbCompoundTable) WithPrefix(pfx string) DbCompoundTable {\n\ttbl.name.Prefix = pfx\n\treturn tbl\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tbytes := []byte(prefix)\n\tif len(bytes) <= 0 {\n\t\treturn true\n\t}\n\tfor _, value := range bytes {\n\t\t//如果数据存在\n\t\tif _, ok := this.nexts[value]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tthis = this.nexts[value]\n\t}\n\treturn true\n}", "func NewPrefixWriter(prefix string, writer types.ArchiveWriter) types.ArchiveWriter {\n\treturn &prefixWriter{\n\t\tprefix: prefix,\n\t\twriter: writer,\n\t}\n}", "func WithPrefix(value string) *Entry {\n\treturn NewDefaultEntry().WithField(\"prefix\", value)\n}", "func (pq *PrefixQueue) Enqueue(prefix, value []byte) (*Item, error) {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\t// Check if queue is closed.\n\tif !pq.isOpen {\n\t\treturn nil, ErrDBClosed\n\t}\n\n\t// Get the queue for this prefix.\n\tq, err := pq.getOrCreateQueue(prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create new Item.\n\titem := &Item{\n\t\tID: q.Tail + 1,\n\t\tKey: generateKeyPrefixID(prefix, q.Tail+1),\n\t\tValue: value,\n\t}\n\n\t// Add it to the queue.\n\tif err := pq.db.Put(item.Key, item.Value, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Increment tail position and prefix queue size.\n\tq.Tail++\n\tpq.size++\n\n\t// Save the queue.\n\tif err := pq.saveQueue(prefix, q); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save main prefix queue data.\n\tif err := pq.save(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item, nil\n}", "func newFileWithPrefix(t *testing.T, prefix, text string) (*os.File, error) {\n\ttmpFile, err := ioutil.TempFile(os.TempDir(), prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Cleanup(func() {\n\t\tos.Remove(tmpFile.Name())\n\t})\n\n\tb := []byte(text)\n\t_, err = tmpFile.Write(b)\n\n\treturn tmpFile, err\n}", "func NewTokenHasPrefix(v string) predicate.User {\n\treturn predicate.User(sql.FieldHasPrefix(FieldNewToken, v))\n}", "func GenerateWithPrefix(size int, prefix string) string {\n\tsize = size - 1 - len(prefix)\n\n\trandom := prefix + randomString(size)\n\tcontrolDigit := strconv.Itoa(generateControlDigit(random))\n\n\treturn random + controlDigit\n}", "func generatePrefixed(prefix string, count *int64, found chan<- result, stop <-chan struct{}) {\n\tnotBefore := time.Now()\n\tnotAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)\n\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: new(big.Int).SetInt64(mr.Int63()),\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: \"syncthing\",\n\t\t},\n\t\tNotBefore: notBefore,\n\t\tNotAfter: notAfter,\n\n\t\tKeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},\n\t\tBasicConstraintsValid: true,\n\t}\n\n\tpriv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tderBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tid := protocol.NewDeviceID(derBytes)\n\t\tatomic.AddInt64(count, 1)\n\n\t\tif strings.HasPrefix(id.String(), prefix) {\n\t\t\tselect {\n\t\t\tcase found <- result{id, priv, derBytes}:\n\t\t\tcase <-stop:\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *Parser) registerPrefix(tokenType token.TokenType, fn prefixParseFn) {\n\tp.prefixParseFns[tokenType] = fn\n}", "func leading(length int) *xmlx.Node {\n\treturn newnode(xmlx.NT_TEXT, \"\", \"\\n\"+strings.Repeat(\"\\t\", length))\n}", "func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {\n\tsearch := prefix\n\tfor {\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\n\t\t} else if bytes.HasPrefix(n.prefix, search) {\n\t\t\t// Child may be under our search prefix\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (o InventoryDestinationBucketOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InventoryDestinationBucket) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (p *Parser) registerPrefix(tokenType token.TokenType, fn PrefixParseFn) {\n\tp.prefixParseFns[tokenType] = fn\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n\tnode := this.searchPrefix(prefix)\n\tif node == nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func NewBranchWithPrefix(parent *Logger, prefix string) *Logger {\n\treturn &Logger{parent: parent, prefix: prefix}\n}", "func NewPrefixBucket(\n\tprefix string,\n\twrapped gcs.Bucket) (b gcs.Bucket, err error) {\n\tif !utf8.ValidString(prefix) {\n\t\terr = errors.New(\"prefix is not valid UTF-8\")\n\t\treturn\n\t}\n\n\tb = &prefixBucket{\n\t\tprefix: prefix,\n\t\twrapped: wrapped,\n\t}\n\n\treturn\n}", "func newPrefixDefinedWriter(writer prefixWriteCloser, prefixLen int) *prefixDefinedWriter {\n\tif prefixLen < 0 {\n\t\tpanic(fmt.Errorf(\"newPrefixDefinedWriter: invalid prefixLen %v\", prefixLen))\n\t}\n\tif writer == nil {\n\t\tpanic(fmt.Errorf(\"newPrefixDefinedWriter: nil writer\"))\n\t}\n\treturn &prefixDefinedWriter{\n\t\tprefixLen: prefixLen,\n\t\tprefix: make([]byte, 0, prefixLen),\n\t\tw: writer}\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func (c *FileSystemCache) Prefix(p ...string) Cache {\n\tc.prefix = p\n\treturn c\n}", "func (t *Trie) FindWithPrefix(p string) (counts map[string]int) {\n\tcounts = make(map[string]int)\n\tcharIdx := p[0] - 'a'\n\tt.children[charIdx].findWithPrefix(p, &counts)\n\treturn\n}", "func (fps *FetcherProcessStream) SetPrefix(prefix string) *FetcherProcessStream {\n\tfps.prefix = prefix + \" \"\n\treturn fps\n}", "func (t *Trie) StartWith(prefix string) bool {\n\tcurr := t.Root\n\tfor _, char := range prefix {\n\t\tif _, ok := curr.Children[char]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcurr = curr.Children[char]\n\t}\n\treturn true\n}", "func (p *Parser) registerPrefix(tokenType token.Type, fn prefixParseFn) {\n\tp.prefixParseFns[tokenType] = fn\n}", "func SetPrefix(p string) {\n\tprefix = p\n}", "func GraphPrefix() []byte {\n\treturn graphPrefix\n}", "func (t *BPTree) PrefixScan(prefix []byte, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func ParsePrefix(line string) *Prefix {\n\t// Start by creating an Prefix with nothing but the host\n\tid := &Prefix{\n\t\tName: line,\n\t}\n\n\tuh := strings.SplitN(id.Name, \"@\", 2)\n\tif len(uh) == 2 {\n\t\tid.Name, id.Host = uh[0], uh[1]\n\t}\n\n\tnu := strings.SplitN(id.Name, \"!\", 2)\n\tif len(nu) == 2 {\n\t\tid.Name, id.User = nu[0], nu[1]\n\t}\n\n\treturn id\n}", "func StartNewNode(\n\tconfig *Config,\n\tinitialNetworkState *pb.NetworkState,\n\tinitialCheckpointValue []byte,\n) (*Node, error) {\n\treturn RestartNode(\n\t\tconfig,\n\t\t&dummyWAL{\n\t\t\tinitialNetworkState: initialNetworkState,\n\t\t\tinitialCheckpointValue: initialCheckpointValue,\n\t\t},\n\t)\n}", "func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {\n\treturn &iter{\n\t\tdb: db,\n\t\tIterator: db.DB.NewIterator(util.BytesPrefix(prefix), nil),\n\t}\n}", "func (s *IPSet) AddPrefix(p IPPrefix) { s.AddRange(p.Range()) }", "func (s *IPSet) AddPrefix(p IPPrefix) { s.AddRange(p.Range()) }", "func prefix(k string) *goraptor.Uri {\n\tvar pref string\n\trest := k\n\tif i := strings.Index(k, \":\"); i >= 0 {\n\t\tpref = k[:i+1]\n\t\trest = k[i+1:]\n\t}\n\tif long, ok := rdfPrefixes[pref]; ok {\n\t\tpref = long\n\t}\n\turi := goraptor.Uri(pref + rest)\n\treturn &uri\n}", "func (pars *Parser) parsePrefixExpression() tree.Expression {\n\texpression := &tree.PrefixExpression{\n\t\tToken: pars.thisToken,\n\t\tOperator: pars.thisToken.Val,\n\t}\n\n\tpars.nextToken()\n\n\texpression.Right = pars.parseExpression(PREFIX)\n\treturn expression\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.root\n for _, r := range prefix {\n child, existed := node.children[r]\n if !existed {\n return false\n }\n node = child\n }\n return true\n}", "func createNode(addr string, nodeStmts map[string]ast.Stmt) *ast.Node {\n\tnID := \"n\" + strings.Replace(addr, \".\", \"\", -1)\n\tnID = strings.Replace(nID, \":\", \"\", -1)\n\tn := &ast.Node{ID: nID}\n\tnodeStmts[n.ID] = &ast.NodeStmt{\n\t\tNode: n,\n\t\tAttrs: []*ast.Attr{\n\t\t\t{\n\t\t\t\tKey: \"label\",\n\t\t\t\tVal: fmt.Sprintf(`\"%s\"`, addr),\n\t\t\t},\n\t\t},\n\t}\n\treturn n\n}", "func (db *Database) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tswitch {\n\tcase db.db == nil:\n\t\treturn &nodb.Iterator{Err: database.ErrClosed}\n\tcase db.corrupted():\n\t\treturn &nodb.Iterator{Err: database.ErrAvoidCorruption}\n\t}\n\n\tit := db.db.NewIterator(db.iteratorOptions)\n\tif it == nil {\n\t\treturn &nodb.Iterator{Err: errFailedToCreateIterator}\n\t}\n\tif bytes.Compare(start, prefix) == 1 {\n\t\tit.Seek(start)\n\t} else {\n\t\tit.Seek(prefix)\n\t}\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t\tprefix: prefix,\n\t}\n}", "func ParsePrefix(cursor *bufio.Reader) string {\n\tvar buffer string\n\tfor {\n\t\tnextc, _, err := cursor.ReadRune()\n\t\tif strings.ContainsRune(\" \", nextc) {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatal(\"Error parsing prefix \", err)\n\t\t}\n\t\tbuffer += string(nextc)\n\t}\n\t//fmt.Printf(\"Prefix:\\t\\t%s \\n\", buffer)\n\treturn buffer\n}", "func Prefix(p string) Option {\n\treturn func(s *storage) {\n\t\ts.prefix = p\n\t}\n}", "func (g *Group) WithPrefix(prefix string) *Group {\n\tg.prefix = prefix\n\treturn g\n}", "func (p *Parser) registerPrefix(typ token.Type, fn parsePrefixFn) {\n\tp.prefixParsers[typ] = fn\n}", "func prefixLoad(db *gorocksdb.DB, prefix string) ([]string, []string, error) {\n\tif db == nil {\n\t\treturn nil, nil, errors.New(\"Rocksdb instance is nil when do prefixLoad\")\n\t}\n\treadOpts := gorocksdb.NewDefaultReadOptions()\n\tdefer readOpts.Destroy()\n\treadOpts.SetPrefixSameAsStart(true)\n\titer := db.NewIterator(readOpts)\n\tdefer iter.Close()\n\tkeys := make([]string, 0)\n\tvalues := make([]string, 0)\n\titer.Seek([]byte(prefix))\n\tfor ; iter.Valid(); iter.Next() {\n\t\tkey := iter.Key()\n\t\tvalue := iter.Value()\n\t\tkeys = append(keys, string(key.Data()))\n\t\tkey.Free()\n\t\tvalues = append(values, string(value.Data()))\n\t\tvalue.Free()\n\t}\n\treturn keys, values, nil\n}", "func SetPrefix(pre string) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tprefix = pre\n}", "func (o BucketV2ReplicationConfigurationRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketV2ReplicationConfigurationRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn false\n\t}\n\thead := this\n\tfor e := range prefix {\n\t\tif head.data[prefix[e]-'a'] == nil {\n\t\t\treturn false\n\t\t}\n\t\thead = head.data[prefix[e]-'a']\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tnode := this\n\tn := len(prefix)\n\tfor i := 0; i < n; i++ {\n\t\tidx := prefix[i] - 'a'\n\t\tif node.sons[idx] == nil {\n\t\t\treturn false\n\t\t}\n\t\tnode = node.sons[idx]\n\t}\n\treturn true\n}", "func (o BucketReplicationConfigurationRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigurationRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (p Printer) WithPrefix(prefix string) *Printer {\n\tnewPrefix := prefix\n\tif len(p.c) > 0 {\n\t\tnewPrefix = color.New(p.c...).Sprintf(newPrefix)\n\t}\n\tp.prefix = p.prefix + newPrefix\n\treturn &p\n}", "func (gobgp *GoBGP) LookupPrefix(\n\tctx context.Context,\n\tprefix string,\n) (*api.RoutesLookupResponse, error) {\n\treturn nil, fmt.Errorf(\"not implemented: LookupPrefix\")\n}", "func (this *Trie) StartsWith(prefix string) bool {\r\n\tstrbyte := []byte(prefix)\r\n\tcurroot := this\r\n\tfor _, char := range strbyte {\r\n\t\tcurroot = curroot.childs[char-'a']\r\n\t\tif curroot == nil {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func compactPrefix() []byte { return []byte{0, 3, 0, 0} }", "func CreateDenomAddressPrefix(denom string) []byte {\n\t// we add a \"zero\" byte at the end - null byte terminator, to allow prefix denom prefix\n\t// scan. Setting it is not needed (key[last] = 0) - because this is the default.\n\tkey := make([]byte, len(DenomAddressPrefix)+len(denom)+1)\n\tcopy(key, DenomAddressPrefix)\n\tcopy(key[len(DenomAddressPrefix):], denom)\n\treturn key\n}", "func (t *Trie) StartsWith(prefix string) bool {\n\tp := t.root\n\twordArr := []rune(prefix)\n\n\tfor i := 0; i < len(wordArr); i++ {\n\t\tif p.edges[wordArr[i]-'a'] == nil {\n\t\t\treturn false\n\t\t} else {\n\t\t\tp = p.edges[wordArr[i]-'a']\n\t\t}\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif len(prefix) == 0 {\n\t\treturn true\n\t}\n\tfor _, e := range this.edges {\n\t\tif e.char == prefix[0] {\n\t\t\treturn e.next.StartsWith(prefix[1:])\n\t\t}\n\t}\n\treturn false\n}", "func resourceNetboxIpamPrefixRead(d *schema.ResourceData, meta interface{}) error {\n\tnetboxClient := meta.(*ProviderNetboxClient).client\n\n\tid := int64(d.Get(\"prefix_id\").(int))\n\n\tvar readParams = ipam.NewIPAMPrefixesReadParams().WithID(id)\n\n\treadResult, err := netboxClient.IPAM.IPAMPrefixesRead(readParams, nil)\n\n\tif err != nil {\n\t\tlog.Debugf(\"Error fetching Prefix ID # %d from Netbox = %v\", id, err)\n\t\treturn err\n\t}\n\n\tvar vrfID int64\n\tif readResult.Payload.Vrf != nil {\n\t\tvrfID = readResult.Payload.Vrf.ID\n\t}\n\n\td.Set(\"prefix\", readResult.Payload.Prefix)\n\td.Set(\"description\", readResult.Payload.Description)\n\td.Set(\"vrf_id\", vrfID)\n\td.Set(\"is_pool\", readResult.Payload.IsPool)\n\n\tvar tenantID int64\n\tif readResult.Payload.Tenant != nil {\n\t\ttenantID = readResult.Payload.Tenant.ID\n\t}\n\td.Set(\"tenant_id\", tenantID)\n\n\treturn nil\n}", "func (o BucketReplicationConfigRuleFilterAndPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigRuleFilterAnd) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (p *Parser) parsePrefixExpression() ast.Expression {\n\texpression := &ast.PrefixExpression{\n\t\tToken: p.curToken,\n\t\tOperator: p.curToken.Literal}\n\tp.nextToken()\n\texpression.Right = p.parseExpression(PREFIX)\n\treturn expression\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn true\n\t}\n\tif this == nil {\n\t\treturn false\n\t}\n\tindex := ([]byte(prefix[0:1]))[0] - byte('a')\n\tif this.child[index] == nil {\n\t\treturn false\n\t}\n\tif prefix[1:] == \"\" {\n\t\treturn true\n\t}\n\treturn this.child[index].StartsWith(prefix[1:])\n\n}", "func NewPrefixWriter(out io.Writer) PrefixWriter {\n\treturn &prefixWriter{out: out}\n}", "func SetPrefix(prefix string) { std.SetPrefix(prefix) }", "func resourceNetboxIpamPrefixUpdate(d *schema.ResourceData, meta interface{}) error {\n\tnetboxClient := meta.(*ProviderNetboxClient).client\n\n\tid := int64(d.Get(\"prefix_id\").(int))\n\n\tprefix := d.Get(\"prefix\").(string)\n\tdescription := d.Get(\"description\").(string)\n\tvrfID := int64(d.Get(\"vrf_id\").(int))\n\tisPool := d.Get(\"is_pool\").(bool)\n\t//status := d.Get(\"status\").(string)\n\ttenantID := int64(d.Get(\"tenant_id\").(int))\n\n\tvar parm = ipam.NewIPAMPrefixesUpdateParams().\n\t\tWithID(id).\n\t\tWithData(\n\t\t\t&models.PrefixCreateUpdate{\n\t\t\t\tPrefix: &prefix,\n\t\t\t\tDescription: description,\n\t\t\t\tIsPool: isPool,\n\t\t\t\tTags: []string{},\n\t\t\t\tVrf: vrfID,\n\t\t\t\tTenant: tenantID,\n\t\t\t},\n\t\t)\n\n\tlog.Debugf(\"Executing IPAMPrefixesUpdate against Netbox: %v\", parm)\n\n\tout, err := netboxClient.IPAM.IPAMPrefixesUpdate(parm, nil)\n\n\tif err != nil {\n\t\tlog.Debugf(\"Failed to execute IPAMPrefixesUpdate: %v\", err)\n\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"Done Executing IPAMPrefixesUpdate: %v\", out)\n\n\treturn nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tnode := this\n\tfor _, v := range prefix {\n\t\tif node = node.next[v-'a']; node == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (o *SignalPersonName) SetPrefix(v string) {\n\to.Prefix.Set(&v)\n}", "func (g *Graph) AppendNode(content []byte, predecessors ...ObjectID) (*Object, error) {\n\tvar buf = make([]byte, 0)\n\n\tfor _, predecessor := range predecessors {\n\t\tbuf = append(buf, predecessor[:]...)\n\t}\n\tbuf = append(buf, content...)\n\n\th := ObjectID{}\n\t// Compute a 64-byte hash of buf and put it in h.\n\tsha3.ShakeSum128(h[:], buf)\n\tvar obj = Object{}\n\tobj.ID = h\n\tobj.Content = content\n\tobj.PredecessorIDs = append([]ObjectID{}, predecessors...)\n\n\tg.ObjectAdapter.WriteObject(obj)\n\n\treturn &obj, nil\n}" ]
[ "0.6869773", "0.59520763", "0.56966764", "0.56332743", "0.5543914", "0.5521665", "0.5477629", "0.54177904", "0.5407354", "0.5355928", "0.5346138", "0.5242986", "0.5131678", "0.51244336", "0.51227385", "0.5112621", "0.51077956", "0.50852245", "0.50659835", "0.5065695", "0.50561976", "0.5044929", "0.50395495", "0.5038937", "0.50284374", "0.5024761", "0.50207394", "0.49970347", "0.49963707", "0.49641263", "0.49630398", "0.49630398", "0.49595848", "0.49590218", "0.4952112", "0.49404186", "0.49254477", "0.49226916", "0.4922675", "0.49076456", "0.4906556", "0.49034226", "0.48987782", "0.4893849", "0.48707917", "0.48660982", "0.48647225", "0.48596814", "0.48573878", "0.4855522", "0.4847873", "0.4846317", "0.4837128", "0.48242348", "0.48202607", "0.4814333", "0.4808552", "0.48058063", "0.48041812", "0.47996294", "0.4793638", "0.4790428", "0.47881734", "0.47862297", "0.47855252", "0.47833958", "0.4781115", "0.4781115", "0.47772905", "0.47757426", "0.47718817", "0.4756971", "0.47507554", "0.47496453", "0.47477597", "0.47443882", "0.4739656", "0.47381493", "0.47372523", "0.47217092", "0.46964663", "0.46946496", "0.4692682", "0.46781087", "0.4674948", "0.46693975", "0.46678934", "0.46676993", "0.46626127", "0.46602848", "0.46595386", "0.46595246", "0.46590912", "0.465567", "0.46548498", "0.46543857", "0.46517915", "0.4651649", "0.46494395", "0.46392244" ]
0.8430526
0
GetAllocator reserves an allocator used for bulk Lookup/Update/Delete operations.
GetAllocator выделяет аллокатор, используемый для массовых операций Lookup/Update/Delete.
func (idx *Tree) GetAllocator() *Allocator { return idx.allocators[idx.allocatorQueue.get()] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetRuntimePortAllocator() (*RuntimePortAllocator, error) {\n\tif rpa.pa == nil {\n\t\tif err := rpa.createAndRestorePortAllocator(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn rpa, nil\n}", "func NewAllocator(provider lCoreProvider) *Allocator {\n\treturn &Allocator{\n\t\tConfig: make(AllocConfig),\n\t\tprovider: provider,\n\t}\n}", "func NewAllocator(\n\tctx context.Context, acc *mon.BoundAccount, factory coldata.ColumnFactory,\n) *Allocator {\n\treturn &Allocator{\n\t\tctx: ctx,\n\t\tacc: acc,\n\t\tfactory: factory,\n\t}\n}", "func NewAllocator(round uint64) Allocator {\n\ta := &allocator{round: round}\n\treturn a\n}", "func NewAllocator() *Allocator {\n\tvar allocator Allocator\n\tallocator.A = C.zj_NewAllocator()\n\treturn &allocator\n}", "func (a *ResourceAllocator) allocator() memory.Allocator {\n\tif a.Allocator == nil {\n\t\treturn DefaultAllocator\n\t}\n\treturn a.Allocator\n}", "func Allocator() pageframe.Allocator {\n\treturn &_buddyAllocator\n}", "func (t *tableCommon) Allocator(ctx sessionctx.Context) autoid.Allocator {\n\ttrace_util_0.Count(_tables_00000, 322)\n\tif ctx != nil {\n\t\ttrace_util_0.Count(_tables_00000, 324)\n\t\tsessAlloc := ctx.GetSessionVars().IDAllocator\n\t\tif sessAlloc != nil {\n\t\t\ttrace_util_0.Count(_tables_00000, 325)\n\t\t\treturn sessAlloc\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 323)\n\treturn t.alloc\n}", "func newAllocator() *allocator {\n\ta := new(allocator)\n\ta.base.Init()\n\treturn a\n}", "func (alloc *inMemoryAllocator) GetType() AllocatorType {\n\treturn alloc.allocType\n}", "func (p *ResourcePool) Alloc(ctx context.Context, id string) (Alloc, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif alloc, ok := p.allocs[id]; ok {\n\t\treturn alloc, nil\n\t}\n\treturn nil, errors.E(\"alloc\", id, errors.NotExist)\n}", "func (idx *Tree) ReleaseAllocator(a *Allocator) {\n\tidx.allocatorQueue.put(a.id)\n}", "func NewPodAllocator(netInfo util.NetInfo, podLister listers.PodLister, kube kube.Interface) *PodAllocator {\n\tpodAnnotationAllocator := pod.NewPodAnnotationAllocator(\n\t\tnetInfo,\n\t\tpodLister,\n\t\tkube,\n\t)\n\n\tpodAllocator := &PodAllocator{\n\t\tnetInfo: netInfo,\n\t\treleasedPods: map[string]sets.Set[string]{},\n\t\treleasedPodsMutex: sync.Mutex{},\n\t\tpodAnnotationAllocator: podAnnotationAllocator,\n\t}\n\n\t// this network might not have IPAM, we will just allocate MAC addresses\n\tif util.DoesNetworkRequireIPAM(netInfo) {\n\t\tpodAllocator.ipAllocator = subnet.NewAllocator()\n\t}\n\n\treturn podAllocator\n}", "func (m *Manager) GetAllocation(fiveTuple *FiveTuple) *Allocation {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn m.allocations[fiveTuple.Fingerprint()]\n}", "func (allocator *Allocator) ReleaseAllocator() {\n\tC.zj_AllocatorRelease(allocator.A)\n}", "func NewUsegAllocator() (Inf, error) {\n\tallocator := &Allocator{\n\t\thostMgrs: make(map[string]usegvlanmgr.Inf),\n\t}\n\terr := allocator.newPGVlanAllocator()\n\treturn allocator, err\n}", "func NewDeviceAllocator() DeviceAllocator {\n\tpossibleDevices := make(map[mountDevice]int)\n\tfor _, firstChar := range []rune{'b', 'c'} {\n\t\tfor i := 'a'; i <= 'z'; i++ {\n\t\t\tdev := mountDevice([]rune{firstChar, i})\n\t\t\tpossibleDevices[dev] = 0\n\t\t}\n\t}\n\treturn &deviceAllocator{\n\t\tpossibleDevices: possibleDevices,\n\t\tcounter: 0,\n\t}\n}", "func (m *Manager) GetAllocation(fiveTuple *FiveTuple) *Allocation {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tfor _, a := range m.allocations {\n\t\tif a.fiveTuple.Equal(fiveTuple) {\n\t\t\treturn a\n\t\t}\n\t}\n\treturn nil\n}", "func (vt *perfSchemaTable) Allocator(ctx sessionctx.Context) autoid.Allocator {\n\treturn nil\n}", "func (sc *schedulerCache) addQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v exist\", quotaAllocator.Name)\n\t}\n\n\tinfo := &QuotaAllocatorInfo{\n\t\tname: quotaAllocator.Name,\n\t\tquotaAllocator: quotaAllocator.DeepCopy(),\n\t\tPods: make([]*v1.Pod, 0),\n\t}\n\n\t// init Request if it is nil\n\tif info.QuotaAllocator().Spec.Request.Resources == nil {\n\t\tinfo.QuotaAllocator().Spec.Request.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\n\t// init Deserved/Allocated/Used/Preemping if it is nil\n\tif info.QuotaAllocator().Status.Deserved.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Deserved.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Allocated.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Allocated.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Used.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Used.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Preempting.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Preempting.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tsc.quotaAllocators[quotaAllocator.Name] = info\n\treturn nil\n}", "func newAllocator(size uint32) *Allocator {\n\t// Set initial offset as 1 since 0 is used for nil pointers.\n\treturn &Allocator{make([]byte, size), initialAllocatorOffset}\n}", "func NewGlobalTSOAllocator(\n\tam *AllocatorManager,\n\tleadership *election.Leadership,\n) Allocator {\n\tgta := &GlobalTSOAllocator{\n\t\tallocatorManager: am,\n\t\tleadership: leadership,\n\t\ttimestampOracle: &timestampOracle{\n\t\t\tclient: leadership.GetClient(),\n\t\t\trootPath: am.rootPath,\n\t\t\tsaveInterval: am.saveInterval,\n\t\t\tupdatePhysicalInterval: am.updatePhysicalInterval,\n\t\t\tmaxResetTSGap: am.maxResetTSGap,\n\t\t\tdcLocation: GlobalDCLocation,\n\t\t\ttsoMux: &tsoObject{},\n\t\t},\n\t}\n\treturn gta\n}", "func (d *Distro) GetResolvedHostAllocatorSettings(s *evergreen.Settings) (HostAllocatorSettings, error) {\n\tconfig := s.Scheduler\n\thas := d.HostAllocatorSettings\n\tresolved := HostAllocatorSettings{\n\t\tVersion: has.Version,\n\t\tMinimumHosts: has.MinimumHosts,\n\t\tMaximumHosts: has.MaximumHosts,\n\t\tAcceptableHostIdleTime: has.AcceptableHostIdleTime,\n\t}\n\n\tcatcher := grip.NewBasicCatcher()\n\tcatcher.Add(config.ValidateAndDefault())\n\n\tif resolved.Version == \"\" {\n\t\tresolved.Version = config.HostAllocator\n\t}\n\tif !util.StringSliceContains(evergreen.ValidHostAllocators, resolved.Version) {\n\t\tcatcher.Errorf(\"'%s' is not a valid HostAllocationSettings.Version\", resolved.Version)\n\t}\n\tif resolved.AcceptableHostIdleTime == 0 {\n\t\tresolved.AcceptableHostIdleTime = time.Duration(config.AcceptableHostIdleTimeSeconds) * time.Second\n\t}\n\tif catcher.HasErrors() {\n\t\treturn HostAllocatorSettings{}, errors.Wrapf(catcher.Resolve(), \"cannot resolve HostAllocatorSettings for distro '%s'\", d.Id)\n\t}\n\n\td.HostAllocatorSettings = resolved\n\treturn resolved, nil\n}", "func (la *Allocator) Alloc(role string, socket eal.NumaSocket) (lc eal.LCore) {\n\tlist := la.Request(AllocRequest{Role: role, Socket: socket})\n\tif len(list) == 0 {\n\t\treturn eal.LCore{}\n\t}\n\treturn list[0]\n}", "func (r *Registry) Alloc(name string, addr ...string) (uint16, error) {\n\n\tr.Lock()\n\tdefer r.Unlock()\n\n\t_, name_taken := r.byname[name]\n\n\tif name_taken {\n\t\treturn 0, fmt.Errorf(\"Name %q is already taken\", name)\n\t}\n\n\tport, err := r.portFind()\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tr.createSvc(port, name, addr...)\n\n\treturn port, nil\n}", "func GetAllocation(f *agonesv1.Fleet) *allocationv1.GameServerAllocation {\n\t// get an allocation\n\treturn &allocationv1.GameServerAllocation{\n\t\tSpec: allocationv1.GameServerAllocationSpec{\n\t\t\tSelectors: []allocationv1.GameServerSelector{\n\t\t\t\t{LabelSelector: metav1.LabelSelector{MatchLabels: map[string]string{agonesv1.FleetNameLabel: f.ObjectMeta.Name}}},\n\t\t\t},\n\t\t}}\n}", "func (sc *schedulerCache) updateQuotaAllocator(oldQuotaAllocator, newQuotaAllocator *arbv1.QuotaAllocator) error {\n\tif err := sc.deleteQuotaAllocator(oldQuotaAllocator); err != nil {\n\t\treturn err\n\t}\n\tsc.addQuotaAllocator(newQuotaAllocator)\n\treturn nil\n}", "func Search(params SearchParams) (*models.AllocatorOverview, error) {\n\tif err := params.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := params.API.V1API.PlatformInfrastructure.SearchAllocators(\n\t\tplatform_infrastructure.NewSearchAllocatorsParams().\n\t\t\tWithContext(api.WithRegion(context.Background(), params.Region)).\n\t\t\tWithBody(&params.Request),\n\t\tparams.AuthWriter,\n\t)\n\tif err != nil {\n\t\treturn nil, apierror.Wrap(err)\n\t}\n\treturn res.Payload, nil\n}", "func GetMgrPlacement(p PlacementSpec) Placement {\n\treturn p.All().Merge(p[KeyMgr])\n}", "func NewGlobalTSOAllocator(leadership *election.Leadership, rootPath string, saveInterval time.Duration, maxResetTSGap func() time.Duration) Allocator {\n\treturn &GlobalTSOAllocator{\n\t\tleadership: leadership,\n\t\ttimestampOracle: &timestampOracle{\n\t\t\tclient: leadership.GetClient(),\n\t\t\trootPath: rootPath,\n\t\t\tsaveInterval: saveInterval,\n\t\t\tmaxResetTSGap: maxResetTSGap,\n\t\t},\n\t}\n}", "func (rs *resourceServer) GetPreferredAllocation(ctx context.Context,\n\trequest *pluginapi.PreferredAllocationRequest) (*pluginapi.PreferredAllocationResponse, error) {\n\treturn &pluginapi.PreferredAllocationResponse{}, nil\n}", "func GetGangAllocation(gang *resmgrsvc.Gang) *Allocation {\n\tgangAllocation := initializeZeroAlloc()\n\n\tfor _, t := range gang.GetTasks() {\n\t\tgangAllocation = gangAllocation.Add(GetTaskAllocation(t))\n\t}\n\treturn gangAllocation\n}", "func (s *stateManager) Get(id uuid.UUID) (*Allocation, error) {\n\n\tctx, cancel := context.WithTimeout(context.Background(), s.requestTimeout)\n\tdefer cancel()\n\n\tgr, err := s.kv.Get(ctx, fmt.Sprintf(\"%s/allocations/%s\", etcdPrefix, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gr.Count == 0 {\n\t\treturn nil, fmt.Errorf(\"No allocation for D %s\", id.String())\n\t}\n\treturn decode(gr.Kvs[0].Value)\n}", "func NewIPAMPoolAllocator(\n\tname string,\n\tstartRange uint32,\n\tendRange uint32,\n\tnetworkStr string) *PoolAllocatorType {\n\n\tvar nextInRange uint32\n\n\tip, n, err := net.ParseCIDR(networkStr)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tnumBitsInMask, _ := n.Mask.Size()\n\n\t// example: /24 is 8 bits so need 2**8 for the bitmap\n\tif startRange == 0 {\n\t\tstartRange = 1 // start at 1 not zero\n\t\tnextInRange = 1\n\t} else {\n\t\tnextInRange = startRange\n\n\t}\n\tif endRange == 0 {\n\t\tendRange = (1 << uint32(32-numBitsInMask)) - 2 // example: 8 bits: 256 - 1 - 1 = 254\n\t}\n\n\ttotalInRange := endRange - startRange + 1\n\n\tif len(ip.To4()) == net.IPv4len {\n\n\t\tpoolAllocator := &PoolAllocatorType{\n\t\t\tName: name,\n\t\t\tStartRange: startRange,\n\t\t\tEndRange: endRange,\n\t\t\tNextInRange: nextInRange,\n\t\t\tTotalInRange: totalInRange,\n\t\t\tNetwork: networkStr,\n\t\t\tipNetworku32: uint32(n.IP[0])<<24 | uint32(n.IP[1])<<16 | uint32(n.IP[2])<<8 | uint32(n.IP[3]),\n\t\t\tipMasku32: uint32(n.Mask[0])<<24 | uint32(n.Mask[1])<<16 | uint32(n.Mask[2])<<8 | uint32(n.Mask[3]),\n\t\t\tnumBitsInMask: numBitsInMask,\n\t\t\tipNetwork: n,\n\t\t\tAllocated: make(map[uint32]struct{}),\n\t\t}\n\t\tfmt.Printf(\"NewIPAMPoolAllocator: %v\\n\", poolAllocator)\n\n\t\treturn poolAllocator\n\t}\n\n\treturn nil\n}", "func NewAllocator(f File) (*Allocator, error) {\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ta := &Allocator{\n\t\tbufp: buffer.CGet(int(szFile - oFileSkip)),\n\t\tf: f,\n\t\tfsize: fi.Size(),\n\t}\n\ta.buf = *a.bufp\n\tfor i := range a.cap {\n\t\ta.cap[i] = int(pageAvail) / (1 << uint(i+4))\n\t}\n\n\tswitch {\n\tcase a.fsize <= oFileSkip:\n\t\tif _, err := f.WriteAt(a.buf, oFileSkip); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\tif n, err := f.ReadAt(a.buf, oFileSkip); n != len(a.buf) {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmax := a.fsize - szPage\n\t\tfor i := range a.pages {\n\t\t\tif a.pages[i], err = a.check(read(a.buf[int(oFilePages-oFileSkip)+8*i:]), 0, max); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tfor i := range a.slots {\n\t\t\tif a.slots[i], err = a.check(read(a.buf[int(oFileSlots-oFileSkip)+8*i:]), 0, max); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn a, nil\n}", "func NewIDAllocator(name string, maxIds int) (Allocator, error) {\n\tidBitmap := bitmapallocator.NewRoundRobinAllocationMap(maxIds, name)\n\n\treturn &idAllocator{\n\t\tnameIdMap: sync.Map{},\n\t\tidBitmap: idBitmap,\n\t}, nil\n}", "func (alloc *RuntimePortAllocator) createAndRestorePortAllocator() (err error) {\n\talloc.pa, err = portallocator.NewPortAllocatorCustom(*alloc.pr, func(max int, rangeSpec string) (allocator.Interface, error) {\n\t\treturn allocator.NewAllocationMap(max, rangeSpec), nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tports, err := alloc.getReservedPorts(alloc.client)\n\tif err != nil {\n\t\treturn err\n\t}\n\talloc.log.Info(\"Found reserved ports\", \"ports\", ports)\n\n\tfor _, port := range ports {\n\t\tif err = alloc.pa.Allocate(port); err != nil {\n\t\t\talloc.log.Error(err, \"can't allocate reserved ports\", \"port\", port)\n\t\t}\n\t}\n\n\treturn nil\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (c *Config) TargetAllocatorImage() string {\n\treturn c.targetAllocatorImage\n}", "func NewMemifAllocator() *MemifAllocatorType {\n\n\tMemifAllocator := &MemifAllocatorType{\n\t\tMemifID: 0,\n\t}\n\n\treturn MemifAllocator\n}", "func (p *ResourcePool) Allocs(ctx context.Context) ([]Alloc, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tallocs := make([]Alloc, len(p.allocs))\n\ti := 0\n\tfor _, a := range p.allocs {\n\t\tallocs[i] = a\n\t\ti++\n\t}\n\treturn allocs, nil\n}", "func (p *staticPolicy) GetAllocatableCPUs(s state.State) cpuset.CPUSet {\n\treturn p.topology.CPUDetails.CPUs().Difference(p.reservedCPUs)\n}", "func GetTaskAllocation(rmTask *resmgr.Task) *Allocation {\n\talloc := initializeZeroAlloc()\n\n\ttaskResource := ConvertToResmgrResource(rmTask.Resource)\n\n\t// check if the task is non-preemptible\n\tif rmTask.GetPreemptible() {\n\t\talloc.Value[PreemptibleAllocation] = taskResource\n\t} else {\n\t\talloc.Value[NonPreemptibleAllocation] = taskResource\n\t}\n\n\t// check if its a controller task\n\tif rmTask.GetController() {\n\t\talloc.Value[ControllerAllocation] = taskResource\n\t}\n\n\tif rmTask.GetRevocable() {\n\t\talloc.Value[SlackAllocation] = taskResource\n\t} else {\n\t\talloc.Value[NonSlackAllocation] = taskResource\n\t}\n\n\t// every task account for total allocation\n\talloc.Value[TotalAllocation] = taskResource\n\n\treturn alloc\n}", "func Allocs(nomad *NomadServer) []Alloc {\n\tallocs := make([]Alloc, 0)\n\tdecodeJSON(url(nomad)+\"/v1/allocations\", &allocs)\n\treturn allocs\n}", "func (c *AgonesDiscoverAllocator) Allocate(ctx context.Context, req *pb.AssignTicketsRequest) error {\n\tlogger := runtime.Logger().WithField(\"component\", \"allocator\")\n\n\tfor _, assignmentGroup := range req.Assignments {\n\t\tif err := IsAssignmentGroupValidForAllocation(assignmentGroup); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfilter, err := extensions.ExtractFilterFromExtensions(assignmentGroup.Assignment.Extensions)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"the assignment does not have a valid filter extension\")\n\t\t}\n\n\t\tgameservers, err := c.ListGameServers(ctx, filter)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif len(gameservers) == 0 {\n\t\t\tlogger.Debugf(\"gameservers not found for request with filter %v\", filter.Map())\n\t\t\tcontinue\n\t\t}\n\n\t\t// NiceToHave: Filter GameServers by Capacity and Count\n\t\t// Remove not assigned tickets based on playersCapacity - Count\n\t\t// strategy: allTogether, CapacityBased FallBack\n\t\tfor _, gs := range gameservers {\n\t\t\tif HasCapacity(assignmentGroup, gs) {\n\t\t\t\tassignmentGroup.Assignment.Connection = gs.Status.Address\n\t\t\t\t//logger.Debugf(\"extension %v\", assignmentGroup.Assignment.Extensions)\n\t\t\t\tlogger.Infof(\"gameserver %s connection %s assigned to request, total tickets: %d\", gs.Name, assignmentGroup.Assignment.Connection, len(assignmentGroup.TicketIds))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m NoAllocs) GetAllocAccount() (v string, err quickfix.MessageRejectError) {\n\tvar f field.AllocAccountField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func SpaceMapAllocate() (* SpaceMap) {\n return &SpaceMap{}\n}", "func NewAlloc(startChunkSize int, slabSize int, growthFactor float64, malloc func(size int) []byte) *Alloc {\n\tc := new(Alloc)\n\tc.m = make(locker,1)\n\tc.arena = slab.NewArena(startChunkSize,slabSize,growthFactor,malloc)\n\tc.recycle = make(chan []byte,128)\n\treturn c\n}", "func (n *NoOpAllocator) Allocate(poolID types.PoolID, ip net.IP) error {\n\treturn errNotSupported\n}", "func (r *PortAllocator) AllocateNext() (int, error) {\n\toffset, ok, err := r.alloc.AllocateNext()\n\tif err != nil {\n\t\tr.metrics.incrementAllocationErrors(\"dynamic\")\n\t\treturn 0, err\n\t}\n\tif !ok {\n\t\tr.metrics.incrementAllocationErrors(\"dynamic\")\n\t\treturn 0, ErrFull\n\t}\n\n\t// update metrics\n\tr.metrics.incrementAllocations(\"dynamic\")\n\tr.metrics.setAllocated(r.Used())\n\tr.metrics.setAvailable(r.Free())\n\n\treturn r.portRange.Base + offset, nil\n}", "func New(pr net.PortRange, allocatorFactory allocator.AllocatorWithOffsetFactory) (*PortAllocator, error) {\n\tmax := pr.Size\n\trangeSpec := pr.String()\n\n\ta := &PortAllocator{\n\t\tportRange: pr,\n\t\tmetrics: &emptyMetricsRecorder{},\n\t}\n\n\tvar offset = 0\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ServiceNodePortStaticSubrange) {\n\t\toffset = calculateRangeOffset(pr)\n\t}\n\n\tvar err error\n\ta.alloc, err = allocatorFactory(max, rangeSpec, offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a, err\n}", "func (m *RdmaDevPlugin) Allocate(ctx context.Context, r *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error) {\n\tlog.Println(\"allocate request:\", r)\n\n\tress := make([]*pluginapi.ContainerAllocateResponse, len(r.GetContainerRequests()))\n\n\tfor i := range r.GetContainerRequests() {\n\t\tress[i] = &pluginapi.ContainerAllocateResponse{\n\t\t\tDevices: m.deviceSpec,\n\t\t}\n\t}\n\n\tresponse := pluginapi.AllocateResponse{\n\t\tContainerResponses: ress,\n\t}\n\n\tlog.Println(\"allocate response: \", response)\n\treturn &response, nil\n}", "func (m *MemifAllocatorType) Allocate() uint32 {\n\n\tm.MemifID++\n\n\treturn m.MemifID\n}", "func (alloc *MockIDAllocator) Alloc() (uint64, error) {\n\treturn atomic.AddUint64(&alloc.base, 1), nil\n}", "func (a *ResourceAllocator) Allocate(size int) []byte {\n\tif a == nil {\n\t\treturn DefaultAllocator.Allocate(size)\n\t}\n\n\tif size < 0 {\n\t\tpanic(errors.New(codes.Internal, \"cannot allocate negative memory\"))\n\t} else if size == 0 {\n\t\treturn nil\n\t}\n\n\t// Account for the size requested.\n\tif err := a.count(size); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Allocate the amount of memory.\n\t// TODO(jsternberg): It's technically possible for this to allocate\n\t// more memory than we requested. How do we deal with that since we\n\t// likely want to use that feature?\n\talloc := a.allocator()\n\n\tbs := alloc.Allocate(size)\n\treturn bs\n}", "func (d Device) Alloc(extern External, size int64) (tensor.Memory, error) {\n\tif d == CPU {\n\t\tcudaLogf(\"device is CPU\")\n\t\treturn nil, nil // well there should be an error because this wouldn't be called\n\t}\n\n\tmachine := extern.(CUDAMachine)\n\tctxes := machine.Contexts()\n\tif len(ctxes) == 0 {\n\t\tcudaLogf(\"allocate nothing\")\n\t\treturn nil, nil\n\t}\n\tctx := ctxes[int(d)]\n\n\tcudaLogf(\"calling ctx.MemAlloc(%d)\", size)\n\treturn ctx.MemAlloc(size)\n}", "func (s *Flaky) Alloc() (kv.Entity, error) {\n\tif s.fail() {\n\t\treturn 0, s.err\n\t}\n\treturn s.Txn.Alloc()\n}", "func newIDAllocator(idKey proto.Key, db *client.DB, minID int64, blockSize int64,\n\tstopper *util.Stopper) (*idAllocator, error) {\n\tif minID <= allocationTrigger {\n\t\treturn nil, util.Errorf(\"minID must be > %d\", allocationTrigger)\n\t}\n\tif blockSize < 1 {\n\t\treturn nil, util.Errorf(\"blockSize must be a positive integer: %d\", blockSize)\n\t}\n\tia := &idAllocator{\n\t\tdb: db,\n\t\tminID: minID,\n\t\tblockSize: blockSize,\n\t\tids: make(chan int64, blockSize+blockSize/2+1),\n\t\tstopper: stopper,\n\t}\n\tia.idKey.Store(idKey)\n\tia.ids <- allocationTrigger\n\treturn ia, nil\n}", "func NewAllocation() *Allocation {\n\treturn initializeZeroAlloc()\n}", "func GetManager() *Manager {\n\treturn &mgr\n}", "func (q *Queue) GetResourceManager(systemname string) (ResourceManager, bool) {\n\tmanager, ok := q.managers.Get(systemname)\n\tif ok == true {\n\t\tmgrtype := manager.(ResourceManager)\n\t\treturn mgrtype, ok\n\t} else {\n\t\treturn nil, ok\n\t}\n}", "func (a *Allocation) GetByType(allocationType AllocationType) *Resources {\n\treturn a.Value[allocationType]\n}", "func NewIPAllocator(pendingIPRanges map[string]bool) *IPAllocator {\n\t// Make a copy of the pending IP ranges and set it in the IPAllocator so that the caller cannot mutate this map outside the library\n\tpendingIPRangesCopy := make(map[string]bool)\n\tfor pendingIPRange := range pendingIPRanges {\n\t\tpendingIPRangesCopy[pendingIPRange] = true\n\t}\n\treturn &IPAllocator{\n\t\tpendingIPRanges: pendingIPRangesCopy,\n\t}\n}", "func NewIPAllocator(pendingIPRanges map[string]bool) *IPAllocator {\n\t// Make a copy of the pending IP ranges and set it in the IPAllocator so that the caller cannot mutate this map outside the library\n\tpendingIPRangesCopy := make(map[string]bool)\n\tfor pendingIPRange := range pendingIPRanges {\n\t\tpendingIPRangesCopy[pendingIPRange] = true\n\t}\n\treturn &IPAllocator{\n\t\tpendingIPRanges: pendingIPRangesCopy,\n\t}\n}", "func (o *AllocationRequest) GetAllocation() AllocationAllocation {\n\tif o == nil || o.Allocation == nil {\n\t\tvar ret AllocationAllocation\n\t\treturn ret\n\t}\n\treturn *o.Allocation\n}", "func (c *Client) AllocID(ctx context.Context, req *pdpb.AllocIDReq) (*pdpb.AllocIDRsp, error) {\n\trsp, err := c.proxyRPC(ctx,\n\t\treq,\n\t\tfunc() {\n\t\t\treq.From = c.name\n\t\t\treq.ID = c.seq\n\t\t},\n\t\tfunc(cc context.Context) (interface{}, error) {\n\t\t\treturn c.pd.AllocID(cc, req, grpc.FailFast(true))\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rsp.(*pdpb.AllocIDRsp), nil\n}", "func FindAlloc(nomad *NomadServer, job *Job, host *Host) (*Alloc, error) {\n\tallocs := Allocs(nomad)\n\tfor _, alloc := range allocs {\n\t\tif alloc.NodeID == host.ID && strings.Contains(alloc.Name, job.Name) {\n\t\t\t// We may be looking at a stale allocation and a newer one exists\n\t\t\tif alloc.DesiredStatus == \"stop\" && len(allocs) > 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn &alloc, nil\n\t\t}\n\t}\n\treturn &Alloc{}, &AllocNotFound{Hostname: host.Name, Jobname: job.Name}\n}", "func (na *cnmNetworkAllocator) Allocate(n *api.Network) error {\n\tif _, ok := na.networks[n.ID]; ok {\n\t\treturn fmt.Errorf(\"network %s already allocated\", n.ID)\n\t}\n\n\td, err := na.resolveDriver(n)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnw := &network{\n\t\tnw: n,\n\t\tendpoints: make(map[string]string),\n\t\tisNodeLocal: d.capability.DataScope == scope.Local,\n\t}\n\n\t// No swarm-level allocation can be provided by the network driver for\n\t// node-local networks. Only thing needed is populating the driver's name\n\t// in the driver's state.\n\tif nw.isNodeLocal {\n\t\tn.DriverState = &api.Driver{\n\t\t\tName: d.name,\n\t\t}\n\t\t// In order to support backward compatibility with older daemon\n\t\t// versions which assumes the network attachment to contains\n\t\t// non nil IPAM attribute, passing an empty object\n\t\tn.IPAM = &api.IPAMOptions{Driver: &api.Driver{}}\n\t} else {\n\t\tnw.pools, err = na.allocatePools(n)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed allocating pools and gateway IP for network %s\", n.ID)\n\t\t}\n\n\t\tif err := na.allocateDriverState(n); err != nil {\n\t\t\tna.freePools(n, nw.pools)\n\t\t\treturn errors.Wrapf(err, \"failed while allocating driver state for network %s\", n.ID)\n\t\t}\n\t}\n\n\tna.networks[n.ID] = nw\n\n\treturn nil\n}", "func GetManager() *Manager {\n\tif manager == nil {\n\t\tmanager = &Manager{\n\t\t\tProcesses: make(map[int64]*Process),\n\t\t}\n\t}\n\treturn manager\n}", "func (p *mockPolicy) GetAllocatableMemory(s state.State) []state.Block {\n\treturn []state.Block{}\n}", "func GetMgr() *Mgr {\n\treturn mgr\n}", "func GetManager() *Manager {\n\tmanagerMu.Lock()\n\tdefer managerMu.Unlock()\n\n\tif managerInstance == nil {\n\t\tmanagerInstance = NewManager(config.GetConfig().Sub(\"katago\"))\n\t}\n\treturn managerInstance\n}", "func (m *Manager) GetCompiler() *ast.Compiler {\n\tm.compilerMux.RLock()\n\tdefer m.compilerMux.RUnlock()\n\treturn m.compiler\n}", "func TestClientEndpoint_GetClientAllocs_WithoutMigrateTokens(t *testing.T) {\n\tt.Parallel()\n\tassert := assert.New(t)\n\n\ts1 := TestServer(t, nil)\n\tdefer s1.Shutdown()\n\tcodec := rpcClient(t, s1)\n\ttestutil.WaitForLeader(t, s1.RPC)\n\n\t// Create the register request\n\tnode := mock.Node()\n\treg := &structs.NodeRegisterRequest{\n\t\tNode: node,\n\t\tWriteRequest: structs.WriteRequest{Region: \"global\"},\n\t}\n\n\t// Fetch the response\n\tvar resp structs.GenericResponse\n\tif err := msgpackrpc.CallWithCodec(codec, \"Node.Register\", reg, &resp); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tnode.CreateIndex = resp.Index\n\tnode.ModifyIndex = resp.Index\n\n\t// Inject fake evaluations\n\tprevAlloc := mock.Alloc()\n\tprevAlloc.NodeID = node.ID\n\talloc := mock.Alloc()\n\talloc.NodeID = node.ID\n\talloc.PreviousAllocation = prevAlloc.ID\n\talloc.DesiredStatus = structs.AllocClientStatusComplete\n\tstate := s1.fsm.State()\n\tstate.UpsertJobSummary(99, mock.JobSummary(alloc.JobID))\n\terr := state.UpsertAllocs(100, []*structs.Allocation{prevAlloc, alloc})\n\tassert.Nil(err)\n\n\t// Lookup the allocs\n\tget := &structs.NodeSpecificRequest{\n\t\tNodeID: node.ID,\n\t\tSecretID: node.SecretID,\n\t\tQueryOptions: structs.QueryOptions{Region: \"global\"},\n\t}\n\tvar resp2 structs.NodeClientAllocsResponse\n\n\terr = msgpackrpc.CallWithCodec(codec, \"Node.GetClientAllocs\", get, &resp2)\n\tassert.Nil(err)\n\n\tassert.Equal(uint64(100), resp2.Index)\n\tassert.Equal(2, len(resp2.Allocs))\n\tassert.Equal(uint64(100), resp2.Allocs[alloc.ID])\n\tassert.Equal(0, len(resp2.MigrateTokens))\n}", "func (_Erc1820Registry *Erc1820RegistryCaller) GetManager(opts *bind.CallOpts, _addr common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Erc1820Registry.contract.Call(opts, &out, \"getManager\", _addr)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *Store) AllocatorDryRun(ctx context.Context, repl *Replica) (tracing.Recording, error) {\n\tctx, collect, cancel := tracing.ContextWithRecordingSpan(ctx, s.ClusterSettings().Tracer, \"allocator dry run\")\n\tdefer cancel()\n\tcanTransferLease := func(ctx context.Context, repl *Replica) bool { return true }\n\t_, err := s.replicateQueue.processOneChange(\n\t\tctx, repl, canTransferLease, true /* dryRun */)\n\tif err != nil {\n\t\tlog.Eventf(ctx, \"error simulating allocator on replica %s: %s\", repl, err)\n\t}\n\treturn collect(), nil\n}", "func (manager *Manager) GetGenerationManager() generation.Manager {\n\treturn manager.generatorManager\n}", "func (a *ResourceAllocator) Allocated() int64 {\n\treturn atomic.LoadInt64(&a.bytesAllocated)\n}", "func (c *Config) TargetAllocatorConfigMapEntry() string {\n\treturn c.targetAllocatorConfigMapEntry\n}", "func (vns *VirtualNetworkService) Allocate(ctx context.Context, vnBlueprint blueprint.Interface,\n\tcluster resources.Cluster) (*resources.VirtualNetwork, error) {\n\tclusterID, err := cluster.ID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblueprintText, err := vnBlueprint.Render()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresArr, err := vns.call(ctx, \"one.vn.allocate\", blueprintText, clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vns.RetrieveInfo(ctx, int(resArr[resultIndex].ResultInt()))\n}", "func Alloc(addr, size uint64, allocType, protect int) *Memory {\n\tpanic(\"not implemented\")\n}", "func (sc *schedulerCache) deleteQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; !ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v doesn't exist\", quotaAllocator.Name)\n\t}\n\tdelete(sc.quotaAllocators, quotaAllocator.Name)\n\treturn nil\n}", "func SetupRuntimePortAllocator(client client.Client, pr *net.PortRange, getReservedPorts func(client client.Client) (ports []int, err error)) {\n\trpa = &RuntimePortAllocator{client: client, pr: pr, getReservedPorts: getReservedPorts}\n\trpa.log = ctrl.Log.WithName(\"RuntimePortAllocator\")\n}", "func (c *Context) GetManager() (*Manager) {\n\tmutableMutex.Lock()\n mutableMutex.Unlock()\n\treturn c.Manager\n}", "func (p *spanSetBlockAlloc) alloc() *spanSetBlock {\n\tif s := (*spanSetBlock)(p.stack.pop()); s != nil {\n\t\treturn s\n\t}\n\treturn (*spanSetBlock)(persistentalloc(unsafe.Sizeof(spanSetBlock{}), cpu.CacheLineSize, &memstats.gcMiscSys))\n}", "func (c *FakeGameServerAllocations) Get(name string, options v1.GetOptions) (result *v1alpha1.GameServerAllocation, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewGetAction(gameserverallocationsResource, c.ns, name), &v1alpha1.GameServerAllocation{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.GameServerAllocation), err\n}", "func (ia *idAllocator) Allocate() (int64, error) {\n\tfor {\n\t\tid := <-ia.ids\n\t\tif id == allocationTrigger {\n\t\t\tif !ia.stopper.StartTask() {\n\t\t\t\tif atomic.CompareAndSwapInt32(&ia.closed, 0, 1) {\n\t\t\t\t\tclose(ia.ids)\n\t\t\t\t}\n\t\t\t\treturn 0, util.Errorf(\"could not allocate ID; system is draining\")\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tia.allocateBlock(ia.blockSize)\n\t\t\t\tia.stopper.FinishTask()\n\t\t\t}()\n\t\t} else {\n\t\t\treturn id, nil\n\t\t}\n\t}\n}", "func (m *arenaManager) getArena(aid int) (*mmap.File, error) {\n\trelAid := aid - m.baseAid\n\tif relAid == len(m.arenas) {\n\t\tm.arenas = append(m.arenas, nil)\n\t}\n\taa := m.arenas[relAid]\n\tif aa != nil {\n\t\treturn aa, nil\n\t}\n\n\t// before we get a new arena into memory, we need to ensure that after fetching\n\t// a new arena into memory, we do not cross the provided memory limit.\n\tif err := m.ensureEnoughMem(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// now, get arena into memory\n\tif err := m.loadArena(aid); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m.arenas[aid], nil\n}", "func (s *Store) AllocateRangeID(ctx context.Context) (roachpb.RangeID, error) {\n\tid, err := s.rangeIDAlloc.Allocate(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn roachpb.RangeID(id), nil\n}", "func (r *PortAllocator) Allocate(port int) error {\n\tok, offset := r.contains(port)\n\tif !ok {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\n\t\t// include valid port range in error\n\t\tvalidPorts := r.portRange.String()\n\t\treturn &ErrNotInRange{validPorts}\n\t}\n\n\tallocated, err := r.alloc.Allocate(offset)\n\tif err != nil {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\t\treturn err\n\t}\n\tif !allocated {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\t\treturn ErrAllocated\n\t}\n\n\t// update metrics\n\tr.metrics.incrementAllocations(\"static\")\n\tr.metrics.setAllocated(r.Used())\n\tr.metrics.setAvailable(r.Free())\n\n\treturn nil\n}", "func New() *AllocGrp {\n\tvar m AllocGrp\n\treturn &m\n}", "func (f *FS) AllocSector(typ DataType, miner address.Address, ssize abi.SectorSize, cache bool, num abi.SectorNumber) (SectorPath, error) {\n\t{\n\t\tspath, err := f.FindSector(typ, miner, num)\n\t\tif err == nil {\n\t\t\treturn spath, xerrors.Errorf(\"allocating sector %s: %m\", spath, ErrExists)\n\t\t}\n\t\tif err != ErrNotFound {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tneed := overheadMul[typ] * uint64(ssize)\n\n\tp, err := f.findBestPath(need, cache, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsp := p.Sector(typ, miner, num)\n\n\treturn sp, f.reserve(typ, sp.storage(), need)\n}", "func GetManager() *AppManager {\n\treturn &appMgr\n}", "func (cp *connPool) Allocate(\n\tcfg *config.SQL,\n\tresolver resolver.ServiceResolver,\n\tcreate func(cfg *config.SQL, resolver resolver.ServiceResolver) (*sqlx.DB, error),\n) (db *sqlx.DB, err error) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\n\tdsn, err := buildDSN(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif entry, ok := cp.pool[dsn]; ok {\n\t\tentry.refCount++\n\t\treturn entry.db, nil\n\t}\n\n\tdb, err = create(cfg, resolver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp.pool[dsn] = entry{db: db, refCount: 1}\n\n\treturn db, nil\n}", "func GetManager(ctx context.Context, env evergreen.Environment, mgrOpts ManagerOpts) (Manager, error) {\n\tvar provider Manager\n\n\tswitch mgrOpts.Provider {\n\tcase evergreen.ProviderNameEc2OnDemand:\n\t\tprovider = &ec2Manager{\n\t\t\tenv: env,\n\t\t\tEC2ManagerOptions: &EC2ManagerOptions{\n\t\t\t\tclient: &awsClientImpl{},\n\t\t\t\tregion: mgrOpts.Region,\n\t\t\t\tproviderKey: mgrOpts.ProviderKey,\n\t\t\t\tproviderSecret: mgrOpts.ProviderSecret,\n\t\t\t},\n\t\t}\n\tcase evergreen.ProviderNameEc2Fleet:\n\t\tprovider = &ec2FleetManager{\n\t\t\tenv: env,\n\t\t\tEC2FleetManagerOptions: &EC2FleetManagerOptions{\n\t\t\t\tclient: &awsClientImpl{},\n\t\t\t\tregion: mgrOpts.Region,\n\t\t\t\tproviderKey: mgrOpts.ProviderKey,\n\t\t\t\tproviderSecret: mgrOpts.ProviderSecret,\n\t\t\t},\n\t\t}\n\tcase evergreen.ProviderNameStatic:\n\t\tprovider = &staticManager{}\n\tcase evergreen.ProviderNameMock:\n\t\tprovider = makeMockManager()\n\tcase evergreen.ProviderNameDocker:\n\t\tprovider = &dockerManager{env: env}\n\tcase evergreen.ProviderNameDockerMock:\n\t\tprovider = &dockerManager{env: env, client: &dockerClientMock{}}\n\tcase evergreen.ProviderNameOpenstack:\n\t\tprovider = &openStackManager{}\n\tcase evergreen.ProviderNameGce:\n\t\tprovider = &gceManager{}\n\tcase evergreen.ProviderNameVsphere:\n\t\tprovider = &vsphereManager{}\n\tdefault:\n\t\treturn nil, errors.Errorf(\"no known provider '%s'\", mgrOpts.Provider)\n\t}\n\n\tif err := provider.Configure(ctx, env.Settings()); err != nil {\n\t\treturn nil, errors.Wrap(err, \"configuring cloud provider\")\n\t}\n\n\treturn provider, nil\n}", "func Convert_config_SecurityAllocator_To_v1_SecurityAllocator(in *config.SecurityAllocator, out *v1.SecurityAllocator, s conversion.Scope) error {\n\treturn autoConvert_config_SecurityAllocator_To_v1_SecurityAllocator(in, out, s)\n}", "func GetMgrResources(p rook.ResourceSpec) v1.ResourceRequirements {\n\treturn p[ResourcesKeyMgr]\n}", "func Alloc(size uintptr) Pointer {\n\treturn Pointer(allocator.Alloc(size))\n}", "func (o *V0037Node) GetAllocMemory() int64 {\n\tif o == nil || o.AllocMemory == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.AllocMemory\n}", "func GetTaskManager(provider string) (TaskManager, error) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tmgr, ok := taskMgrs[provider]\n\tif !ok {\n\t\treturn nil, ErrCloudNoProvider\n\t}\n\treturn mgr, nil\n}" ]
[ "0.68342525", "0.6720525", "0.67027986", "0.6658546", "0.66041344", "0.65315723", "0.6260463", "0.6200884", "0.613557", "0.60628927", "0.595554", "0.588803", "0.5842821", "0.5842404", "0.5824318", "0.57718134", "0.5739044", "0.56429476", "0.559904", "0.5523092", "0.537339", "0.5353337", "0.5258639", "0.51769775", "0.5175778", "0.5163283", "0.5158048", "0.5124906", "0.51056814", "0.5083702", "0.5079356", "0.50778127", "0.5058568", "0.5036097", "0.5032813", "0.5029127", "0.49826175", "0.49767303", "0.49698672", "0.49435058", "0.49346673", "0.49323758", "0.4929502", "0.49186382", "0.49039596", "0.4832469", "0.4824459", "0.4806311", "0.48019302", "0.47948796", "0.47792956", "0.47559065", "0.47557467", "0.4747922", "0.47392437", "0.47127235", "0.47043908", "0.46996912", "0.46955013", "0.4695302", "0.46925154", "0.46874115", "0.46799907", "0.46799907", "0.4677543", "0.46692127", "0.46494237", "0.46301797", "0.46232623", "0.4611734", "0.4581553", "0.45813552", "0.45747536", "0.45721257", "0.45487478", "0.45174846", "0.45070684", "0.45035124", "0.44924206", "0.44836444", "0.4475445", "0.447118", "0.44616953", "0.44609138", "0.44278392", "0.44207782", "0.44201404", "0.44137236", "0.4411491", "0.44061965", "0.44004583", "0.44001287", "0.43975213", "0.43822205", "0.4382004", "0.43814838", "0.43790603", "0.43733928", "0.43697068", "0.43677026" ]
0.7612451
0
ReleaseAllocator returns an allocator previously reserved using GetAllocator
ReleaseAllocator возвращает аллокатор, ранее зарезервированный с помощью GetAllocator
func (idx *Tree) ReleaseAllocator(a *Allocator) { idx.allocatorQueue.put(a.id) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (allocator *Allocator) ReleaseAllocator() {\n\tC.zj_AllocatorRelease(allocator.A)\n}", "func (a *ResourceAllocator) Free(b []byte) {\n\tif a == nil {\n\t\tDefaultAllocator.Free(b)\n\t\treturn\n\t}\n\n\tsize := len(b)\n\n\t// Release the memory to the allocator first.\n\talloc := a.allocator()\n\talloc.Free(b)\n\n\t// Release the memory in our accounting.\n\tatomic.AddInt64(&a.bytesAllocated, int64(-size))\n}", "func (stack *StackAllocator) release() {\n\tstack.alloc = 0\n}", "func NewAllocator(round uint64) Allocator {\n\ta := &allocator{round: round}\n\treturn a\n}", "func NewAllocator() *Allocator {\n\tvar allocator Allocator\n\tallocator.A = C.zj_NewAllocator()\n\treturn &allocator\n}", "func (c *crdBackend) Release(ctx context.Context, id idpool.ID, key allocator.AllocatorKey) (err error) {\n\t// For CiliumIdentity-based allocation, the reference counting is\n\t// handled via CiliumEndpoint. Any CiliumEndpoint referring to a\n\t// CiliumIdentity will keep the CiliumIdentity alive. No action is\n\t// needed to release the reference here.\n\treturn nil\n}", "func (mm *MMapRWManager) Release() (err error) {\n\tmm.fdm.reduceUsing(mm.path)\n\treturn mm.m.Unmap()\n}", "func newAllocator() *allocator {\n\ta := new(allocator)\n\ta.base.Init()\n\treturn a\n}", "func (p *ResourcePool) Free(a Alloc) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\treturn p.doFree(a)\n}", "func (idx *Tree) GetAllocator() *Allocator {\n\treturn idx.allocators[idx.allocatorQueue.get()]\n}", "func (s *ControllerPool) Release(controllerName string, controller interface{}) {\n\ts.mu.RLock()\n\tpool, ok := s.poolMap[controllerName]\n\ts.mu.RUnlock()\n\tif !ok {\n\t\tpanic(\"unknown controller name\")\n\t}\n\tDiFree(controller)\n\tpool.Put(controller)\n\n}", "func NewAllocator(provider lCoreProvider) *Allocator {\n\treturn &Allocator{\n\t\tConfig: make(AllocConfig),\n\t\tprovider: provider,\n\t}\n}", "func GetRuntimePortAllocator() (*RuntimePortAllocator, error) {\n\tif rpa.pa == nil {\n\t\tif err := rpa.createAndRestorePortAllocator(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn rpa, nil\n}", "func (r *PortAllocator) Destroy() {\n\tr.alloc.Destroy()\n}", "func (r *PortAllocator) Release(port int) error {\n\tok, offset := r.contains(port)\n\tif !ok {\n\t\tklog.Warningf(\"port is not in the range when release it. port: %v\", port)\n\t\treturn nil\n\t}\n\n\terr := r.alloc.Release(offset)\n\tif err == nil {\n\t\t// update metrics\n\t\tr.metrics.setAllocated(r.Used())\n\t\tr.metrics.setAvailable(r.Free())\n\t}\n\treturn err\n}", "func (am *AccountManager) Release() {\n\tam.bsem <- struct{}{}\n}", "func (s *BasevhdlListener) ExitAllocator(ctx *AllocatorContext) {}", "func (jbobject *UnsafeMemoryMemoryAllocator) Free(a UnsafeMemoryMemoryBlockInterface) {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\t_, err := jbobject.CallMethod(javabind.GetEnv(), \"free\", javabind.Void, conv_a.Value().Cast(\"org/apache/spark/unsafe/memory/MemoryBlock\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\n}", "func Allocator() pageframe.Allocator {\n\treturn &_buddyAllocator\n}", "func (a *Allocator) ReleaseMemory(size int64) {\n\tif size < 0 {\n\t\tcolexecerror.InternalError(errors.AssertionFailedf(\"unexpectedly negative size in ReleaseMemory: %d\", size))\n\t}\n\tif size > a.acc.Used() {\n\t\tsize = a.acc.Used()\n\t}\n\ta.acc.Shrink(a.ctx, size)\n}", "func (a *ResourceAllocator) allocator() memory.Allocator {\n\tif a.Allocator == nil {\n\t\treturn DefaultAllocator\n\t}\n\treturn a.Allocator\n}", "func (y *Yaraus) Release() error {\n\ty.mu.Lock()\n\tdefer y.mu.Unlock()\n\treturn y.release()\n}", "func (ba *buddyAllocator) Release(addr, order uint32) {\n\tindex, first := ba.getIndex(addr, order)\n\n\tif order >= MaxOrder {\n\t\t// we need to free order / _maxOrder pages\n\t\tn := order / MaxOrder\n\t\t// Mark n pages from index as free\n\t\tfor i := uint32(0); i < n; i++ {\n\t\t\tba.buddies[MaxOrder].freeMap.Set(index + i)\n\t\t}\n\t\treturn\n\t}\n\n\t// go up until we get a buddy with one page allocated\n\tfor order <= MaxOrder {\n\t\t// check if other buddy is still allocated\n\t\tif !ba.buddies[order].freeMap.IsSet(index) {\n\t\t\t// mark buddy as free\n\t\t\tba.buddies[order].freeMap.Toggle(index)\n\t\t\t// add this page to free list\n\t\t\tba.buddies[order].freeList.Append(addr)\n\t\t\t// no need to go further\n\t\t\tbreak\n\t\t}\n\t\t// buddy is also free, combine buddies\n\t\tbuddyAddress := ba.getBuddyAddress(index, order, first)\n\t\tba.buddies[order].freeList.Delete(buddyAddress)\n\t\t// now, mark both pages are free\n\t\tba.buddies[order].freeMap.Toggle(index)\n\t\t// go to next order\n\t\torder++\n\t\tif buddyAddress < addr {\n\t\t\taddr = buddyAddress\n\t\t}\n\t\tindex, first = ba.getIndex(addr, order)\n\t}\n\treturn\n}", "func NewAllocator(\n\tctx context.Context, acc *mon.BoundAccount, factory coldata.ColumnFactory,\n) *Allocator {\n\treturn &Allocator{\n\t\tctx: ctx,\n\t\tacc: acc,\n\t\tfactory: factory,\n\t}\n}", "func (tr *tableReader) Release() {\n\ttr.ProcessorBase.Reset()\n\ttr.fetcher.Reset()\n\t*tr = tableReader{\n\t\tProcessorBase: tr.ProcessorBase,\n\t\tfetcher: tr.fetcher,\n\t\tspans: tr.spans[:0],\n\t\trowsRead: 0,\n\t}\n\ttrPool.Put(tr)\n}", "func (t *IDAllocator) Release(id int) {\n\tif id >= t.nextId {\n\t\tlog.Error(\"id[%v] is invalid to release\", id)\n\t\treturn\n\t}\n\tt.reuseIds = append(t.reuseIds, id)\n\tutils.DescFastSort(t.reuseIds)\n}", "func (na *cnmNetworkAllocator) Deallocate(n *api.Network) error {\n\tlocalNet := na.getNetwork(n.ID)\n\tif localNet == nil {\n\t\treturn fmt.Errorf(\"could not get networker state for network %s\", n.ID)\n\t}\n\n\t// No swarm-level resource deallocation needed for node-local networks\n\tif localNet.isNodeLocal {\n\t\tdelete(na.networks, n.ID)\n\t\treturn nil\n\t}\n\n\tif err := na.freeDriverState(n); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to free driver state for network %s\", n.ID)\n\t}\n\n\tdelete(na.networks, n.ID)\n\n\treturn na.freePools(n, localNet.pools)\n}", "func (ng *NameGenerator) Release(name string) {\n\tng.mu.Lock()\n\tdefer ng.mu.Unlock()\n\n\tif _, ok := ng.use[name]; ok {\n\t\tdelete(ng.use, name)\n\t}\n}", "func newAllocator(size uint32) *Allocator {\n\t// Set initial offset as 1 since 0 is used for nil pointers.\n\treturn &Allocator{make([]byte, size), initialAllocatorOffset}\n}", "func (alloc *RuntimePortAllocator) createAndRestorePortAllocator() (err error) {\n\talloc.pa, err = portallocator.NewPortAllocatorCustom(*alloc.pr, func(max int, rangeSpec string) (allocator.Interface, error) {\n\t\treturn allocator.NewAllocationMap(max, rangeSpec), nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tports, err := alloc.getReservedPorts(alloc.client)\n\tif err != nil {\n\t\treturn err\n\t}\n\talloc.log.Info(\"Found reserved ports\", \"ports\", ports)\n\n\tfor _, port := range ports {\n\t\tif err = alloc.pa.Allocate(port); err != nil {\n\t\t\talloc.log.Error(err, \"can't allocate reserved ports\", \"port\", port)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *PortAllocator) Free() int {\n\treturn r.alloc.Free()\n}", "func (la *Allocator) Free(lc eal.LCore) {\n\tif la.allocated[lc.ID()] == \"\" {\n\t\tpanic(\"lcore double free\")\n\t}\n\tlogger.Info(\"lcore freed\",\n\t\tlc.ZapField(\"lc\"),\n\t\tzap.String(\"role\", la.allocated[lc.ID()]),\n\t\tla.provider.NumaSocketOf(lc).ZapField(\"socket\"),\n\t)\n\tla.allocated[lc.ID()] = \"\"\n}", "func (p *request) Release() {\n\tp.ctx = nil\n\tp.Entry = nil\n\tp.read = false\n\trequestPool.Put(p)\n}", "func (client *VirtualMachineScaleSetsClient) deallocate(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsBeginDeallocateOptions) (*http.Response, error) {\n\treq, err := client.deallocateCreateRequest(ctx, resourceGroupName, vmScaleSetName, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.pl.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {\n\t\treturn nil, client.deallocateHandleError(resp)\n\t}\n\treturn resp, nil\n}", "func (r *Reaper) Release() (Destructor, error) {\n\tif r == nil {\n\t\treturn Noop, nil\n\t}\n\tif r.released {\n\t\treturn nil, kerror.New(kerror.EIllegal,\n\t\t\t\"reaper was already released from responsibility for calling destructors\")\n\t}\n\tif r.finalized {\n\t\treturn nil, kerror.New(kerror.EIllegal, \"reaper has already called destructors\")\n\t}\n\tr.released = true\n\tdestructors := r.destructors\n\treturn DestructorFunc(func() error {\n\t\treturn reap(destructors...)\n\t}), nil\n}", "func (_TokenVesting *TokenVestingTransactorSession) Release(_token common.Address) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.Release(&_TokenVesting.TransactOpts, _token)\n}", "func (idAllocator *idAllocator) ReleaseID(name string) {\n\tv, ok := idAllocator.nameIdMap.Load(name)\n\tif ok {\n\t\tidAllocator.idBitmap.Release(v.(int))\n\t\tidAllocator.nameIdMap.Delete(name)\n\t}\n}", "func (ta *CachedAllocator) Close() {\n\tta.CancelFunc()\n\tta.wg.Wait()\n\tta.TChan.Close()\n\terrMsg := fmt.Sprintf(\"%s is closing\", ta.Role)\n\tta.revokeRequest(errors.New(errMsg))\n}", "func ReleaseDecoder(dec *Decoder) {\n\tif dec.buf.Len() != 0 {\n\t\tpanic(\"marshal.Decoder: found trailing junk\")\n\t}\n\tdecoderPool.Put(dec)\n}", "func NewUsegAllocator() (Inf, error) {\n\tallocator := &Allocator{\n\t\thostMgrs: make(map[string]usegvlanmgr.Inf),\n\t}\n\terr := allocator.newPGVlanAllocator()\n\treturn allocator, err\n}", "func (_TokenVesting *TokenVestingTransactor) Release(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _TokenVesting.contract.Transact(opts, \"release\", _token)\n}", "func (p *PreemptiveLocker) Release(ctx context.Context) (err error) {\n\tspan, ctx := p.startSpanFromContext(ctx, \"release\")\n\tp.w.Stop()\n\tdefer func() {\n\t\terr = p.l.Unlock() // always unlock\n\t\tspan.Finish(tracer.WithError(err))\n\t}()\n\tvar kp *consul.KVPair\n\tkp, _, _ = p.kv.Get(p.pendingKey, &consul.QueryOptions{AllowStale: false, WaitIndex: uint64(0), WaitTime: p.opts.LockWait})\n\tif p.id == string(kp.Value[:]) {\n\t\tp.kv.DeleteCAS(&consul.KVPair{Key: p.pendingKey, Value: nil}, nil)\n\t}\n\treturn nil\n}", "func (s *MockManagedThread) Release() {}", "func (sc *schedulerCache) deleteQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; !ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v doesn't exist\", quotaAllocator.Name)\n\t}\n\tdelete(sc.quotaAllocators, quotaAllocator.Name)\n\treturn nil\n}", "func (tracer *Instance) Release() {\n\ttracer.collections.Del(tracer.key())\n}", "func (m *Manager) Release() {\n\tm.con.Close()\n\tm.stdCimV2Con.Close()\n}", "func (sm *SharedManager) release(ctx context.Context) error {\n\tremaining := atomic.AddInt32(&sm.refCount, -1)\n\tif remaining != 0 {\n\t\tlog(ctx).Debugf(\"not closing shared manager, remaining = %v\", remaining)\n\t\treturn nil\n\t}\n\n\tatomic.StoreInt32(&sm.closed, 1)\n\n\tlog(ctx).Debugf(\"closing shared manager\")\n\n\tif err := sm.committedContents.close(); err != nil {\n\t\treturn errors.Wrap(err, \"error closed committed content index\")\n\t}\n\n\tsm.contentCache.close(ctx)\n\tsm.metadataCache.close(ctx)\n\tsm.encryptionBufferPool.Close()\n\n\treturn sm.st.Close(ctx)\n}", "func (r *ResponsePool) Release(resp *Response) {\n\tresp.Reset()\n\tr.pool.Put(resp)\n}", "func (sc *schedulerCache) updateQuotaAllocator(oldQuotaAllocator, newQuotaAllocator *arbv1.QuotaAllocator) error {\n\tif err := sc.deleteQuotaAllocator(oldQuotaAllocator); err != nil {\n\t\treturn err\n\t}\n\tsc.addQuotaAllocator(newQuotaAllocator)\n\treturn nil\n}", "func Release(b *Buffer) {\n\tb.B = b.B[:0]\n\tpool.Put(b)\n}", "func (r *RequestPool) Release(req *Request) {\n\treq.Reset()\n\tr.pool.Put(req)\n}", "func (b *defaultByteBuffer) Release(e error) (err error) {\n\tb.zero()\n\tbytebufPool.Put(b)\n\treturn\n}", "func Release() {\n\tdefaultRoutinePool.Release()\n}", "func (p *Buffer) release() []byte {\n\tbytes := p.buf\n\tp.buf = nil\n\tp.index = 0\n\tp.Immutable = false\n\tp.err = nil\n\tp.array_indexes = nil\n\tbuffer_pool.Put(p)\n\treturn bytes\n}", "func (a *Allocator) Close() error {\n\tif err := a.flush(); err != nil {\n\t\treturn err\n\t}\n\n\tbuffer.Put(a.bufp)\n\treturn a.f.Close()\n}", "func ReleaseRequest(req *Request) {\n\treq.Reset()\n\trequestPool.Put(req)\n}", "func (c *Compiler) Release() {\n\tC.shaderc_compiler_release(c.compiler)\n}", "func (c DevSession) Release() {\n\tcapnp.Client(c).Release()\n}", "func (_ *MemStore) Release() error {\n\treturn nil\n}", "func (sc *schedulerCache) addQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v exist\", quotaAllocator.Name)\n\t}\n\n\tinfo := &QuotaAllocatorInfo{\n\t\tname: quotaAllocator.Name,\n\t\tquotaAllocator: quotaAllocator.DeepCopy(),\n\t\tPods: make([]*v1.Pod, 0),\n\t}\n\n\t// init Request if it is nil\n\tif info.QuotaAllocator().Spec.Request.Resources == nil {\n\t\tinfo.QuotaAllocator().Spec.Request.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\n\t// init Deserved/Allocated/Used/Preemping if it is nil\n\tif info.QuotaAllocator().Status.Deserved.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Deserved.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Allocated.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Allocated.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Used.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Used.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Preempting.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Preempting.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tsc.quotaAllocators[quotaAllocator.Name] = info\n\treturn nil\n}", "func (b *Buffer) Release() {\n\tif b.mem != nil || b.parent != nil {\n\t\tdebug.Assert(atomic.LoadInt64(&b.refCount) > 0, \"too many releases\")\n\n\t\tif atomic.AddInt64(&b.refCount, -1) == 0 {\n\t\t\tif b.mem != nil {\n\t\t\t\tb.mem.Free(b.buf)\n\t\t\t} else {\n\t\t\t\tb.parent.Release()\n\t\t\t\tb.parent = nil\n\t\t\t}\n\t\t\tb.buf, b.length = nil, 0\n\t\t}\n\t}\n}", "func (_TokenVesting *TokenVestingSession) Release(_token common.Address) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.Release(&_TokenVesting.TransactOpts, _token)\n}", "func (sm *SourceMgr) Release() {\n\tos.Remove(path.Join(sm.cachedir, \"sm.lock\"))\n}", "func (lr *libraryCache) Release() {\n\tlr.mtx.Lock()\n\tdefer lr.mtx.Unlock()\n\n\tif lr.refCount == 0 {\n\t\treturn\n\t}\n\n\tlr.refCount--\n\tif lr.refCount == 0 {\n\t\tos.RemoveAll(lr.path)\n\t\tlr.path = \"\"\n\t}\n}", "func (_m *TimeoutSemaphoreInterface) Release(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func (cr *ChunkIterator) Release() {\n\tdebug.Assert(atomic.LoadInt64(&cr.refCount) > 0, \"too many releases\")\n\tref := atomic.AddInt64(&cr.refCount, -1)\n\tif ref == 0 {\n\t\tcr.col.Release()\n\t\tfor i := range cr.chunks {\n\t\t\tcr.chunks[i].Release()\n\t\t}\n\t\tif cr.currentChunk != nil {\n\t\t\tcr.currentChunk.Release()\n\t\t\tcr.currentChunk = nil\n\t\t}\n\t\tcr.col = nil\n\t\tcr.chunks = nil\n\t\tcr.dtype = nil\n\t}\n}", "func (p *provider) release() error {\n\tp.m.Lock()\n\tdefer p.m.Unlock()\n\n\tp.refs--\n\n\tif p.refs > 0 {\n\t\treturn nil\n\t}\n\n\tdb := p.db\n\tp.db = nil\n\n\treturn p.close(db)\n}", "func release(k *gostwriter.K) {\n\terr := k.Release()\n\tguard(err)\n}", "func ReleaseEncoder(enc *Encoder) []byte {\n\tdata := enc.Bytes()\n\tenc.Reset(nil)\n\tencoderPool.Put(enc)\n\treturn data\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (s *Sampler) Release() {\n\treleaseSampler(s)\n}", "func (d *DeviceInfoCache) Release(deviceInfo DeviceInfo) error {\n\n\t//this information record might be used by more than one SSM\n\tif deviceInfo._refCount == 0 {\n\t\treturn errors.New(\"reference count\")\n\t}\n\n\t// decrement the reference count\n\tdeviceInfo._refCount--\n\td.cache[deviceInfo._cacheKey.HashKey()] = deviceInfo\n\treturn nil\n}", "func (p *tubePool) allocAndReleaseGate(session int64, done chan tube, releaseGate bool, opt RequestOptions) {\n\ttube, err := p.alloc(session, opt)\n\tif releaseGate {\n\t\tp.gate.exit()\n\t}\n\tif err == nil {\n\t\tselect {\n\t\tcase done <- tube:\n\t\tdefault:\n\t\t\tp.put(tube)\n\t\t}\n\t} else {\n\t\tp.mutex.Lock()\n\t\tif !p.closed {\n\t\t\tselect {\n\t\t\tcase p.errCh <- err:\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t\tp.mutex.Unlock()\n\t}\n\tif done != nil {\n\t\tclose(done)\n\t}\n}", "func (alloc *inMemoryAllocator) GetType() AllocatorType {\n\treturn alloc.allocType\n}", "func ReleaseResponse(resp *Response) {\n\tresp.Reset()\n\tresponsePool.Put(resp)\n}", "func NewDeviceAllocator() DeviceAllocator {\n\tpossibleDevices := make(map[mountDevice]int)\n\tfor _, firstChar := range []rune{'b', 'c'} {\n\t\tfor i := 'a'; i <= 'z'; i++ {\n\t\t\tdev := mountDevice([]rune{firstChar, i})\n\t\t\tpossibleDevices[dev] = 0\n\t\t}\n\t}\n\treturn &deviceAllocator{\n\t\tpossibleDevices: possibleDevices,\n\t\tcounter: 0,\n\t}\n}", "func (t *tableCommon) Allocator(ctx sessionctx.Context) autoid.Allocator {\n\ttrace_util_0.Count(_tables_00000, 322)\n\tif ctx != nil {\n\t\ttrace_util_0.Count(_tables_00000, 324)\n\t\tsessAlloc := ctx.GetSessionVars().IDAllocator\n\t\tif sessAlloc != nil {\n\t\t\ttrace_util_0.Count(_tables_00000, 325)\n\t\t\treturn sessAlloc\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 323)\n\treturn t.alloc\n}", "func (elm *etcdLeaseManager) Release(key string) {\n\telm.mu.Lock()\n\tdefer elm.mu.Unlock()\n\n\telm.releaseUnlocked(key)\n}", "func (kvclient *MockResKVClient) ReleaseReservation(ctx context.Context, key string) error {\n\treturn nil\n}", "func (rh *ReservationHelper) ReleaseReservation(\n\tctx context.Context, volume *genV1.Volume, ac, acReplacement *accrd.AvailableCapacity) error {\n\tlogger := util.AddCommonFields(ctx, rh.logger, \"ReservationHelper.ReleaseReservation\")\n\tif err := rh.updateIfRequired(ctx); err != nil {\n\t\treturn err\n\t}\n\t// we should select ACR to remove from ACRs which have same size and SC as volume\n\tfilteredACRMap, filteredACNameToACR := buildACRMaps(\n\t\tFilterACRList(rh.acrList, func(acr acrcrd.AvailableCapacityReservation) bool {\n\t\t\treturn acr.Spec.StorageClass == volume.StorageClass && acr.Spec.Size == volume.Size\n\t\t}))\n\t_, acrToRemove := choseACFromOldestACR(ACMap{ac.Name: ac}, filteredACRMap, filteredACNameToACR)\n\tif acrToRemove == nil {\n\t\tlogger.Infof(\"ACR holding AC %s not found. Skip deletion.\", ac.Name)\n\t\treturn nil\n\t}\n\tif err := rh.removeACR(ctx, acrToRemove); err != nil {\n\t\treturn err\n\t}\n\tif ac == acReplacement {\n\t\treturn nil\n\t}\n\tif err := rh.removeACFromACRs(ctx, acrToRemove.Name, ac); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *pollerAutoScaler) Release(resource autoscaler.ResourceUnit) {\n\tp.sem.Release(int(resource))\n}", "func (b *Bucket) Release() {\n\tif b == nil || b.tokens == nil {\n\t\treturn\n\t}\n\tselect {\n\tcase <-b.tokens:\n\tdefault:\n\t}\n}", "func (ctx *Context) Release() {\n\treleaseContext(ctx)\n}", "func ReleaseBuffer(buffer Buffer) {\n\tpool.put(buffer)\n}", "func NewPodAllocator(netInfo util.NetInfo, podLister listers.PodLister, kube kube.Interface) *PodAllocator {\n\tpodAnnotationAllocator := pod.NewPodAnnotationAllocator(\n\t\tnetInfo,\n\t\tpodLister,\n\t\tkube,\n\t)\n\n\tpodAllocator := &PodAllocator{\n\t\tnetInfo: netInfo,\n\t\treleasedPods: map[string]sets.Set[string]{},\n\t\treleasedPodsMutex: sync.Mutex{},\n\t\tpodAnnotationAllocator: podAnnotationAllocator,\n\t}\n\n\t// this network might not have IPAM, we will just allocate MAC addresses\n\tif util.DoesNetworkRequireIPAM(netInfo) {\n\t\tpodAllocator.ipAllocator = subnet.NewAllocator()\n\t}\n\n\treturn podAllocator\n}", "func (a *allocator) Recycle() {\n\ta.base.Recycle()\n}", "func (mci *XMCacheIterator) Release() {\n\tif mci.dir == dirReleased {\n\t\treturn\n\t}\n\tmci.dir = dirReleased\n\tif mci.mIter != nil {\n\t\tmci.mIter.Release()\n\t}\n\tfor _, it := range mci.iters {\n\t\tit.Release()\n\t}\n\tmci.keys = nil\n\tmci.iters = nil\n}", "func Release(p PTR) {\n\tC.release(C.PTR(p))\n}", "func (sm *SourceMgr) Release() {\n\tsm.lf.Close()\n\tos.Remove(filepath.Join(sm.cachedir, \"sm.lock\"))\n}", "func (it *iterator) Release() {\n\tclose(it.next)\n}", "func (c Controller) Release() {\n\tcapnp.Client(c).Release()\n}", "func NewGlobalTSOAllocator(\n\tam *AllocatorManager,\n\tleadership *election.Leadership,\n) Allocator {\n\tgta := &GlobalTSOAllocator{\n\t\tallocatorManager: am,\n\t\tleadership: leadership,\n\t\ttimestampOracle: &timestampOracle{\n\t\t\tclient: leadership.GetClient(),\n\t\t\trootPath: am.rootPath,\n\t\t\tsaveInterval: am.saveInterval,\n\t\t\tupdatePhysicalInterval: am.updatePhysicalInterval,\n\t\t\tmaxResetTSGap: am.maxResetTSGap,\n\t\t\tdcLocation: GlobalDCLocation,\n\t\t\ttsoMux: &tsoObject{},\n\t\t},\n\t}\n\treturn gta\n}", "func Free(p Pointer) {\n\tallocator.Free(uintptr(p))\n}", "func (p *ResourcePool) doFree(a Alloc) error {\n\tid := a.ID()\n\tif p.allocs[id] != a {\n\t\treturn nil\n\t}\n\tdelete(p.allocs, id)\n\treturn p.manager.Kill(a)\n}", "func (rebase *Rebase) Free() {\n\truntime.SetFinalizer(rebase, nil)\n\tC.git_rebase_free(rebase.ptr)\n}", "func (c PersistentIdentity) Release() {\n\tcapnp.Client(c).Release()\n}", "func (sem *Semaphore) Release() {\n\tsem.slots <- struct{}{}\n}", "func (c *QueueController) Release() {\n\tclose(c.reqCh)\n}", "func (iter *ldbCacheIter) Release() {\n}", "func (r *Reaper) MustRelease() Destructor {\n\tdtor, err := r.Release()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn dtor\n}" ]
[ "0.81131625", "0.64977455", "0.64955264", "0.6233524", "0.6059499", "0.604095", "0.59881294", "0.59217936", "0.59119517", "0.5881009", "0.585588", "0.5847171", "0.5824737", "0.5790185", "0.56845546", "0.5651543", "0.5623506", "0.5620355", "0.56128675", "0.5577229", "0.55664533", "0.5508566", "0.55084443", "0.5491774", "0.54756415", "0.5455362", "0.544748", "0.5394747", "0.5374111", "0.5362999", "0.5346324", "0.5340482", "0.5316079", "0.53064674", "0.5286615", "0.52764666", "0.52754813", "0.5274515", "0.52672213", "0.52663815", "0.52619797", "0.5258916", "0.5247062", "0.5225845", "0.5198869", "0.51913166", "0.5179808", "0.51791257", "0.51721156", "0.5170974", "0.51684546", "0.5163162", "0.5162442", "0.51529056", "0.51376283", "0.5136907", "0.51215285", "0.5119683", "0.51142555", "0.50805825", "0.5076433", "0.507555", "0.50657576", "0.506125", "0.50532794", "0.5042628", "0.5034848", "0.5034837", "0.50252086", "0.5019844", "0.501028", "0.50065976", "0.50052875", "0.500476", "0.5001767", "0.50008124", "0.500073", "0.49967572", "0.49932927", "0.4951296", "0.49511155", "0.49504763", "0.49459922", "0.4945317", "0.49437845", "0.4942172", "0.49391234", "0.49376106", "0.49280185", "0.49274075", "0.49187866", "0.49038902", "0.48980716", "0.48964584", "0.48805925", "0.4874965", "0.48743984", "0.48722187", "0.48547292", "0.4852783" ]
0.7707561
1
PrepareUpdate reserves an allocator and uses it to prepare an update operation. See Allocator.PrepareUpdate for details
PrepareUpdate выделяет аллоциатор и использует его для подготовки операции обновления. См. Allocator.PrepareUpdate для деталей
func (idx *Tree) PrepareUpdate(key []byte) (found bool, op *UpdateOperation) { id := idx.allocatorQueue.get() op = newUpdateOperation(idx, idx.allocators[id], true) return op.prepareUpdate(key), op }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Table) PrepareUpdate(tu fibdef.Update) (*UpdateCommand, error) {\n\tu := &UpdateCommand{}\n\tu.real.RealUpdate = tu.Real()\n\tu.virt.VirtUpdate = tu.Virt()\n\n\tu.allocSplit = u.real.prepare(t)\n\tu.allocated = make([]*Entry, u.allocSplit+u.virt.prepare(t))\n\tif e := t.allocBulk(u.allocated); e != nil {\n\t\treturn nil, e\n\t}\n\n\treturn u, nil\n}", "func AllocateUpdate() int {\n\tupdateIdGen++\n\treturn updateIdGen\n}", "func (m *MockAllocStateUpdater) Update(alloc *structs.Allocation) {\n\tm.mu.Lock()\n\tm.Allocs = append(m.Allocs, alloc)\n\tm.mu.Unlock()\n}", "func (s DirectorBindStatusStrategy) PrepareForUpdate(ctx request.Context, obj, old runtime.Object) {\n\ts.DefaultStatusStorageStrategy.PrepareForUpdate(ctx, obj, old)\n\tdNew := obj.(*bind.DirectorBind)\n\tlabels := dNew.GetObjectMeta().GetLabels()\n\tif labels == nil {\n\t\tlabels = make(map[string]string)\n\t\tdNew.GetObjectMeta().SetLabels(labels)\n\t}\n\tlabels[\"state\"] = dNew.Status.State\n}", "func (detailsStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewBuild := obj.(*buildapi.Build)\n\toldBuild := old.(*buildapi.Build)\n\n\t// ignore phase updates unless the caller is updating the build to\n\t// a completed phase.\n\tphase := oldBuild.Status.Phase\n\tstages := newBuild.Status.Stages\n\tif buildinternalhelpers.IsBuildComplete(newBuild) {\n\t\tphase = newBuild.Status.Phase\n\t}\n\trevision := newBuild.Spec.Revision\n\tmessage := newBuild.Status.Message\n\treason := newBuild.Status.Reason\n\toutputTo := newBuild.Status.Output.To\n\t*newBuild = *oldBuild\n\tnewBuild.Status.Phase = phase\n\tnewBuild.Status.Stages = stages\n\tnewBuild.Spec.Revision = revision\n\tnewBuild.Status.Reason = reason\n\tnewBuild.Status.Message = message\n\tnewBuild.Status.Output.To = outputTo\n}", "func (b *AllocUpdateBatcher) CreateUpdate(allocs map[string]*structs.DesiredTransition, eval *structs.Evaluation) *BatchFuture {\n\twrapper := &updateWrapper{\n\t\tallocs: allocs,\n\t\te: eval,\n\t\tf: make(chan *BatchFuture, 1),\n\t}\n\n\tb.workCh <- wrapper\n\treturn <-wrapper.f\n}", "func (s *ReleaseServer) prepareUpdate(req *services.UpdateReleaseRequest) (*release.Release, *release.Release, error) {\n\tif req.Chart == nil {\n\t\treturn nil, nil, errMissingChart\n\t}\n\n\t// finds the deployed release with the given name\n\tcurrentRelease, err := s.env.Releases.Deployed(req.Name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// determine if values will be reused\n\tif err := s.reuseValues(req, currentRelease); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// finds the non-deleted release with the given name\n\tlastRelease, err := s.env.Releases.Last(req.Name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Increment revision count. This is passed to templates, and also stored on\n\t// the release object.\n\trevision := lastRelease.Version + 1\n\n\tts := timeconv.Now()\n\toptions := chartutil.ReleaseOptions{\n\t\tName: req.Name,\n\t\tTime: ts,\n\t\tNamespace: currentRelease.Namespace,\n\t\tIsUpgrade: true,\n\t\tRevision: int(revision),\n\t}\n\n\tcaps, err := capabilities(s.clientset.Discovery())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvaluesToRender, err := chartutil.ToRenderValuesCaps(req.Chart, req.Values, options, caps)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\thooks, manifestDoc, notesTxt, err := s.renderResources(req.Chart, valuesToRender, caps.APIVersions)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Store an updated release.\n\tupdatedRelease := &release.Release{\n\t\tName: req.Name,\n\t\tNamespace: currentRelease.Namespace,\n\t\tChart: req.Chart,\n\t\tConfig: req.Values,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: currentRelease.Info.FirstDeployed,\n\t\t\tLastDeployed: ts,\n\t\t\tStatus: &release.Status{Code: release.Status_PENDING_UPGRADE},\n\t\t\tDescription: \"Preparing upgrade\", // This should be overwritten later.\n\t\t},\n\t\tVersion: revision,\n\t\tManifest: manifestDoc.String(),\n\t\tHooks: hooks,\n\t}\n\n\tif len(notesTxt) > 0 {\n\t\tupdatedRelease.Info.Status.Notes = notesTxt\n\t}\n\terr = validateManifest(s.env.KubeClient, currentRelease.Namespace, manifestDoc.Bytes())\n\treturn currentRelease, updatedRelease, err\n}", "func (podPresetStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {\n\tnewPodPreset := obj.(*settings.PodPreset)\n\toldPodPreset := old.(*settings.PodPreset)\n\n\t// Update is not allowed\n\tnewPodPreset.Spec = oldPodPreset.Spec\n}", "func (endpointSliceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewEPS := obj.(*discovery.EndpointSlice)\n\toldEPS := old.(*discovery.EndpointSlice)\n\n\t// Increment generation if anything other than meta changed\n\t// This needs to be changed if a status attribute is added to EndpointSlice\n\togNewMeta := newEPS.ObjectMeta\n\togOldMeta := oldEPS.ObjectMeta\n\tnewEPS.ObjectMeta = v1.ObjectMeta{}\n\toldEPS.ObjectMeta = v1.ObjectMeta{}\n\n\tif !apiequality.Semantic.DeepEqual(newEPS, oldEPS) {\n\t\togNewMeta.Generation = ogOldMeta.Generation + 1\n\t}\n\n\tnewEPS.ObjectMeta = ogNewMeta\n\toldEPS.ObjectMeta = ogOldMeta\n\n\tdropDisabledConditionsOnUpdate(oldEPS, newEPS)\n}", "func (sc *schedulerCache) updateQuotaAllocator(oldQuotaAllocator, newQuotaAllocator *arbv1.QuotaAllocator) error {\n\tif err := sc.deleteQuotaAllocator(oldQuotaAllocator); err != nil {\n\t\treturn err\n\t}\n\tsc.addQuotaAllocator(newQuotaAllocator)\n\treturn nil\n}", "func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewBuild := obj.(*buildapi.Build)\n\toldBuild := old.(*buildapi.Build)\n\t// If the build is already in a failed state, do not allow an update\n\t// of the reason and message. This is to prevent the build controller from\n\t// overwriting the reason and message that was set by the builder pod\n\t// when it updated the build's details.\n\t// Only allow OOMKilled override because various processes in a container\n\t// can get OOMKilled and this confuses builder to prematurely populate\n\t// failure reason\n\tif oldBuild.Status.Phase == buildapi.BuildPhaseFailed &&\n\t\tnewBuild.Status.Reason != buildapi.StatusReasonOutOfMemoryKilled {\n\t\tnewBuild.Status.Reason = oldBuild.Status.Reason\n\t\tnewBuild.Status.Message = oldBuild.Status.Message\n\t}\n}", "func (rh *ReservationHelper) Update(ctx context.Context) error {\n\tlogger := util.AddCommonFields(ctx, rh.logger, \"ReservationHelper.update\")\n\tvar err error\n\trh.acList, err = rh.capReader.ReadCapacity(ctx)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to read AC list: %s\", err.Error())\n\t\treturn err\n\t}\n\trh.acrList, err = rh.resReader.ReadReservations(ctx)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to read ACR list: %s\", err.Error())\n\t\treturn err\n\t}\n\trh.acMap = buildACMap(rh.acList)\n\trh.acrMap, rh.acNameToACR = buildACRMaps(rh.acrList)\n\n\trh.updated = true\n\n\treturn nil\n}", "func (accountStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {\n}", "func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\t_ = obj.(*authorizationapi.RoleBindingRestriction)\n\t_ = old.(*authorizationapi.RoleBindingRestriction)\n}", "func (client *CapacityReservationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsBeginUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif capacityReservationGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationGroupName}\", url.PathEscape(capacityReservationGroupName))\n\tif capacityReservationName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationName}\", url.PathEscape(capacityReservationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func (idx *Tree) PrepareDelete(key []byte) (found bool, op *DeleteOperation) {\n\tid := idx.allocatorQueue.get()\n\top = newDeleteOperation(idx, idx.allocators[id], true)\n\tif op.prepare(key) {\n\t\treturn true, op\n\t}\n\top.Abort()\n\treturn false, nil\n}", "func NewAllocUpdateBatcher(ctx context.Context, batchDuration time.Duration, raft DeploymentRaftEndpoints) *AllocUpdateBatcher {\n\tb := &AllocUpdateBatcher{\n\t\tbatch: batchDuration,\n\t\traft: raft,\n\t\tctx: ctx,\n\t\tworkCh: make(chan *updateWrapper, 10),\n\t}\n\n\tgo b.batcher()\n\treturn b\n}", "func (client *CapacitiesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, dedicatedCapacityName string, capacityUpdateParameters DedicatedCapacityUpdateParameters, options *CapacitiesClientBeginUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif dedicatedCapacityName == \"\" {\n\t\treturn nil, errors.New(\"parameter dedicatedCapacityName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{dedicatedCapacityName}\", url.PathEscape(dedicatedCapacityName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-01-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, capacityUpdateParameters)\n}", "func (client QuotaRequestClient) UpdatePreparer(ctx context.Context, subscriptionID string, providerID string, location string, resourceName string, createQuotaRequest CurrentQuotaLimitBase, ifMatch string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"location\": autorest.Encode(\"path\", location),\n\t\t\"providerId\": autorest.Encode(\"path\", providerID),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", subscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-07-19-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}\", pathParameters),\n\t\tautorest.WithJSON(createQuotaRequest),\n\t\tautorest.WithQueryParameters(queryParameters),\n\t\tautorest.WithHeader(\"If-Match\", autorest.String(ifMatch)))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (b *CompactableBuffer) Update(address *EntryAddress, data []byte) error {\n\taddress.LockForWrite()\n\tdefer address.UnlockWrite()\n\theader, err := b.ReadHeader(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbeforeUpdataDataSize := header.dataSize\n\tafterUpdateDataSize := len(data) + VarIntSize(len(data))\n\tdataSizeDelta := afterUpdateDataSize - int(beforeUpdataDataSize)\n\n\tremainingSpace := int(header.entrySize) - reservedSize - afterUpdateDataSize\n\theader.dataSize = int64(afterUpdateDataSize)\n\tif remainingSpace <= 0 {\n\t\tatomic.AddInt64(&b.dataSize, int64(-beforeUpdataDataSize))\n\t\tatomic.AddInt64(&b.entrySize, int64(-header.entrySize))\n\t\treturn b.expand(address, data)\n\t}\n\n\tatomic.AddInt64(&b.dataSize, int64(dataSizeDelta))\n\tvar target = make([]byte, 0)\n\tAppendToBytes(data, &target)\n\tif len(target) > int(header.dataSize) {\n\t\treturn io.EOF\n\t}\n\twritableBuffer := b.writableBuffer()\n\t_, err = writableBuffer.Write(address.Position()+reservedSize, target...)\n\treturn err\n}", "func NewUpdate(zone string, class uint16) *Msg {\n\tu := new(Msg)\n\tu.MsgHdr.Response = false\n\tu.MsgHdr.Opcode = OpcodeUpdate\n\tu.Compress = false // Seems BIND9 at least cannot handle compressed update pkgs\n\tu.Question = make([]Question, 1)\n\tu.Question[0] = Question{zone, TypeSOA, class}\n\treturn u\n}", "func (vc *VehicleContainer) Prepare(apiEntries []*APIVehicleEntry) error {\n\ttimezone, err := time.LoadLocation(\"Europe/Warsaw\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvc.Vehicles = make(map[string]*Vehicle, len(apiEntries))\n\n\tfor _, ae := range apiEntries {\n\t\tv, err := NewVehicle(ae, timezone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvc.Vehicles[v.ID] = v\n\t}\n\n\treturn nil\n}", "func (sb *spdkBackend) Prepare(req storage.BdevPrepareRequest) (*storage.BdevPrepareResponse, error) {\n\tsb.log.Debugf(\"spdk backend prepare (script call): %+v\", req)\n\treturn sb.prepare(req, DetectVMD, cleanHugepages)\n}", "func (t *Table) DiscardUpdate(u *UpdateCommand) {\n\tif u.allocated != nil {\n\t\tmempool.Free(t.mp, u.allocated)\n\t}\n\tu.clear()\n}", "func (e *UpdateExec) prepare(row []types.Datum) (err error) {\n\tif e.updatedRowKeys == nil {\n\t\te.updatedRowKeys = make(map[int]*kv.MemAwareHandleMap[bool])\n\t}\n\te.handles = e.handles[:0]\n\te.tableUpdatable = e.tableUpdatable[:0]\n\te.changed = e.changed[:0]\n\te.matches = e.matches[:0]\n\tfor _, content := range e.tblColPosInfos {\n\t\tif e.updatedRowKeys[content.Start] == nil {\n\t\t\te.updatedRowKeys[content.Start] = kv.NewMemAwareHandleMap[bool]()\n\t\t}\n\t\thandle, err := content.HandleCols.BuildHandleByDatums(row)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\te.handles = append(e.handles, handle)\n\n\t\tupdatable := false\n\t\tflags := e.assignFlag[content.Start:content.End]\n\t\tfor _, flag := range flags {\n\t\t\tif flag >= 0 {\n\t\t\t\tupdatable = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif unmatchedOuterRow(content, row) {\n\t\t\tupdatable = false\n\t\t}\n\t\te.tableUpdatable = append(e.tableUpdatable, updatable)\n\n\t\tchanged, ok := e.updatedRowKeys[content.Start].Get(handle)\n\t\tif ok {\n\t\t\te.changed = append(e.changed, changed)\n\t\t\te.matches = append(e.matches, false)\n\t\t} else {\n\t\t\te.changed = append(e.changed, false)\n\t\t\te.matches = append(e.matches, true)\n\t\t}\n\t}\n\treturn nil\n}", "func (client AccountClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, body AccountResourcePatchDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPatch(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (n *NodeBlockMaker) doPrepareNewBlock() error {\n\t// firstly, check count of transactions to know if there are enough\n\tcount, err := n.getTransactionsManager().GetUnapprovedCount()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tmin, max, err := n.getTransactionNumbersLimits(nil)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.Logger.Trace.Printf(\"Minting: Found %d transaction from minimum %d\\n\", count, min)\n\n\tif count >= min {\n\t\t// number of transactions is fine\n\t\tif count > max {\n\t\t\tcount = max\n\t\t}\n\t\t// get unapproved transactions\n\t\ttxs, err := n.getTransactionsManager().GetUnapprovedTransactionsForNewBlock(count)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(txs) < min {\n\t\t\treturn errors.New(\"No enought valid transactions! Waiting for new ones...\")\n\t\t}\n\n\t\tn.Logger.Trace.Printf(\"Minting: All good. New block assigned to address %s\\n\", n.MinterAddress)\n\n\t\tnewBlock, err := n.makeNewBlockFromTransactions(txs)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tn.Logger.Trace.Printf(\"Minting: New block Prepared. Not yet complete\\n\")\n\n\t\tn.PreparedBlock = newBlock\n\n\t}\n\n\treturn nil\n}", "func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRole := obj.(*rbac.Role)\n\toldRole := old.(*rbac.Role)\n\n\t_, _ = newRole, oldRole\n}", "func (_RandomBeacon *RandomBeaconTransactor) UpdateAuthorizationParameters(opts *bind.TransactOpts, _minimumAuthorization *big.Int, _authorizationDecreaseDelay uint64, _authorizationDecreaseChangePeriod uint64) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"updateAuthorizationParameters\", _minimumAuthorization, _authorizationDecreaseDelay, _authorizationDecreaseChangePeriod)\n}", "func (c *HardwareConfig) Prepare() []error {\n\tvar errs []error\n\n\tif c.RAMReservation > 0 && c.RAMReserveAll != false {\n\t\terrs = append(errs, fmt.Errorf(\"'RAM_reservation' and 'RAM_reserve_all' cannot be used together\"))\n\t}\n\n\treturn errs\n}", "func PrepareDBSweep() error {\n\tif !isDBInit {\n\t\tisDBInit = true\n\t\tdbInit <- 1\n\t}\n\treturn nil\n}", "func (c *Command) Prepare() {}", "func (client VersionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, templateSpecName string, templateSpecVersion string, templateSpecVersionUpdateModel *VersionUpdateModel) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"templateSpecName\": autorest.Encode(\"path\", templateSpecName),\n\t\t\"templateSpecVersion\": autorest.Encode(\"path\", templateSpecVersion),\n\t}\n\n\tconst APIVersion = \"2019-06-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Resources/templateSpecs/{templateSpecName}/versions/{templateSpecVersion}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif templateSpecVersionUpdateModel != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(templateSpecVersionUpdateModel))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (cr *cmdRunner) prep(req storage.ScmPrepareRequest, scanRes *storage.ScmScanResponse) (resp *storage.ScmPrepareResponse, err error) {\n\tstate := scanRes.State\n\tresp = &storage.ScmPrepareResponse{State: state}\n\n\tcr.log.Debugf(\"scm backend prep: state %q\", state)\n\n\tif err = cr.deleteGoals(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Handle unspecified NrNamespacesPerSocket in request.\n\tif req.NrNamespacesPerSocket == 0 {\n\t\treq.NrNamespacesPerSocket = minNrNssPerSocket\n\t}\n\n\tswitch state {\n\tcase storage.ScmStateNotInterleaved:\n\t\t// Non-interleaved AppDirect memory mode is unsupported.\n\t\terr = storage.FaultScmNotInterleaved\n\tcase storage.ScmStateNoRegions:\n\t\t// No regions exist, create interleaved AppDirect PMem regions.\n\t\tif err = cr.createRegions(); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tresp.RebootRequired = true\n\tcase storage.ScmStateFreeCapacity:\n\t\t// Regions exist but no namespaces, create block devices on PMem regions.\n\t\tresp.Namespaces, err = cr.createNamespaces(req.NrNamespacesPerSocket)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tresp.State = storage.ScmStateNoFreeCapacity\n\tcase storage.ScmStateNoFreeCapacity:\n\t\t// Regions and namespaces exist so sanity check number of namespaces matches the\n\t\t// number requested before returning details.\n\t\tvar regionFreeBytes []uint64\n\t\tregionFreeBytes, err = cr.getRegionFreeSpace()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tnrRegions := uint(len(regionFreeBytes))\n\t\tnrNamespaces := uint(len(scanRes.Namespaces))\n\n\t\t// Assume 1:1 mapping between region and NUMA node.\n\t\tif (nrRegions * req.NrNamespacesPerSocket) != nrNamespaces {\n\t\t\terr = storage.FaultScmNamespacesNrMismatch(req.NrNamespacesPerSocket,\n\t\t\t\tnrRegions, nrNamespaces)\n\t\t\tbreak\n\t\t}\n\t\tresp.Namespaces = scanRes.Namespaces\n\tdefault:\n\t\terr = errors.Errorf(\"unhandled scm state %q\", state)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n\tif mb.resourceCapacity < rm.Resource().Attributes().Len() {\n\t\tmb.resourceCapacity = rm.Resource().Attributes().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n\tif mb.resourceCapacity < rm.Resource().Attributes().Len() {\n\t\tmb.resourceCapacity = rm.Resource().Attributes().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n\tif mb.resourceCapacity < rm.Resource().Attributes().Len() {\n\t\tmb.resourceCapacity = rm.Resource().Attributes().Len()\n\t}\n}", "func (sb *spdkBackend) prepare(req storage.BdevPrepareRequest, vmdDetect vmdDetectFn, hpClean hpCleanFn) (*storage.BdevPrepareResponse, error) {\n\tresp := &storage.BdevPrepareResponse{}\n\n\tif req.CleanHugepagesOnly {\n\t\t// Remove hugepages that were created by a no-longer-active SPDK process. Note that\n\t\t// when running prepare, it's unlikely that any SPDK processes are active as this\n\t\t// is performed prior to starting engines.\n\t\tnrRemoved, err := hpClean(sb.log, hugepageDir)\n\t\tif err != nil {\n\t\t\treturn resp, errors.Wrapf(err, \"clean spdk hugepages\")\n\t\t}\n\t\tresp.NrHugepagesRemoved = nrRemoved\n\n\t\tlogNUMAStats(sb.log)\n\n\t\treturn resp, nil\n\t}\n\n\t// Update request if VMD has been explicitly enabled and there are VMD endpoints configured.\n\tif err := updatePrepareRequest(sb.log, &req, vmdDetect); err != nil {\n\t\treturn resp, errors.Wrapf(err, \"update prepare request\")\n\t}\n\tresp.VMDPrepared = req.EnableVMD\n\n\t// Before preparing, reset device bindings.\n\tif req.EnableVMD {\n\t\t// Unbind devices to speed up VMD re-binding as per\n\t\t// https://github.com/spdk/spdk/commit/b0aba3fcd5aceceea530a702922153bc75664978.\n\t\t//\n\t\t// Applies block (not allow) list if VMD is configured so specific NVMe devices can\n\t\t// be reserved for other use (bdev_exclude).\n\t\tif err := sb.script.Unbind(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"un-binding devices\")\n\t\t}\n\t} else {\n\t\tif err := sb.script.Reset(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"resetting device bindings\")\n\t\t}\n\t}\n\n\treturn resp, errors.Wrap(sb.script.Prepare(&req), \"binding devices to userspace drivers\")\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) UpdateRequest(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"updateRequest\")\n}", "func (p *Preparer) Prepare(fullInfo chan resource.Resource, done chan bool, mapWg *sync.WaitGroup) {\n\tmapWg.Wait()\n\n\tvar wg sync.WaitGroup\n\n\tidentifierSend := false\n\n\tfor data := range fullInfo {\n\t\tif !identifierSend {\n\t\t\terr := p.prep.SendIdentifier()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"error\": err}).Fatal(\"error send identifier\")\n\t\t\t}\n\t\t\tidentifierSend = true\n\t\t}\n\t\twg.Add(1)\n\t\tgo p.prep.Preparation(data, &wg)\n\t}\n\n\twg.Wait()\n\n\t// If the identifier was not sent, there is no resource to prepare and send,\n\t// a gRPC connection was not open and no finishing and closing of a connection are needed.\n\tif identifierSend {\n\t\tp.prep.Finish()\n\t}\n\n\tdone <- true\n}", "func (c *AgonesDiscoverAllocator) Allocate(ctx context.Context, req *pb.AssignTicketsRequest) error {\n\tlogger := runtime.Logger().WithField(\"component\", \"allocator\")\n\n\tfor _, assignmentGroup := range req.Assignments {\n\t\tif err := IsAssignmentGroupValidForAllocation(assignmentGroup); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfilter, err := extensions.ExtractFilterFromExtensions(assignmentGroup.Assignment.Extensions)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"the assignment does not have a valid filter extension\")\n\t\t}\n\n\t\tgameservers, err := c.ListGameServers(ctx, filter)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif len(gameservers) == 0 {\n\t\t\tlogger.Debugf(\"gameservers not found for request with filter %v\", filter.Map())\n\t\t\tcontinue\n\t\t}\n\n\t\t// NiceToHave: Filter GameServers by Capacity and Count\n\t\t// Remove not assigned tickets based on playersCapacity - Count\n\t\t// strategy: allTogether, CapacityBased FallBack\n\t\tfor _, gs := range gameservers {\n\t\t\tif HasCapacity(assignmentGroup, gs) {\n\t\t\t\tassignmentGroup.Assignment.Connection = gs.Status.Address\n\t\t\t\t//logger.Debugf(\"extension %v\", assignmentGroup.Assignment.Extensions)\n\t\t\t\tlogger.Infof(\"gameserver %s connection %s assigned to request, total tickets: %d\", gs.Name, assignmentGroup.Assignment.Connection, len(assignmentGroup.TicketIds))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (client DeploymentsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithJSON(deploymentResource),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (s *BasevhdlListener) EnterAllocator(ctx *AllocatorContext) {}", "func (client AccountQuotaPolicyClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, policyName string, body AccountQuotaPolicyResourcePatchDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"policyName\": policyName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPatch(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/accountQuotaPolicies/{policyName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (_RandomBeacon *RandomBeaconTransactorSession) UpdateAuthorizationParameters(_minimumAuthorization *big.Int, _authorizationDecreaseDelay uint64, _authorizationDecreaseChangePeriod uint64) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateAuthorizationParameters(&_RandomBeacon.TransactOpts, _minimumAuthorization, _authorizationDecreaseDelay, _authorizationDecreaseChangePeriod)\n}", "func Enqueue(update *update.UpdateEntry) {\n\tif update.SeqId==0 {\n\t\tupdate.SeqId=AllocateUpdate()\n\t}\n\tcurrentQueue[update.SeqId]=update\n}", "func (_Container *ContainerTransactor) UpdateRequest(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Container.contract.Transact(opts, \"updateRequest\")\n}", "func (d *DataBuckets) Prepare() {\n}", "func (a *Agent) PreUpdate(s gorp.SqlExecutor) error {\n\ta.Updated = time.Now()\n\treturn nil\n}", "func (txmgr *LockBasedTxMgr) ValidateAndPrepare(blockAndPvtdata *ledger.BlockAndPvtData, doMVCCValidation bool) (\n\t[]*validation.AppInitiatedPurgeUpdate, []*validation.TxStatInfo, []byte, error,\n) {\n\t// Among ValidateAndPrepare(), PrepareForExpiringKeys(), and\n\t// RemoveStaleAndCommitPvtDataOfOldBlocks(), we can allow only one\n\t// function to execute at a time. The reason is that each function calls\n\t// LoadCommittedVersions() which would clear the existing entries in the\n\t// transient buffer and load new entries (such a transient buffer is not\n\t// applicable for the golevelDB). As a result, these three functions can\n\t// interleave and nullify the optimization provided by the bulk read API.\n\t// Once the ledger cache (FAB-103) is introduced and existing\n\t// LoadCommittedVersions() is refactored to return a map, we can allow\n\t// these three functions to execute parallelly.\n\tlogger.Debugf(\"Waiting for purge mgr to finish the background job of computing expirying keys for the block\")\n\ttxmgr.pvtdataPurgeMgr.WaitForPrepareToFinish()\n\ttxmgr.oldBlockCommit.Lock()\n\tdefer txmgr.oldBlockCommit.Unlock()\n\tlogger.Debug(\"lock acquired on oldBlockCommit for validating read set version against the committed version\")\n\n\tblock := blockAndPvtdata.Block\n\tlogger.Debugf(\"Validating new block with num trans = [%d]\", len(block.Data.Data))\n\tbatch, appPurgeUpdates, txstatsInfo, err := txmgr.commitBatchPreparer.ValidateAndPrepareBatch(blockAndPvtdata, doMVCCValidation)\n\tif err != nil {\n\t\ttxmgr.reset()\n\t\treturn nil, nil, nil, err\n\t}\n\ttxmgr.currentUpdates = &currentUpdates{block: block, batch: batch}\n\tif err := txmgr.invokeNamespaceListeners(); err != nil {\n\t\ttxmgr.reset()\n\t\treturn nil, nil, nil, err\n\t}\n\n\tupdateBytes, err := deterministicBytesForPubAndHashUpdates(batch)\n\treturn appPurgeUpdates, txstatsInfo, updateBytes, err\n}", "func (l *blocksLRU) prepareForAdd() {\n\tswitch {\n\tcase l.ll.Len() > l.capacity:\n\t\tpanic(\"impossible\")\n\tcase l.ll.Len() == l.capacity:\n\t\toldest := l.ll.Remove(l.ll.Back()).(block)\n\t\tdelete(l.blocks, oldest.offset)\n\t\tl.evicted(oldest)\n\t}\n}", "func assembleAssetUpdate(curr, update *BaseAsset) {\n\tfor currK, currV := range curr.Data {\n\t\t// Do not update field in `update` asset from `curr` asset\n\t\tif _, ok := update.Data[currK]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tupdate.Data[currK] = currV\n\t}\n}", "func (action *ActionLocationNetworkCreate) Prepare() *ActionLocationNetworkCreateInvocation {\n\treturn &ActionLocationNetworkCreateInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/location_networks\",\n\t}\n}", "func TestAllocRunner_TerminalUpdate_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\t// Ensure task takes some time\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Driver = \"mock_driver\"\n\ttask.Config[\"run_for\"] = \"10s\"\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusRunning {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusRunning)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Update the alloc to be terminal which should cause the alloc runner to\n\t// stop the tasks and wait for a destroy.\n\tupdate := ar.alloc.Copy()\n\tupdate.DesiredStatus = structs.AllocDesiredStatusStop\n\tar.Update(update)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory still exists\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err != nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir destroyed: %v\", ar.allocDir.AllocDir)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Send the destroy signal and ensure the AllocRunner cleans up.\n\tar.Destroy()\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory was cleaned\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn false, fmt.Errorf(\"stat err: %v\", err)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\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 (h *HTTPTester) Prepare(stmt string, bSz int, tx bool) error {\n\ts := make([]string, bSz)\n\tfor i := 0; i < len(s); i++ {\n\t\ts[i] = stmt\n\t}\n\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.br = bytes.NewReader(b)\n\n\tif tx {\n\t\th.url = h.url + \"?transaction\"\n\t}\n\n\treturn nil\n}", "func (p *PetsEquipmentsetEntries) Prepare() {\n}", "func (_Mcapscontroller *McapscontrollerTransactor) UpdateMinimumBalance(opts *bind.TransactOpts, pool common.Address, tokenAddress common.Address) (*types.Transaction, error) {\n\treturn _Mcapscontroller.contract.Transact(opts, \"updateMinimumBalance\", pool, tokenAddress)\n}", "func execPrepareStmt(prepStmt string) {\n\tif db == nil {\n\t\tdb = getDB()\n\t}\n\n\tstmt, err := db.Prepare(prepStmt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = stmt.Exec()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (client ReferenceDataSetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, environmentName string, referenceDataSetName string, referenceDataSetUpdateParameters ReferenceDataSetUpdateParameters) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"environmentName\": autorest.Encode(\"path\", environmentName),\n\t\t\"referenceDataSetName\": autorest.Encode(\"path\", referenceDataSetName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-05-15\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}\", pathParameters),\n\t\tautorest.WithJSON(referenceDataSetUpdateParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client WorkloadNetworksClient) UpdateSegmentsPreparer(ctx context.Context, resourceGroupName string, privateCloudName string, segmentID string, workloadNetworkSegment WorkloadNetworkSegment) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"privateCloudName\": autorest.Encode(\"path\", privateCloudName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"segmentId\": autorest.Encode(\"path\", segmentID),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-07-17-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/workloadNetworks/default/segments/{segmentId}\", pathParameters),\n\t\tautorest.WithJSON(workloadNetworkSegment),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (p *pod) preparePodUpdateMessage(msgText string) string {\n\t// Handle simple message replacements.\n\treplacements := map[string]string{\n\t\t\"pod triggered scale-up\": \"Job requires additional resources, scaling up cluster.\",\n\t\t\"Successfully assigned\": \"Pod resources allocated.\",\n\t\t\"skip schedule deleting pod\": \"Deleting unscheduled pod.\",\n\t}\n\n\tsimpleReplacement := false\n\n\tfor k, v := range replacements {\n\t\tmatched, err := regexp.MatchString(k, msgText)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t} else if matched {\n\t\t\tmsgText = v\n\t\t\tsimpleReplacement = true\n\t\t}\n\t}\n\n\t// Otherwise, try special treatment for slots availability message.\n\tif !simpleReplacement {\n\t\tmatched, err := regexp.MatchString(\"nodes are available\", msgText)\n\t\tif err == nil && matched {\n\t\t\tavailable := string(msgText[0])\n\t\t\trequired := strconv.Itoa(p.slots)\n\t\t\tvar resourceName string\n\t\t\tswitch p.slotType {\n\t\t\tcase device.CPU:\n\t\t\t\tresourceName = \"CPU slots\"\n\t\t\tdefault:\n\t\t\t\tresourceName = \"GPUs\"\n\t\t\t}\n\n\t\t\tmsgText = fmt.Sprintf(\"Waiting for resources. %s %s are available, %s %s required\",\n\t\t\t\tavailable, resourceName, required, resourceName)\n\t\t}\n\t}\n\n\treturn msgText\n}", "func (oo *OnuDeviceEntry) PrepareForGarbageCollection(ctx context.Context, aDeviceID string) {\n\tlogger.Debugw(ctx, \"prepare for garbage collection\", log.Fields{\"device-id\": aDeviceID})\n\too.baseDeviceHandler = nil\n\too.pOnuTP = nil\n\tif oo.PDevOmciCC != nil {\n\t\too.PDevOmciCC.PrepareForGarbageCollection(ctx, aDeviceID)\n\t}\n\too.PDevOmciCC = nil\n}", "func NewUpdateDeviceRequest(d *v1alpha2.Device) *packngo.DeviceUpdateRequest {\n\treturn &packngo.DeviceUpdateRequest{\n\t\tHostname: d.Spec.ForProvider.Hostname,\n\t\tLocked: d.Spec.ForProvider.Locked,\n\t\tUserData: d.Spec.ForProvider.UserData,\n\t\tIPXEScriptURL: d.Spec.ForProvider.IPXEScriptURL,\n\t\tAlwaysPXE: d.Spec.ForProvider.AlwaysPXE,\n\t\tTags: &d.Spec.ForProvider.Tags,\n\t\tDescription: d.Spec.ForProvider.Description,\n\t\tCustomData: d.Spec.ForProvider.CustomData,\n\t}\n}", "func (i *Installer) Prepare(d Device) error {\n\t// Sanity check inputs.\n\tif i.config == nil {\n\t\treturn fmt.Errorf(\"installer missing config: %w\", errConfig)\n\t}\n\tif i.config.ImageFile() == \"\" {\n\t\treturn fmt.Errorf(\"missing image: %w\", errInput)\n\t}\n\text := regExFileExt.FindString(i.config.ImageFile())\n\tif ext == \"\" {\n\t\treturn fmt.Errorf(\"could not find extension for %q: %w\", i.config.ImageFile(), errFile)\n\t}\n\tf, err := os.Stat(filepath.Join(i.cache, i.config.ImageFile()))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v: %w\", err, errPath)\n\t}\n\t// Compensate for very small image files that can cause the wrong partition\n\t// to be selected.\n\tsize := uint64(f.Size())\n\tif size < oneGB {\n\t\tsize = oneGB\n\t}\n\t// Prepare the devices for provisioning.\n\tswitch {\n\tcase ext == \".iso\" && i.config.UpdateOnly():\n\t\treturn i.prepareForISOWithoutElevation(d, size)\n\tcase ext == \".iso\":\n\t\treturn i.prepareForISOWithElevation(d, size)\n\tcase ext == \".img\":\n\t\treturn i.prepareForRaw(d)\n\t}\n\treturn fmt.Errorf(\"%q is not a supported image type: %w\", ext, errProvision)\n}", "func (b *mpgBuff) Prepare() {\n\tcap := b.BufferSize()\n\t// ensure capacity is divisible by 4\n\tcap += cap % 4\n\t// make sure we have an even cap value\n\tcap += (cap % 2)\n\t// get individual buffer length\n\tl := cap / 2\n\tb.eof = false\n\t// make and initialize buffers\n\tb.bufA = &concBuff{\n\t\tdata: make([]byte, l)}\n\tb.fill(b.bufA)\n\tb.bufB = &concBuff{\n\t\tdata: make([]byte, l)}\n\tb.fill(b.bufB)\n}", "func (s *PBFTServer) PrePrepare(args PrePrepareArgs, reply *PrePrepareReply) error {\n\t// Verify message signature and digest\n\n\ts.lock.Lock()\n\n\ts.stopTimer()\n\n\tif !s.changing && s.view == args.View && s.h <= args.Seq && args.Seq < s.H {\n\t\tUtil.Dprintf(\"%s[R/PrePrepare]:Args:%+v\", s, args)\n\n\t\tent := s.getEntry(entryID{args.View, args.Seq})\n\t\ts.lock.Unlock()\n\n\t\tent.lock.Lock()\n\t\tif ent.pp == nil || (ent.pp.Digest == args.Digest && ent.pp.Seq == args.Seq) {\n\t\t\tpArgs := PrepareArgs{\n\t\t\t\tView: args.View,\n\t\t\t\tSeq: args.Seq,\n\t\t\t\tDigest: args.Digest,\n\t\t\t\tRid: s.id,\n\t\t\t}\n\t\t\tent.pp = &args\n\n\t\t\tUtil.Dprintf(\"%s[B/Prepare]:Args:%+v\", s, pArgs)\n\n\t\t\ts.broadcast(false, true, \"PBFTServer.Prepare\", pArgs, &PrepareReply{})\n\t\t}\n\t\tent.lock.Unlock()\n\t} else {\n\t\ts.lock.Unlock()\n\t}\n\n\treturn nil\n}", "func (consensus *Consensus) Prepare(chain ChainReader, header *types.Header) error {\n\t// TODO: implement prepare method\n\treturn nil\n}", "func (cs *ChatServer) Updatecapacity() {\n\tcs.capacity = cs.cpus - cs.rooms\n}", "func (client MSIXPackagesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, hostPoolName string, msixPackageFullName string, msixPackage *MSIXPackagePatch) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostPoolName\": autorest.Encode(\"path\", hostPoolName),\n\t\t\"msixPackageFullName\": autorest.Encode(\"path\", msixPackageFullName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-09-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif msixPackage != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(msixPackage))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CertificateOrdersClient) UpdateCertificateOrderPreparer(ctx context.Context, resourceGroupName string, name string, certificateDistinguishedName CertificateOrder) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-08-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{name}\", pathParameters),\n\t\tautorest.WithJSON(certificateDistinguishedName),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (e *engineImpl) Prepare(chain engine.ChainReader, header *block.Header) error {\n\t// TODO: implement prepare method\n\treturn nil\n}", "func (client *DiskEncryptionSetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsBeginUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif diskEncryptionSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter diskEncryptionSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{diskEncryptionSetName}\", url.PathEscape(diskEncryptionSetName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, diskEncryptionSet)\n}", "func (p *preImpl) Prepare(ctx context.Context, s *testing.State) interface{} {\n\tctx, st := timing.Start(ctx, \"prepare_\"+p.name)\n\tdefer st.End()\n\n\tif p.arc != nil {\n\t\tpre, err := func() (interface{}, error) {\n\t\t\tctx, cancel := context.WithTimeout(ctx, resetTimeout)\n\t\t\tdefer cancel()\n\t\t\tctx, st := timing.Start(ctx, \"reset_\"+p.name)\n\t\t\tdefer st.End()\n\t\t\tpkgs, err := p.installedPackages(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to get installed packages\")\n\t\t\t}\n\t\t\tif err := p.checkUsable(ctx, pkgs); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"existing Chrome or ARC connection is unusable\")\n\t\t\t}\n\t\t\tif err := p.resetState(ctx, pkgs); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed resetting existing Chrome or ARC session\")\n\t\t\t}\n\t\t\tif err := p.arc.setLogcatFile(filepath.Join(s.OutDir(), logcatName)); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to update logcat output file\")\n\t\t\t}\n\t\t\treturn PreData{p.cr, p.arc}, nil\n\t\t}()\n\t\tif err == nil {\n\t\t\ts.Log(\"Reusing existing ARC session\")\n\t\t\treturn pre\n\t\t}\n\t\ts.Log(\"Failed to reuse existing ARC session: \", err)\n\t\tlocked = false\n\t\tchrome.Unlock()\n\t\tp.closeInternal(ctx, s)\n\t}\n\n\t// Revert partial initialization.\n\tshouldClose := true\n\tdefer func() {\n\t\tif shouldClose {\n\t\t\tp.closeInternal(ctx, s)\n\t\t}\n\t}()\n\n\tfunc() {\n\t\tctx, cancel := context.WithTimeout(ctx, chrome.LoginTimeout)\n\t\tdefer cancel()\n\t\tvar err error\n\t\tif p.cr, err = chrome.New(ctx, chrome.ARCEnabled()); err != nil {\n\t\t\ts.Fatal(\"Failed to start Chrome: \", err)\n\t\t}\n\t}()\n\n\tfunc() {\n\t\tctx, cancel := context.WithTimeout(ctx, BootTimeout)\n\t\tdefer cancel()\n\t\tvar err error\n\t\tif p.arc, err = New(ctx, s.OutDir()); err != nil {\n\t\t\ts.Fatal(\"Failed to start ARC: \", err)\n\t\t}\n\t\tif p.origInitPID, err = InitPID(); err != nil {\n\t\t\ts.Fatal(\"Failed to get initial init PID: \", err)\n\t\t}\n\t\tif p.origPackages, err = p.installedPackages(ctx); err != nil {\n\t\t\ts.Fatal(\"Failed to list initial packages: \", err)\n\t\t}\n\t}()\n\n\t// Prevent the arc and chrome package's New and Close functions from\n\t// being called while this precondition is active.\n\tlocked = true\n\tchrome.Lock()\n\n\tshouldClose = false\n\treturn PreData{p.cr, p.arc}\n}", "func (client CertificateClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string, parameters CertificateCreateOrUpdateParameters, ifMatch string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"certificateName\": autorest.Encode(\"path\", certificateName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif len(ifMatch) > 0 {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithHeader(\"If-Match\", autorest.String(ifMatch)))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (action *ActionVpsFeatureUpdateAll) Prepare() *ActionVpsFeatureUpdateAllInvocation {\n\treturn &ActionVpsFeatureUpdateAllInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/vpses/{vps_id}/features/update_all\",\n\t}\n}", "func (_RandomBeacon *RandomBeaconSession) UpdateAuthorizationParameters(_minimumAuthorization *big.Int, _authorizationDecreaseDelay uint64, _authorizationDecreaseChangePeriod uint64) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateAuthorizationParameters(&_RandomBeacon.TransactOpts, _minimumAuthorization, _authorizationDecreaseDelay, _authorizationDecreaseChangePeriod)\n}", "func NewContractPrepareCmd(client ioctl.Client) *cobra.Command {\n\tshort, _ := client.SelectTranslation(_prepareCmdShorts)\n\n\treturn &cobra.Command{\n\t\tUse: \"prepare\",\n\t\tShort: short,\n\t\tArgs: cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcmd.SilenceUsage = true\n\t\t\t_, err := util.SolidityVersion(_solCompiler)\n\t\t\tif err != nil {\n\t\t\t\tcmdString := \"curl --silent https://raw.githubusercontent.com/iotexproject/iotex-core/master/install-solc.sh | sh\"\n\t\t\t\tinstallCmd := exec.Command(\"bash\", \"-c\", cmdString)\n\t\t\t\tcmd.Println(\"Preparing solidity compiler ...\")\n\n\t\t\t\terr = installCmd.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"failed to prepare solc\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tsolc, err := util.SolidityVersion(_solCompiler)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"solidity compiler not ready\")\n\t\t\t}\n\t\t\tif !checkCompilerVersion(solc) {\n\t\t\t\treturn errors.Errorf(\"unsupported solc version %d.%d.%d, expects solc version 0.8.17\\n\",\n\t\t\t\t\tsolc.Major, solc.Minor, solc.Patch)\n\t\t\t}\n\n\t\t\tcmd.Println(\"Solidity compiler is ready now.\")\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func (action *ActionMailTemplateTranslationUpdate) Prepare() *ActionMailTemplateTranslationUpdateInvocation {\n\treturn &ActionMailTemplateTranslationUpdateInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/mail_templates/{mail_template_id}/translations/{translation_id}\",\n\t}\n}", "func (_RandomBeacon *RandomBeaconTransactor) UpdateRewardParameters(opts *bind.TransactOpts, sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"updateRewardParameters\", sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func NewUpdateDeviceRequest(d *v1alpha1.Device) *packngo.DeviceUpdateRequest {\n\treturn &packngo.DeviceUpdateRequest{\n\t\tHostname: &d.Spec.ForProvider.Hostname,\n\t\tLocked: &d.Spec.ForProvider.Locked,\n\t\tUserData: &d.Spec.ForProvider.UserData,\n\t\tIPXEScriptURL: &d.Spec.ForProvider.IPXEScriptURL,\n\t\tAlwaysPXE: &d.Spec.ForProvider.AlwaysPXE,\n\t\tTags: &d.Spec.ForProvider.Tags,\n\t}\n}", "func (dl *DrawList) PrimReserve(idxCount, vtxCount int) {\n\tif sz, require := len(dl.VtxBuffer), dl.vtxIndex+vtxCount; require >= sz {\n\t\tvtxBuffer := make([]DrawVert, sz+1024)\n\t\tcopy(vtxBuffer, dl.VtxBuffer)\n\t\tdl.VtxBuffer = vtxBuffer\n\t}\n\tif sz, require := len(dl.IdxBuffer), dl.idxIndex+idxCount; require >= sz {\n\t\tidxBuffer := make([]DrawIdx, sz+1024)\n\t\tcopy(idxBuffer, dl.IdxBuffer)\n\t\tdl.IdxBuffer = idxBuffer\n\t}\n\tdl.VtxWriter = dl.VtxBuffer[dl.vtxIndex:dl.vtxIndex+vtxCount]\n\tdl.IdxWriter = dl.IdxBuffer[dl.idxIndex:dl.idxIndex+idxCount]\n}", "func NewUpdateStatement(keyspace, table string, fieldMap map[string]interface{}, rel []Relation, keys Keys) (UpdateStatement, error) {\n\tstmt := UpdateStatement{}\n\tif keyspace == \"\" || table == \"\" {\n\t\treturn stmt, fmt.Errorf(\"keyspace and table can't be empty\")\n\t}\n\n\tif len(fieldMap) < 1 {\n\t\treturn stmt, fmt.Errorf(\"fieldMap must be a map fields to insert\")\n\t}\n\n\tif len(rel) < 1 {\n\t\treturn stmt, fmt.Errorf(\"must supply at least one relation WHERE clause\")\n\t}\n\n\tif len(keys.PartitionKeys) == 0 {\n\t\treturn stmt, fmt.Errorf(\"partition key should be supplied\")\n\t}\n\n\tstmt.keyspace = keyspace\n\tstmt.table = table\n\tstmt.fieldMap = fieldMap\n\tstmt.where = rel\n\tstmt.keys = keys\n\treturn stmt, nil\n}", "func Prepare(p Preparer, query string) (st *sql.Stmt, err error) {\n\tst, err = p.Prepare(query)\n\terr = interpretError(err)\n\treturn\n}", "func (client *DedicatedHostsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsBeginUpdateOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodPatch, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, req.MarshalAsJSON(parameters)\n}", "func (px *Paxos) Prepare(args *PrepareArgs, reply *PrepareReply) error {\n\tif args.PNum > px.APp[args.Seq] {\n\t\t// prepare request with higher Proposal Number\n\t\tpx.APp[args.Seq] = args.PNum\n\t\treply.Err = OK\n\t\treply.Proposal = px.APa[args.Seq]\n\t} else {\n\t\t// Already promised to Proposal with a higher Proposal Number\n\t\treply.Err = Reject\n\t\treply.Proposal = Proposal{px.APp[args.Seq], nil}\n\t}\n\treturn nil\n}", "func (sc *schedulerCache) addQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v exist\", quotaAllocator.Name)\n\t}\n\n\tinfo := &QuotaAllocatorInfo{\n\t\tname: quotaAllocator.Name,\n\t\tquotaAllocator: quotaAllocator.DeepCopy(),\n\t\tPods: make([]*v1.Pod, 0),\n\t}\n\n\t// init Request if it is nil\n\tif info.QuotaAllocator().Spec.Request.Resources == nil {\n\t\tinfo.QuotaAllocator().Spec.Request.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\n\t// init Deserved/Allocated/Used/Preemping if it is nil\n\tif info.QuotaAllocator().Status.Deserved.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Deserved.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Allocated.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Allocated.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Used.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Used.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Preempting.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Preempting.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tsc.quotaAllocators[quotaAllocator.Name] = info\n\treturn nil\n}", "func (out *OutBuffer) Prepare(size int) {\n\tif out.Data == nil {\n\t\tout.pos = 0\n\t\tout.Data = globalPool.GetOutDataBuffer(size)\n\t}\n\n\tpos := out.pos\n\n\tif cap(out.Data)-pos < size {\n\t\tdata := globalPool.GetOutDataBuffer(pos + size)\n\t\tif out.pos > 0 && len(out.Data) > 0 {\n\t\t\tcopy(data, out.Data[0:out.pos])\n\t\t}\n\t\toldData := out.Data\n\t\tglobalPool.PutOutDataBuffer(oldData)\n\t\tout.Data = data\n\t} else {\n\t\tout.Data = out.Data[0 : pos+size]\n\t}\n}", "func (client ServicesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}\", pathParameters),\n\t\tautorest.WithJSON(resource),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *mockSpdkNvme) Update(pciAddr string, path string, slot int32) (\n\t[]Controller, []Namespace, error) {\n\n\tfor i, ctrlr := range m.initCtrlrs {\n\t\tif ctrlr.PCIAddr == pciAddr && m.updateRet == nil {\n\t\t\tm.initCtrlrs[i].FWRev = m.fwRevAfter\n\t\t}\n\t}\n\n\treturn m.initCtrlrs, m.initNss, m.updateRet\n}", "func Prepare() error {\n\n\t// log.Println(\"Preparing work...\")\n\n\t// commands := [][]string{\n\t// \t[]string{\"yum\", \"update\", \"-y\"},\n\t// \t[]string{\"yum\", \"install\", \"-y\", \"docker\"},\n\t// \t[]string{\"service\", \"docker\", \"start\"},\n\t// \t[]string{\"docker\", \"pull\", \"tnolet/scraper:0.1.0\"},\n\t// }\n\n\t// for _, command := range commands {\n\t// \tout, err := exec.Command(command).Output()\n\n\t// \tif err != nil {\n\t// \t\tlog.Printf(\"Prepare command unsuccessful: %v, %v\", err.Error(), out)\n\t// \t\treturn err\n\t// \t}\n\n\t// \tlog.Printf(\"Succesfully executed preparation: %v\", out)\n\t// }\n\treturn nil\n\n}", "func (h *consulGRPCSocketHook) Update(req *interfaces.RunnerUpdateRequest) error {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.alloc = req.Alloc\n\n\tif !h.shouldRun() {\n\t\treturn nil\n\t}\n\n\treturn h.proxy.run(h.alloc)\n}", "func (db *DB) Prepare(query string) (Stmt, error) {\n\tstmts := make([]*sql.Stmt, len(db.cpdbs))\n\n\terr := scatter(len(db.cpdbs), func(i int) (err error) {\n\t\tstmts[i], err = db.cpdbs[i].db.Prepare(query)\n\t\treturn errors.WithStack(err)\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &stmt{db: db, stmts: stmts}, nil\n}", "func NewUpdateParamsCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"update [change-file]\",\n\t\tShort: \"UpdateValidator params\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclientCtx, err := client.GetClientTxContext(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tchanges, _ := utils.ParseParamChange(clientCtx.LegacyAmino, args[0])\n\n\t\t\tmsg := types.NewMsgUpdateParams(\n\t\t\t\tchanges.ToParamChanges(),\n\t\t\t\tclientCtx.GetFromAddress(),\n\t\t\t)\n\n\t\t\tif err := msg.ValidateBasic(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)\n\t\t},\n\t}\n\n\tflags.AddTxFlagsToCmd(cmd)\n\t_ = cmd.MarkFlagRequired(flags.FlagFrom)\n\n\treturn cmd\n}" ]
[ "0.7424789", "0.5677787", "0.5536896", "0.5494887", "0.53911835", "0.5362883", "0.53093344", "0.52692324", "0.5254965", "0.5247992", "0.51920253", "0.51712793", "0.5147966", "0.5011077", "0.5002912", "0.4989964", "0.48652557", "0.48066962", "0.47724175", "0.47566584", "0.47195667", "0.47023305", "0.4686456", "0.46021235", "0.46005666", "0.45783454", "0.45699158", "0.45429024", "0.45266357", "0.452046", "0.45096803", "0.4509138", "0.4507075", "0.44880393", "0.44823208", "0.44823208", "0.44823208", "0.44729355", "0.44669476", "0.44577768", "0.44483525", "0.44424304", "0.44294766", "0.44243592", "0.44024333", "0.4400741", "0.4397658", "0.43969405", "0.43892333", "0.43837065", "0.43825734", "0.43816105", "0.43787733", "0.43714362", "0.43713537", "0.43708798", "0.43707442", "0.43532276", "0.43426168", "0.4339708", "0.43373013", "0.43317693", "0.4329482", "0.4329482", "0.4329482", "0.4329482", "0.4329482", "0.43235755", "0.43149957", "0.43121323", "0.43049544", "0.43031088", "0.4302492", "0.43009222", "0.42973953", "0.42952096", "0.42874128", "0.42853817", "0.42790735", "0.42787963", "0.42745325", "0.42728996", "0.4272612", "0.42704937", "0.42694998", "0.42590466", "0.42545283", "0.4252241", "0.425063", "0.42466584", "0.42354137", "0.42345986", "0.42326608", "0.42324015", "0.42247424", "0.4223482", "0.42216295", "0.42214578", "0.42181906", "0.42166966" ]
0.75170195
0
PrepareDelete reserves an allocator and uses it to prepare a delete operation. See Allocator.PrepareDelete for details
PrepareDelete выделяет аллоциатор и использует его для подготовки операции удаления. См. Allocator.PrepareDelete для деталей
func (idx *Tree) PrepareDelete(key []byte) (found bool, op *DeleteOperation) { id := idx.allocatorQueue.get() op = newDeleteOperation(idx, idx.allocators[id], true) if op.prepare(key) { return true, op } op.Abort() return false, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client Client) DeletePreparer(resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": url.QueryEscape(name),\n\t\t\"resourceGroupName\": url.QueryEscape(resourceGroupName),\n\t\t\"subscriptionId\": url.QueryEscape(client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}\"),\n\t\tautorest.WithPathParameters(pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n}", "func (client MeshNetworkClient) DeletePreparer(ctx context.Context, networkResourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"networkResourceName\": networkResourceName,\n\t}\n\n\tconst APIVersion = \"6.4-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/Resources/Networks/{networkResourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AccountClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (vfs *VirtualFilesystem) PrepareDeleteDentry(mntns *MountNamespace, d *Dentry) error {\n\tif checkInvariants {\n\t\tif d.parent == nil {\n\t\t\tpanic(\"d is independent\")\n\t\t}\n\t\tif d.IsDisowned() {\n\t\t\tpanic(\"d is already disowned\")\n\t\t}\n\t}\n\tvfs.mountMu.Lock()\n\tif mntns.mountpoints[d] != 0 {\n\t\tvfs.mountMu.Unlock()\n\t\treturn syserror.EBUSY\n\t}\n\td.mu.Lock()\n\tvfs.mountMu.Unlock()\n\t// Return with d.mu locked to block attempts to mount over it; it will be\n\t// unlocked by AbortDeleteDentry or CommitDeleteDentry.\n\treturn nil\n}", "func (client CertificateClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"certificateName\": autorest.Encode(\"path\", certificateName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *CassandraClustersClient) deallocateCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *CassandraClustersClientBeginDeallocateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/deallocate\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func MakeDeleter(\n\tcodec keys.SQLCodec, tableDesc catalog.TableDescriptor, requestedCols []descpb.ColumnDescriptor,\n) Deleter {\n\tindexes := tableDesc.DeletableNonPrimaryIndexes()\n\tindexDescs := make([]descpb.IndexDescriptor, len(indexes))\n\tfor i, index := range indexes {\n\t\tindexDescs[i] = *index.IndexDesc()\n\t}\n\n\tvar fetchCols []descpb.ColumnDescriptor\n\tvar fetchColIDtoRowIndex catalog.TableColMap\n\tif requestedCols != nil {\n\t\tfetchCols = requestedCols[:len(requestedCols):len(requestedCols)]\n\t\tfetchColIDtoRowIndex = ColIDtoRowIndexFromCols(fetchCols)\n\t} else {\n\t\tmaybeAddCol := func(colID descpb.ColumnID) error {\n\t\t\tif _, ok := fetchColIDtoRowIndex.Get(colID); !ok {\n\t\t\t\tcol, err := tableDesc.FindColumnWithID(colID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfetchColIDtoRowIndex.Set(col.GetID(), len(fetchCols))\n\t\t\t\tfetchCols = append(fetchCols, *col.ColumnDesc())\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tfor j := 0; j < tableDesc.GetPrimaryIndex().NumColumns(); j++ {\n\t\t\tcolID := tableDesc.GetPrimaryIndex().GetColumnID(j)\n\t\t\tif err := maybeAddCol(colID); err != nil {\n\t\t\t\treturn Deleter{}\n\t\t\t}\n\t\t}\n\t\tfor _, index := range indexes {\n\t\t\tfor j := 0; j < index.NumColumns(); j++ {\n\t\t\t\tcolID := index.GetColumnID(j)\n\t\t\t\tif err := maybeAddCol(colID); err != nil {\n\t\t\t\t\treturn Deleter{}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// The extra columns are needed to fix #14601.\n\t\t\tfor j := 0; j < index.NumExtraColumns(); j++ {\n\t\t\t\tcolID := index.GetExtraColumnID(j)\n\t\t\t\tif err := maybeAddCol(colID); err != nil {\n\t\t\t\t\treturn Deleter{}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\trd := Deleter{\n\t\tHelper: newRowHelper(codec, tableDesc, indexDescs),\n\t\tFetchCols: fetchCols,\n\t\tFetchColIDtoRowIndex: fetchColIDtoRowIndex,\n\t}\n\n\treturn rd\n}", "func (client OpenShiftManagedClustersClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": v20180930preview.APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/openShiftManagedClusters/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client GroupClient) DeleteSecretPreparer(accountName string, databaseName string, secretName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"secretName\": autorest.Encode(\"path\", secretName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/secrets/{secretName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func prepareDeletecluster(params map[string]string, clusterName string, Region string) {\n\tif clusterName != \"\" {\n\t\tparams[\"clusterName\"] = clusterName\n\t}\n\tif Region != \"\" {\n\t\tparams[\"Region\"] = Region\n\t}\n\tparams[\"amztarget\"] = \"AmazonEC2ContainerServiceV20141113.DeleteCluster\"\n}", "func (oo *OmciCC) PrepareForGarbageCollection(ctx context.Context, aDeviceID string) {\n\tlogger.Debugw(ctx, \"prepare for garbage collection\", log.Fields{\"device-id\": aDeviceID})\n\too.pBaseDeviceHandler = nil\n\too.pOnuDeviceEntry = nil\n\too.pOnuAlarmManager = nil\n}", "func (client DeploymentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client StorageTargetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, cacheName string, storageTargetName string, force string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"cacheName\": autorest.Encode(\"path\", cacheName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"storageTargetName\": autorest.Encode(\"path\", storageTargetName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-09-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(force) > 0 {\n\t\tqueryParameters[\"force\"] = autorest.Encode(\"query\", force)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StorageCache/caches/{cacheName}/storageTargets/{storageTargetName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ThreatIntelligenceIndicatorClient) DeletePreparer(ctx context.Context, resourceGroupName string, workspaceName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"workspaceName\": autorest.Encode(\"path\", workspaceName),\n\t}\n\n\tconst APIVersion = \"2022-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func preparedeleteserviceparams(params map[string]string, deleteservice Deleteservice, Region string) {\n\tif Region != \"\" {\n\t\tparams[\"Region\"] = Region\n\t}\n\tparams[\"amztarget\"] = \"AmazonEC2ContainerServiceV20141113.DeleteService\"\n}", "func (client HTTPSuccessClient) Delete202Preparer(booleanValue *bool) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/http/success/202\"))\n if booleanValue != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(booleanValue))\n }\n return preparer.Prepare(&http.Request{})\n}", "func (c SqlDedicatedGatewayClient) preparerForServiceDelete(ctx context.Context, id ServiceId) (*http.Request, error) {\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": defaultApiVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(c.baseUri),\n\t\tautorest.WithPath(id.ID()),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DatasetClient) DeletePreparer(ctx context.Context, datasetID string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"datasetId\": autorest.Encode(\"path\",datasetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/datasets/{datasetId}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (idx *Tree) PrepareUpdate(key []byte) (found bool, op *UpdateOperation) {\n\tid := idx.allocatorQueue.get()\n\top = newUpdateOperation(idx, idx.allocators[id], true)\n\treturn op.prepareUpdate(key), op\n}", "func (client DatabasesClient) DeletePreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serverName\": autorest.Encode(\"path\", serverName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2014-04-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (oo *OnuDeviceEntry) PrepareForGarbageCollection(ctx context.Context, aDeviceID string) {\n\tlogger.Debugw(ctx, \"prepare for garbage collection\", log.Fields{\"device-id\": aDeviceID})\n\too.baseDeviceHandler = nil\n\too.pOnuTP = nil\n\tif oo.PDevOmciCC != nil {\n\t\too.PDevOmciCC.PrepareForGarbageCollection(ctx, aDeviceID)\n\t}\n\too.PDevOmciCC = nil\n}", "func (client ReferenceDataSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, environmentName string, referenceDataSetName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"environmentName\": autorest.Encode(\"path\", environmentName),\n\t\t\"referenceDataSetName\": autorest.Encode(\"path\", referenceDataSetName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-05-15\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client VersionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, templateSpecName string, templateSpecVersion string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"templateSpecName\": autorest.Encode(\"path\", templateSpecName),\n\t\t\"templateSpecVersion\": autorest.Encode(\"path\", templateSpecVersion),\n\t}\n\n\tconst APIVersion = \"2019-06-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Resources/templateSpecs/{templateSpecName}/versions/{templateSpecVersion}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CloudEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"cloudEndpointName\": autorest.Encode(\"path\", cloudEndpointName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"storageSyncServiceName\": autorest.Encode(\"path\", storageSyncServiceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"syncGroupName\": autorest.Encode(\"path\", syncGroupName),\n\t}\n\n\tconst APIVersion = \"2020-03-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}/cloudEndpoints/{cloudEndpointName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c *Conn) Deallocate(ctx context.Context, name string) error {\n\tdelete(c.preparedStatements, name)\n\t_, err := c.pgConn.Exec(ctx, \"deallocate \"+quoteIdentifier(name)).ReadAll()\n\treturn err\n}", "func (client MSIXPackagesClient) DeletePreparer(ctx context.Context, resourceGroupName string, hostPoolName string, msixPackageFullName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostPoolName\": autorest.Encode(\"path\", hostPoolName),\n\t\t\"msixPackageFullName\": autorest.Encode(\"path\", msixPackageFullName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-09-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ViewsClient) DeletePreparer(ctx context.Context, viewName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2019-11-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.CostManagement/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *CapacityReservationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif capacityReservationGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationGroupName}\", url.PathEscape(capacityReservationGroupName))\n\tif capacityReservationName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationName}\", url.PathEscape(capacityReservationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client JobClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, jobName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"jobName\": jobName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs/{jobName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client IotHubResourceClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-04-30-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) DeletePreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CertificateOrdersClient) DeleteCertificateOrderPreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-08-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CertificateOrdersClient) DeleteCertificatePreparer(ctx context.Context, resourceGroupName string, certificateOrderName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"certificateOrderName\": autorest.Encode(\"path\", certificateOrderName),\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-08-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{certificateOrderName}/certificates/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func TestAllocRunner_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\n\t// Ensure task takes some time\n\talloc := mock.BatchAlloc()\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Config[\"run_for\"] = \"10s\"\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\n\t// Use a MemDB to assert alloc state gets cleaned up\n\tconf.StateDB = state.NewMemDB(conf.Logger)\n\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tgo ar.Run()\n\n\t// Wait for alloc to be running\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tstate := ar.AllocState()\n\n\t\treturn state.ClientStatus == structs.AllocClientStatusRunning,\n\t\t\tfmt.Errorf(\"got client status %v; want running\", state.ClientStatus)\n\t}, func(err error) {\n\t\trequire.NoError(t, err)\n\t})\n\n\t// Assert state was stored\n\tls, ts, err := conf.StateDB.GetTaskRunnerState(alloc.ID, task.Name)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ls)\n\trequire.NotNil(t, ts)\n\n\t// Now destroy\n\tar.Destroy()\n\n\tselect {\n\tcase <-ar.DestroyCh():\n\t\t// Destroyed properly!\n\tcase <-time.After(10 * time.Second):\n\t\trequire.Fail(t, \"timed out waiting for alloc to be destroyed\")\n\t}\n\n\t// Assert alloc is dead\n\tstate := ar.AllocState()\n\trequire.Equal(t, structs.AllocClientStatusComplete, state.ClientStatus)\n\n\t// Assert the state was cleaned\n\tls, ts, err = conf.StateDB.GetTaskRunnerState(alloc.ID, task.Name)\n\trequire.NoError(t, err)\n\trequire.Nil(t, ls)\n\trequire.Nil(t, ts)\n\n\t// Assert the alloc directory was cleaned\n\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\trequire.Fail(t, \"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t} else if !os.IsNotExist(err) {\n\t\trequire.Failf(t, \"expected NotExist error\", \"found %v\", err)\n\t}\n}", "func (client PublishedBlueprintsClient) DeletePreparer(ctx context.Context, resourceScope string, blueprintName string, versionID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"blueprintName\": autorest.Encode(\"path\", blueprintName),\n\t\t\"resourceScope\": resourceScope,\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tconst APIVersion = \"2018-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/versions/{versionId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client WorkloadNetworksClient) DeleteSegmentPreparer(ctx context.Context, resourceGroupName string, privateCloudName string, segmentID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"privateCloudName\": autorest.Encode(\"path\", privateCloudName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"segmentId\": autorest.Encode(\"path\", segmentID),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-07-17-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/workloadNetworks/default/segments/{segmentId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c *AgonesDiscoverAllocator) Allocate(ctx context.Context, req *pb.AssignTicketsRequest) error {\n\tlogger := runtime.Logger().WithField(\"component\", \"allocator\")\n\n\tfor _, assignmentGroup := range req.Assignments {\n\t\tif err := IsAssignmentGroupValidForAllocation(assignmentGroup); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfilter, err := extensions.ExtractFilterFromExtensions(assignmentGroup.Assignment.Extensions)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"the assignment does not have a valid filter extension\")\n\t\t}\n\n\t\tgameservers, err := c.ListGameServers(ctx, filter)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif len(gameservers) == 0 {\n\t\t\tlogger.Debugf(\"gameservers not found for request with filter %v\", filter.Map())\n\t\t\tcontinue\n\t\t}\n\n\t\t// NiceToHave: Filter GameServers by Capacity and Count\n\t\t// Remove not assigned tickets based on playersCapacity - Count\n\t\t// strategy: allTogether, CapacityBased FallBack\n\t\tfor _, gs := range gameservers {\n\t\t\tif HasCapacity(assignmentGroup, gs) {\n\t\t\t\tassignmentGroup.Assignment.Connection = gs.Status.Address\n\t\t\t\t//logger.Debugf(\"extension %v\", assignmentGroup.Assignment.Extensions)\n\t\t\t\tlogger.Infof(\"gameserver %s connection %s assigned to request, total tickets: %d\", gs.Name, assignmentGroup.Assignment.Connection, len(assignmentGroup.TicketIds))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (sc *schedulerCache) deleteQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; !ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v doesn't exist\", quotaAllocator.Name)\n\t}\n\tdelete(sc.quotaAllocators, quotaAllocator.Name)\n\treturn nil\n}", "func (client CertificateClient) CancelDeletionPreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"certificateName\": autorest.Encode(\"path\", certificateName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client FirewallPolicyRuleGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleGroupName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"firewallPolicyName\": autorest.Encode(\"path\", firewallPolicyName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"ruleGroupName\": autorest.Encode(\"path\", ruleGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleGroups/{ruleGroupName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeviceClient) DeletePreparer(ctx context.Context, serviceID string, userID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"serviceId\": serviceID,\n\t\t\"userId\": autorest.Encode(\"path\", userID),\n\t}\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"DELETE\", common.GetPathParameters(DefaultBaseURI, \"/push/v2/services/{serviceId}/users/{userId}\", pathParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/push/v2/services/{serviceId}/users/{userId}\", pathParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-api-key\", client.APIGatewayAPIKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (n *SQSNotify) ReserveDelete(m *SQSMessage) {\n\tn.addDeleteQueue(m)\n\t// flush to delete ASAP when the queue beyond max delete messages.\n\tif n.dqID.Len() >= maxDelete {\n\t\t_ = n.flushDeleteQueue()\n\t}\n}", "func (client *DiskEncryptionSetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif diskEncryptionSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter diskEncryptionSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{diskEncryptionSetName}\", url.PathEscape(diskEncryptionSetName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func PrepareForDeleteUser(roundTripper *mhttp.MockRoundTripper, rootURL, userName, user, passwd string) (\n\tresponse *http.Response) {\n\trequest, _ := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s/securityRealm/user/%s/doDelete\", rootURL, userName), nil)\n\trequest.Header.Add(httpdownloader.ContentType, httpdownloader.ApplicationForm)\n\tresponse = PrepareCommonPost(request, \"\", roundTripper, user, passwd, rootURL)\n\treturn\n}", "func (p *MemoryProposer) RemovePreparer(target Acceptor) error {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif _, ok := p.preparers[target.Address()]; !ok {\n\t\treturn ErrNotFound\n\t}\n\tdelete(p.preparers, target.Address())\n\treturn nil\n}", "func (client HTTPSuccessClient) Delete204Preparer(booleanValue *bool) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/http/success/204\"))\n if booleanValue != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(booleanValue))\n }\n return preparer.Prepare(&http.Request{})\n}", "func (client ScheduleMessageClient) DeletePreparer(ctx context.Context, serviceID string, scheduleCode string, messageID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"messageId\": autorest.Encode(\"path\", messageID),\n\t\t\"scheduleCode\": autorest.Encode(\"path\", scheduleCode),\n\t\t\"serviceId\": serviceID,\n\t}\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"DELETE\", common.GetPathParameters(DefaultBaseURI, \"/push/v2/services/{serviceId}/schedules/{scheduleCode}/messages/{messageId}\", pathParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/push/v2/services/{serviceId}/schedules/{scheduleCode}/messages/{messageId}\", pathParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-api-key\", client.APIGatewayAPIKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (a *Acceptor) DeliverPrepare(prp Prepare) {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.prepareChan <- prp\n}", "func (a *Acceptor) DeliverPrepare(prp Prepare) {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.prepareChan <- prp\n}", "func (client IngestionSettingsClient) DeletePreparer(ctx context.Context, ingestionSettingName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"ingestionSettingName\": autorest.Encode(\"path\", ingestionSettingName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-01-15-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Security/ingestionSettings/{ingestionSettingName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (idx *Tree) ReleaseAllocator(a *Allocator) {\n\tidx.allocatorQueue.put(a.id)\n}", "func (m *RdmaDevPlugin) Allocate(ctx context.Context, r *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error) {\n\tlog.Println(\"allocate request:\", r)\n\n\tress := make([]*pluginapi.ContainerAllocateResponse, len(r.GetContainerRequests()))\n\n\tfor i := range r.GetContainerRequests() {\n\t\tress[i] = &pluginapi.ContainerAllocateResponse{\n\t\t\tDevices: m.deviceSpec,\n\t\t}\n\t}\n\n\tresponse := pluginapi.AllocateResponse{\n\t\tContainerResponses: ress,\n\t}\n\n\tlog.Println(\"allocate response: \", response)\n\treturn &response, nil\n}", "func (client *CapacitiesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, dedicatedCapacityName string, options *CapacitiesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif dedicatedCapacityName == \"\" {\n\t\treturn nil, errors.New(\"parameter dedicatedCapacityName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{dedicatedCapacityName}\", url.PathEscape(dedicatedCapacityName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-01-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client BaseClient) DeleteExpectationPreparer(ctx context.Context, pathParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"path\": autorest.Encode(\"path\", pathParameter),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/api/expectations/{path}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *PacketCoreDataPlanesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, packetCoreControlPlaneName string, packetCoreDataPlaneName string, options *PacketCoreDataPlanesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MobileNetwork/packetCoreControlPlanes/{packetCoreControlPlaneName}/packetCoreDataPlanes/{packetCoreDataPlaneName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif packetCoreControlPlaneName == \"\" {\n\t\treturn nil, errors.New(\"parameter packetCoreControlPlaneName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{packetCoreControlPlaneName}\", url.PathEscape(packetCoreControlPlaneName))\n\tif packetCoreDataPlaneName == \"\" {\n\t\treturn nil, errors.New(\"parameter packetCoreDataPlaneName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{packetCoreDataPlaneName}\", url.PathEscape(packetCoreDataPlaneName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (na *cnmNetworkAllocator) Deallocate(n *api.Network) error {\n\tlocalNet := na.getNetwork(n.ID)\n\tif localNet == nil {\n\t\treturn fmt.Errorf(\"could not get networker state for network %s\", n.ID)\n\t}\n\n\t// No swarm-level resource deallocation needed for node-local networks\n\tif localNet.isNodeLocal {\n\t\tdelete(na.networks, n.ID)\n\t\treturn nil\n\t}\n\n\tif err := na.freeDriverState(n); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to free driver state for network %s\", n.ID)\n\t}\n\n\tdelete(na.networks, n.ID)\n\n\treturn na.freePools(n, localNet.pools)\n}", "func (client RosettaNetProcessConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, rosettaNetProcessConfigurationName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"integrationAccountName\": autorest.Encode(\"path\", integrationAccountName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"rosettaNetProcessConfigurationName\": autorest.Encode(\"path\", rosettaNetProcessConfigurationName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2016-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/rosettanetprocessconfigurations/{rosettaNetProcessConfigurationName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client BaseClient) DeleteSystemPreparer(ctx context.Context, pathParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"path\": autorest.Encode(\"path\", pathParameter),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/api/systems/{path}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client BaseClient) DeleteSubscriptionPreparer(ctx context.Context, subscriptionID uuid.UUID, APIVersion string, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"subscriptionId\": autorest.Encode(\"path\",subscriptionID),\n }\n\n queryParameters := map[string]interface{} {\n \"ApiVersion\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPathParameters(\"/{subscriptionId}\",pathParameters),\n autorest.WithQueryParameters(queryParameters),\n autorest.WithHeader(\"Content-Type\", \"application/json\"))\n if xMsRequestid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-requestid\",autorest.String(xMsRequestid)))\n }\n if xMsCorrelationid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-correlationid\",autorest.String(xMsCorrelationid)))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client HTTPSuccessClient) Delete200Preparer(booleanValue *bool) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/http/success/200\"))\n if booleanValue != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(booleanValue))\n }\n return preparer.Prepare(&http.Request{})\n}", "func (client LabClient) DeleteResourcePreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-05-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (t *Table) PrepareUpdate(tu fibdef.Update) (*UpdateCommand, error) {\n\tu := &UpdateCommand{}\n\tu.real.RealUpdate = tu.Real()\n\tu.virt.VirtUpdate = tu.Virt()\n\n\tu.allocSplit = u.real.prepare(t)\n\tu.allocated = make([]*Entry, u.allocSplit+u.virt.prepare(t))\n\tif e := t.allocBulk(u.allocated); e != nil {\n\t\treturn nil, e\n\t}\n\n\treturn u, nil\n}", "func (client DeletedCertificateListResult) DeletedCertificateListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif hostGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\tif hostName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (p AzurePKEClusterCreationParamsPreparer) Prepare(ctx context.Context, params *AzurePKEClusterCreationParams) error {\n\tif params.Name == \"\" {\n\t\treturn validationErrorf(\"Name cannot be empty\")\n\t}\n\tif params.OrganizationID == 0 {\n\t\treturn validationErrorf(\"OrganizationID cannot be 0\")\n\t}\n\t// TODO check org exists\n\t// TODO check creator user exists if present\n\tif params.SecretID == \"\" {\n\t\treturn validationErrorf(\"SecretID cannot be empty\")\n\t}\n\t// TODO validate secret ID\n\t// TODO validate SSH secret ID if present\n\n\tif params.ResourceGroup == \"\" {\n\t\tparams.ResourceGroup = fmt.Sprintf(\"%s-rg\", params.Name)\n\t\tp.logger.Debugf(\"ResourceGroup not specified, defaulting to [%s]\", params.ResourceGroup)\n\t}\n\n\tif err := p.k8sPreparer.Prepare(&params.Kubernetes); err != nil {\n\t\treturn emperror.Wrap(err, \"failed to prepare k8s network\")\n\t}\n\n\tsir, err := secret.Store.Get(params.OrganizationID, params.SecretID)\n\tif err != nil {\n\t\treturn emperror.Wrap(err, \"failed to fetch secret from store\")\n\t}\n\tcc, err := azure.NewCloudConnection(&autoazure.PublicCloud, azure.NewCredentials(sir.Values))\n\tif err != nil {\n\t\treturn emperror.Wrap(err, \"failed to create Azure cloud connection\")\n\t}\n\tif err := p.getVNetPreparer(cc, params.Name, params.ResourceGroup).Prepare(ctx, &params.Network); err != nil {\n\t\treturn emperror.Wrap(err, \"failed to prepare cluster network\")\n\t}\n\n\tif err := p.nodePoolsPreparer.Prepare(params.NodePools); err != nil {\n\t\treturn emperror.Wrap(err, \"failed to prepare node pools\")\n\t}\n\n\treturn nil\n}", "func (connection *Connection) CreateMapDeleteRequest(param ...interface{}) (request *DeleteRequest, err error) {\n\tt := reflect.TypeOf(param[0])\n\tswitch t.Kind() {\n\tcase reflect.Ptr, reflect.Struct:\n\t\tif connection.repository == nil {\n\t\t\tif connection.adabasMap != nil && connection.adabasMap.Name == inmapMapName {\n\t\t\t\t// Lock this Adabas Map for ReadRequest creation process of dynamic part\n\t\t\t\tconnection.adabasMap.lock.Lock()\n\t\t\t\tdefer connection.adabasMap.lock.Unlock()\n\t\t\t\tadatypes.Central.Log.Debugf(\"InMap used: %s\", connection.adabasMap.Name)\n\t\t\t\terr = connection.adabasMap.defineByInterface(param[0])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\trequest, err = NewMapDeleteRequest(connection.adabasToData, connection.adabasMap)\n\t\t\t} else {\n\t\t\t\tadatypes.Central.Log.Debugf(\"No repository used: %#v\", connection.adabasToMap)\n\t\t\t\trequest, err = NewMapNameDeleteRequest(connection.adabasToMap, evaluateInterface(param[0]))\n\t\t\t}\n\t\t} else {\n\t\t\tadatypes.Central.Log.Debugf(\"With repository used: %#v\", connection.adabasMap)\n\t\t\trequest, err = NewMapNameDeleteRequestRepo(evaluateInterface(param[0]), connection.adabasToMap, connection.repository)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif len(param) > 1 {\n\t\t\tswitch t := param[1].(type) {\n\t\t\tcase int:\n\t\t\t\tconnection.fnr = Fnr(t)\n\t\t\t\trequest.repository.Fnr = Fnr(t)\n\t\t\tcase Fnr:\n\t\t\t\tconnection.fnr = t\n\t\t\t\trequest.repository.Fnr = t\n\t\t\t}\n\t\t} else {\n\t\t\tconnection.fnr = request.adabasMap.Data.Fnr\n\t\t}\n\t\tconnection.adabasMap = request.adabasMap\n\tcase reflect.String:\n\t\tmapName := param[0].(string)\n\t\terr = connection.prepareMapUsage(mapName)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t// if connection.repository == nil {\n\t\t// \terr = adatypes.NewGenericError(9)\n\t\t// \treturn\n\t\t// }\n\t\t// connection.repository.SearchMapInRepository(connection.adabasToMap, mapName)\n\t\tif connection.adabasMap == nil {\n\t\t\terr = adatypes.NewGenericError(8, mapName)\n\t\t\treturn\n\t\t}\n\t\tconnection.adabasToData = connection.ID.getAdabas(connection.adabasMap.URL())\n\t\t// NewAdabas(connection.adabasMap.URL(), connection.ID)\n\t\t// if err != nil {\n\t\t// \treturn\n\t\t// }\n\t\tconnection.fnr = connection.adabasMap.Data.Fnr\n\t\tadatypes.Central.Log.Debugf(\"Connection FNR=%d, Map referenced : %#v\", connection.fnr, connection.adabasMap)\n\t\trequest, err = NewMapDeleteRequest(connection.adabasToData, connection.adabasMap)\n\t}\n\treturn\n}", "func (client Client) DeletePreparer(ctx context.Context, nasVolumeInstanceNoListN string) (*http.Request, error) {\n\tqueryParameters := map[string]interface{}{\n\t\t\"nasVolumeInstanceNoList.N\": autorest.Encode(\"query\", nasVolumeInstanceNoListN),\n\t\t\"responseFormatType\": autorest.Encode(\"query\", \"json\"),\n\t}\n\n\tqueryParameters[\"regionCode\"] = autorest.Encode(\"query\", \"FKR\")\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"POST\", common.GetPath(DefaultBaseURI, \"/deleteNasVolumeInstances\")+\"?\"+common.GetQuery(queryParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/deleteNasVolumeInstances\"),\n\t\tautorest.WithQueryParameters(queryParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c *Inventory) PrepareDeletableObjects() error {\n\tvar deleteObjects []runtime.Object\n\n\tcurrentObjects := c.inventoryData.CurrentObjects\n\tfor _, currentObject := range currentObjects {\n\t\tmetaobj, err := meta.Accessor(currentObject)\n\t\tif err != nil {\n\t\t\treturn errors.WrapIfWithDetails(err,\n\t\t\t\t\"could not access object metadata\",\n\t\t\t\t\"gvk\", currentObject.GetObjectKind().GroupVersionKind().String())\n\t\t}\n\n\t\tisClusterScoped, err := c.IsClusterScoped(currentObject)\n\t\tif err != nil {\n\t\t\tc.log.Error(err, \"scope check failed, unable to determine whether object is eligible for deletion\")\n\t\t\tcontinue\n\t\t}\n\t\t// check if current object still exists\n\t\tif !isClusterScoped && metaobj.GetNamespace() == \"\" {\n\t\t\tc.log.Info(\"object namespace is unknown, unable to determine whether is eligible for deletion\", \"gvk\", currentObject.GetObjectKind().GroupVersionKind().String(), \"name\", metaobj.GetName())\n\t\t\tcontinue\n\t\t}\n\t\terr = c.genericClient.Get(context.TODO(), types.NamespacedName{Namespace: metaobj.GetNamespace(), Name: metaobj.GetName()}, currentObject.(client.Object))\n\t\tif err != nil && !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) {\n\t\t\treturn errors.WrapIfWithDetails(err,\n\t\t\t\t\"could not verify if object exists\",\n\t\t\t\t\"namespace\", metaobj.GetNamespace(), \"objectName\", metaobj.GetName())\n\t\t}\n\n\t\tcurrentObjGVK := currentObject.GetObjectKind().GroupVersionKind()\n\n\t\tif metaobj.GetDeletionTimestamp() != nil || currentObjGVK.Kind == CustomResourceDefinition || currentObjGVK.Kind == Namespace {\n\t\t\tcontinue\n\t\t}\n\n\t\tdesiredObjects := c.inventoryData.DesiredObjects\n\t\tfound := false\n\n\t\tfor _, desiredObject := range desiredObjects {\n\t\t\tdesiredObjGVK := desiredObject.GetObjectKind().GroupVersionKind()\n\t\t\tdesiredObjMeta, _ := meta.Accessor(desiredObject)\n\n\t\t\tif currentObjGVK.Group == desiredObjGVK.Group &&\n\t\t\t\tcurrentObjGVK.Version == desiredObjGVK.Version &&\n\t\t\t\tcurrentObjGVK.Kind == desiredObjGVK.Kind &&\n\t\t\t\tmetaobj.GetNamespace() == desiredObjMeta.GetNamespace() &&\n\t\t\t\tmetaobj.GetName() == desiredObjMeta.GetName() {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tc.log.Info(\"object eligible for delete\", \"gvk\", currentObjGVK.String(), \"namespace\", metaobj.GetNamespace(), \"name\", metaobj.GetName())\n\t\t\tdeleteObjects = append(deleteObjects, currentObject)\n\t\t}\n\t}\n\n\tc.inventoryData.ObjectsToDelete = deleteObjects\n\treturn nil\n}", "func (client AppsClient) DeletePreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *VirtualMachineScaleSetsClient) deallocateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsBeginDeallocateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif vmScaleSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter vmScaleSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{vmScaleSetName}\", url.PathEscape(vmScaleSetName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\tif options != nil && options.VMInstanceIDs != nil {\n\t\treturn req, runtime.MarshalAsJSON(req, *options.VMInstanceIDs)\n\t}\n\treturn req, nil\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (client DataControllersClient) DeleteDataControllerPreparer(ctx context.Context, resourceGroupName string, dataControllerName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"dataControllerName\": autorest.Encode(\"path\", dataControllerName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-07-24-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureData/dataControllers/{dataControllerName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *IPAllocationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif ipAllocationName == \"\" {\n\t\treturn nil, errors.New(\"parameter ipAllocationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ipAllocationName}\", url.PathEscape(ipAllocationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (allocator *Allocator) ReleaseAllocator() {\n\tC.zj_AllocatorRelease(allocator.A)\n}", "func (client *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treturn req, nil\n}", "func (client DeletedSecretListResult) DeletedSecretListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func PrepareTape(hDevice HANDLE, dwOperation DWORD, bImmediate bool) DWORD {\n\tret1 := syscall3(prepareTape, 3,\n\t\tuintptr(hDevice),\n\t\tuintptr(dwOperation),\n\t\tgetUintptrFromBool(bImmediate))\n\treturn DWORD(ret1)\n}", "func (client ListManagementTermListsClient) DeletePreparer(ctx context.Context, listID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"listId\": autorest.Encode(\"path\", listID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/contentmoderator/lists/v1.0/termlists/{listId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, kubernetesClusterName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkCloud/kubernetesClusters/{kubernetesClusterName}/agentPools/{agentPoolName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif kubernetesClusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter kubernetesClusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{kubernetesClusterName}\", url.PathEscape(kubernetesClusterName))\n\tif agentPoolName == \"\" {\n\t\treturn nil, errors.New(\"parameter agentPoolName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{agentPoolName}\", url.PathEscape(agentPoolName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (p *Preparer) Prepare(fullInfo chan resource.Resource, done chan bool, mapWg *sync.WaitGroup) {\n\tmapWg.Wait()\n\n\tvar wg sync.WaitGroup\n\n\tidentifierSend := false\n\n\tfor data := range fullInfo {\n\t\tif !identifierSend {\n\t\t\terr := p.prep.SendIdentifier()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"error\": err}).Fatal(\"error send identifier\")\n\t\t\t}\n\t\t\tidentifierSend = true\n\t\t}\n\t\twg.Add(1)\n\t\tgo p.prep.Preparation(data, &wg)\n\t}\n\n\twg.Wait()\n\n\t// If the identifier was not sent, there is no resource to prepare and send,\n\t// a gRPC connection was not open and no finishing and closing of a connection are needed.\n\tif identifierSend {\n\t\tp.prep.Finish()\n\t}\n\n\tdone <- true\n}", "func (client PatternClient) DeletePatternPreparer(ctx context.Context, appID uuid.UUID, versionID string, patternID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"patternId\": autorest.Encode(\"path\", patternID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternrules/{patternId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (p VspherePKEClusterCreationParamsPreparer) Prepare(ctx context.Context, params *VspherePKEClusterCreationParams) error {\n\tif params.Name == \"\" {\n\t\treturn validationErrorf(\"Name cannot be empty\")\n\t}\n\tif params.OrganizationID == 0 {\n\t\treturn validationErrorf(\"OrganizationID cannot be 0\")\n\t}\n\n\t_, err := auth.GetOrganizationById(params.OrganizationID)\n\tif err != nil {\n\t\treturn validationErrorf(\"OrganizationID cannot be found %s\", err.Error())\n\t}\n\n\t// validate secretID\n\tif params.SecretID == \"\" {\n\t\treturn validationErrorf(\"SecretID cannot be empty\")\n\t}\n\tif err := p.verifySecretIsOfType(params.OrganizationID, params.SecretID, secrettype.Vsphere); err != nil {\n\t\treturn err\n\t}\n\n\t// validate storageSecretID if present\n\tif err := p.verifySecretIsOfType(params.OrganizationID, params.StorageSecretID, secrettype.Vsphere); err != nil {\n\t\treturn err\n\t}\n\n\t// validate SSH secret ID if present\n\tif err := p.verifySecretIsOfType(params.OrganizationID, params.SSHSecretID, secrettype.SSHSecretType); err != nil {\n\t\treturn err\n\t}\n\n\tif err := p.k8sPreparer.Prepare(&params.Kubernetes); err != nil {\n\t\treturn errors.WrapIf(err, \"failed to prepare k8s network\")\n\t}\n\n\tif err := p.getNodePoolsPreparer(clusterCreatorNodePoolPreparerDataProvider{}).Prepare(ctx, params.NodePools); err != nil {\n\t\treturn errors.WrapIf(err, \"failed to prepare node pools\")\n\t}\n\n\treturn nil\n}", "func (l *blocksLRU) prepareForAdd() {\n\tswitch {\n\tcase l.ll.Len() > l.capacity:\n\t\tpanic(\"impossible\")\n\tcase l.ll.Len() == l.capacity:\n\t\toldest := l.ll.Remove(l.ll.Back()).(block)\n\t\tdelete(l.blocks, oldest.offset)\n\t\tl.evicted(oldest)\n\t}\n}", "func (dl *DrawList) PrimReserve(idxCount, vtxCount int) {\n\tif sz, require := len(dl.VtxBuffer), dl.vtxIndex+vtxCount; require >= sz {\n\t\tvtxBuffer := make([]DrawVert, sz+1024)\n\t\tcopy(vtxBuffer, dl.VtxBuffer)\n\t\tdl.VtxBuffer = vtxBuffer\n\t}\n\tif sz, require := len(dl.IdxBuffer), dl.idxIndex+idxCount; require >= sz {\n\t\tidxBuffer := make([]DrawIdx, sz+1024)\n\t\tcopy(idxBuffer, dl.IdxBuffer)\n\t\tdl.IdxBuffer = idxBuffer\n\t}\n\tdl.VtxWriter = dl.VtxBuffer[dl.vtxIndex:dl.vtxIndex+vtxCount]\n\tdl.IdxWriter = dl.IdxBuffer[dl.idxIndex:dl.idxIndex+idxCount]\n}", "func (client ViewsClient) DeleteByScopePreparer(ctx context.Context, scope string, viewName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"scope\": autorest.Encode(\"path\", scope),\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2019-11-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{scope}/providers/Microsoft.CostManagement/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (sb *spdkBackend) prepare(req storage.BdevPrepareRequest, vmdDetect vmdDetectFn, hpClean hpCleanFn) (*storage.BdevPrepareResponse, error) {\n\tresp := &storage.BdevPrepareResponse{}\n\n\tif req.CleanHugepagesOnly {\n\t\t// Remove hugepages that were created by a no-longer-active SPDK process. Note that\n\t\t// when running prepare, it's unlikely that any SPDK processes are active as this\n\t\t// is performed prior to starting engines.\n\t\tnrRemoved, err := hpClean(sb.log, hugepageDir)\n\t\tif err != nil {\n\t\t\treturn resp, errors.Wrapf(err, \"clean spdk hugepages\")\n\t\t}\n\t\tresp.NrHugepagesRemoved = nrRemoved\n\n\t\tlogNUMAStats(sb.log)\n\n\t\treturn resp, nil\n\t}\n\n\t// Update request if VMD has been explicitly enabled and there are VMD endpoints configured.\n\tif err := updatePrepareRequest(sb.log, &req, vmdDetect); err != nil {\n\t\treturn resp, errors.Wrapf(err, \"update prepare request\")\n\t}\n\tresp.VMDPrepared = req.EnableVMD\n\n\t// Before preparing, reset device bindings.\n\tif req.EnableVMD {\n\t\t// Unbind devices to speed up VMD re-binding as per\n\t\t// https://github.com/spdk/spdk/commit/b0aba3fcd5aceceea530a702922153bc75664978.\n\t\t//\n\t\t// Applies block (not allow) list if VMD is configured so specific NVMe devices can\n\t\t// be reserved for other use (bdev_exclude).\n\t\tif err := sb.script.Unbind(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"un-binding devices\")\n\t\t}\n\t} else {\n\t\tif err := sb.script.Reset(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"resetting device bindings\")\n\t\t}\n\t}\n\n\treturn resp, errors.Wrap(sb.script.Prepare(&req), \"binding devices to userspace drivers\")\n}", "func CreateDeleteSurveyResourcesRequest() (request *DeleteSurveyResourcesRequest) {\n\trequest = &DeleteSurveyResourcesRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"apds\", \"2022-03-31\", \"DeleteSurveyResources\", \"/okss-services/confirm-resource/destroy\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func allocateSpace(ctx *downloaderContext, status *types.DownloaderStatus,\n\tsize uint64) {\n\tif status.Size != 0 {\n\t\tlog.Errorf(\"%s, request for duplicate storage allocation\\n\", status.Name)\n\t\treturn\n\t}\n\tkb := types.RoundupToKB(size)\n\tctx.globalStatusLock.Lock()\n\tctx.globalStatus.ReservedSpace -= status.ReservedSpace\n\tctx.globalStatus.UsedSpace += kb\n\tupdateRemainingSpace(ctx)\n\tctx.globalStatusLock.Unlock()\n\tstatus.ReservedSpace = 0\n\tstatus.Size = size\n\tpublishGlobalStatus(ctx)\n}", "func (client ModelClient) DeletePrebuiltPreparer(ctx context.Context, appID uuid.UUID, versionID string, prebuiltID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"prebuiltId\": autorest.Encode(\"path\", prebuiltID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts/{prebuiltId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (action *ActionUserDelete) Prepare() *ActionUserDeleteInvocation {\n\treturn &ActionUserDeleteInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/users/{user_id}\",\n\t}\n}", "func (cp *connPool) Allocate(\n\tcfg *config.SQL,\n\tresolver resolver.ServiceResolver,\n\tcreate func(cfg *config.SQL, resolver resolver.ServiceResolver) (*sqlx.DB, error),\n) (db *sqlx.DB, err error) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\n\tdsn, err := buildDSN(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif entry, ok := cp.pool[dsn]; ok {\n\t\tentry.refCount++\n\t\treturn entry.db, nil\n\t}\n\n\tdb, err = create(cfg, resolver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp.pool[dsn] = entry{db: db, refCount: 1}\n\n\treturn db, nil\n}", "func CreateDeleteApDeviceRequest() (request *DeleteApDeviceRequest) {\n\trequest = &DeleteApDeviceRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"cloudesl\", \"2020-02-01\", \"DeleteApDevice\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (m *manager) Reserve(d *structs.AllocatedDeviceResource) (*device.ContainerReservation, error) {\n\t// Go through each plugin and see if it can reserve the resources\n\tfor _, i := range m.instances {\n\t\tif !i.HasDevices(d) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We found a match so reserve\n\t\treturn i.Reserve(d)\n\t}\n\n\treturn nil, UnknownDeviceErrFromAllocated(\"failed to reserve devices\", d)\n}", "func (client *AvailabilitySetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif availabilitySetName == \"\" {\n\t\treturn nil, errors.New(\"parameter availabilitySetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{availabilitySetName}\", url.PathEscape(availabilitySetName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (a *Allocator) ResetMaybeReallocate(\n\ttyps []*types.T, oldBatch coldata.Batch, minCapacity int, maxBatchMemSize int64,\n) (newBatch coldata.Batch, reallocated bool) {\n\tif minCapacity < 0 {\n\t\tcolexecerror.InternalError(errors.AssertionFailedf(\"invalid minCapacity %d\", minCapacity))\n\t} else if minCapacity == 0 {\n\t\tminCapacity = 1\n\t} else if minCapacity > coldata.BatchSize() {\n\t\tminCapacity = coldata.BatchSize()\n\t}\n\treallocated = true\n\tif oldBatch == nil {\n\t\tnewBatch = a.NewMemBatchWithFixedCapacity(typs, minCapacity)\n\t} else {\n\t\t// If old batch is already of the largest capacity, we will reuse it.\n\t\tuseOldBatch := oldBatch.Capacity() == coldata.BatchSize()\n\t\t// Avoid calculating the memory footprint if possible.\n\t\tvar oldBatchMemSize int64\n\t\tif !useOldBatch {\n\t\t\t// Check if the old batch already reached the maximum memory size,\n\t\t\t// and use it if so. Note that we must check that the old batch has\n\t\t\t// enough capacity too.\n\t\t\toldBatchMemSize = GetBatchMemSize(oldBatch)\n\t\t\tuseOldBatch = oldBatchMemSize >= maxBatchMemSize && oldBatch.Capacity() >= minCapacity\n\t\t}\n\t\tif useOldBatch {\n\t\t\treallocated = false\n\t\t\toldBatch.ResetInternalBatch()\n\t\t\tnewBatch = oldBatch\n\t\t} else {\n\t\t\ta.ReleaseMemory(oldBatchMemSize)\n\t\t\tnewCapacity := oldBatch.Capacity() * 2\n\t\t\tif newCapacity < minCapacity {\n\t\t\t\tnewCapacity = minCapacity\n\t\t\t}\n\t\t\tif newCapacity > coldata.BatchSize() {\n\t\t\t\tnewCapacity = coldata.BatchSize()\n\t\t\t}\n\t\t\tnewBatch = a.NewMemBatchWithFixedCapacity(typs, newCapacity)\n\t\t}\n\t}\n\treturn newBatch, reallocated\n}", "func (client *PrivateDNSZoneGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif privateEndpointName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateEndpointName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateEndpointName}\", url.PathEscape(privateEndpointName))\n\tif privateDNSZoneGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateDNSZoneGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateDnsZoneGroupName}\", url.PathEscape(privateDNSZoneGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (endpointSliceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tendpointSlice := obj.(*discovery.EndpointSlice)\n\tendpointSlice.Generation = 1\n\n\tdropDisabledConditionsOnCreate(endpointSlice)\n}", "func (client *VirtualNetworkTapsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, tapName string, options *VirtualNetworkTapsBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{tapName}\", url.PathEscape(tapName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-07-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client PatternClient) DeletePatternsPreparer(ctx context.Context, appID uuid.UUID, versionID string, patternIds []uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternrules\", pathParameters),\n\t\tautorest.WithJSON(patternIds))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}" ]
[ "0.52881616", "0.5262748", "0.5250947", "0.51915395", "0.51663846", "0.5157574", "0.51027143", "0.50212806", "0.49939945", "0.49535996", "0.49505183", "0.49463445", "0.49417627", "0.49401733", "0.49396092", "0.49217606", "0.49027976", "0.4893439", "0.4889526", "0.48798436", "0.48636538", "0.48604572", "0.4852044", "0.484313", "0.4810996", "0.4810434", "0.48058358", "0.47897765", "0.47731048", "0.4770574", "0.47650862", "0.47509113", "0.47167692", "0.47110742", "0.47033072", "0.46956378", "0.46651572", "0.4650921", "0.46395397", "0.46283084", "0.4621157", "0.4614807", "0.46130496", "0.46028414", "0.46012732", "0.45998585", "0.4588479", "0.45834482", "0.457999", "0.457999", "0.4574488", "0.45615423", "0.45505762", "0.4544602", "0.4521481", "0.45194003", "0.4486145", "0.44834992", "0.44800392", "0.44229165", "0.44184166", "0.4396064", "0.4372618", "0.43641576", "0.43615744", "0.43530807", "0.43511218", "0.43437427", "0.43415195", "0.43263972", "0.4319228", "0.43182853", "0.43099466", "0.43084496", "0.4288889", "0.42871842", "0.42806348", "0.427231", "0.42684782", "0.42607883", "0.4235968", "0.42333505", "0.42322484", "0.42311874", "0.4218239", "0.42168736", "0.4212839", "0.42109028", "0.42106557", "0.42052257", "0.41985473", "0.41955143", "0.4180018", "0.4178601", "0.41782945", "0.41766337", "0.41667384", "0.41623294", "0.41583794", "0.41579723" ]
0.7151367
0
MaxKey returns the maximum key having the given searchPrefix, or the maximum key in the whole index if searchIndex is nil. Maximum means the last key in the lexicographic order. If keys are uint64 in BigEndian it is also the largest number. If ok is false the index is empty. For example, if we store temperature readings using the key "temp_TIMESTAMP" where timestamp is an 8 byte BigEndian ns timestamp MaxKey([]byte("temp_")) returns the last made reading.
MaxKey возвращает максимальный ключ, имеющий заданный searchPrefix, или максимальный ключ в целом индекса, если searchIndex равно nil. Максимальным считается последний ключ в лексикографическом порядке. Если ключи являются uint64 в BigEndian, это также наибольшее число. Если ok равно false, индекс пуст. Например, если мы храним показания температуры с использованием ключа "temp_TIMESTAMP", где timestamp — это 8-байтовое значение BigEndian наносекундного времени, MaxKey([]byte("temp_")) возвращает последнее сделанное измерение.
func (idx *Tree) MaxKey(searchPrefix []byte) (v uint64, ok bool) { raw, _ := idx.partialSearch(searchPrefix) if raw == 0 { return 0, false } if isLeaf(raw) { return getLeafValue(raw), true } // now find the max searchLoop: for { _, node, count, prefixLen := explodeNode(raw) block := int(node >> blockSlotsShift) offset := int(node & blockSlotsOffsetMask) data := idx.blocks[block].data[offset:] var prefixSlots int if prefixLen > 0 { if prefixLen == 255 { prefixLen = int(data[0]) prefixSlots = (prefixLen + 15) >> 3 } else { prefixSlots = (prefixLen + 7) >> 3 } data = data[prefixSlots:] } if count >= fullAllocFrom { // find max, iterate from top for k := 255; k >= 0; k-- { a := atomic.LoadUint64(&data[k]) if a != 0 { if isLeaf(a) { return getLeafValue(a), true } raw = a continue searchLoop } } // BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree! return 0, false } // load the last child (since they are ordered) a := atomic.LoadUint64(&data[count-1]) if isLeaf(a) { return getLeafValue(a), true } raw = a } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetMaxIndexKey(shardID uint64, key []byte) []byte {\n\tkey = getKeySlice(key, idKeyLength)\n\treturn getIDKey(maxIndexSuffix, shardID, key)\n}", "func MaxKey() Val { return Val{t: bsontype.MaxKey} }", "func (this *AllOne) GetMaxKey() string {\n\tif this.tail.pre != this.head {\n\t\tfor k := range this.tail.pre.keys {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn \"\"\n}", "func (tf tFiles) searchMax(icmp *iComparer, ikey internalKey) int {\n\treturn sort.Search(len(tf), func(i int) bool {\n\t\treturn icmp.Compare(tf[i].imax, ikey) >= 0\n\t})\n}", "func Max(key []byte, nodes []*memberlist.Node) (max *memberlist.Node) {\n\tmaxValue := big.NewInt(0)\n\n\tCompute(key, nodes, func(node *memberlist.Node, bi *big.Int) {\n\t\tif bi.Cmp(maxValue) == 1 {\n\t\t\tmaxValue = bi\n\t\t\tmax = node\n\t\t}\n\t})\n\n\treturn max\n}", "func (this *AllOne) GetMaxKey() string {\n\tif this.Head.Next != this.Tail {\n\t\tnmap := this.Head.Next.NodeMap\n\t\tret := \"\"\n\t\tfor k, _ := range nmap {\n\t\t\tret = k\n\t\t\tbreak\n\t\t}\n\t\treturn ret\n\t}\n\n\treturn \"\"\n}", "func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) {\n\tvar last *leafNode\n\tsearch := k\n\tfor {\n\t\t// Look for a leaf node\n\t\tif n.isLeaf() {\n\t\t\tlast = n.leaf\n\t\t}\n\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif last != nil {\n\t\treturn last.key, last.val, true\n\t}\n\treturn nil, nil, false\n}", "func (this *AllOne) GetMaxKey() string {\n if len(this.m) == 0{\n return \"\"\n }\n return this.g[this.max][1].k\n}", "func (this *AllOne) GetMaxKey() string {\n\tif this.head == nil {\n\t\treturn \"\"\n\t}\n\tfor k := range this.head.set {\n\t\treturn k\n\t}\n\treturn \"ERROR\"\n}", "func ComputeMaxKey() *big.Int {\n\tbase := big.NewInt(2)\n\tm := big.NewInt(int64(MBits))\n\n\tmax_key := big.NewInt(0)\n\tmax_key.Exp(base, m, nil)\n\tmax_key.Sub(max_key, big.NewInt(1))\n\n\treturn max_key\n}", "func (t *BinarySearch[T]) Max() (T, bool) {\n\tret := maximum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}", "func (st *RedBlackBST) Max() Key {\n\tif st.IsEmpty() {\n\t\tpanic(\"call Max on empty RedBlackbst\")\n\t}\n\treturn st.max(st.root).key\n}", "func (tree *avlBetterTree) MaxKey() (key string, value interface{}, exist bool) {\n\ttree.Lock()\n\tdefer tree.Unlock()\n\tif tree.root == nil {\n\t\t// 如果是空树,返回空\n\t\treturn\n\t}\n\n\tnode := tree.root.maxNode()\n\treturn node.k, node.v, true\n}", "func (table *Table) SearchLast(searchValues ...interface{}) (int, error) {\n\n\terr := table.checkSearchArguments(searchValues...)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\trowIndex, err := table.searchByKeysLast(searchValues)\n\n\treturn rowIndex, err\n}", "func (sa *SuffixArray) MaxValue() uint64 { return sa.ba.MaxValue() }", "func getTableMaxKey(stub shim.ChaincodeStubInterface, tableName string) ([]byte, error) {\n\t// Use emty columns slice to get all rows for count\n\tvar cols []shim.Column\n\n\tvar key string\n\tkey = \"0\"\n\tkeyint, _ := strconv.Atoi(key)\n\n\trowChan, err := stub.GetRows(tableName, cols)\n\tif err != nil {\n\t\treturn []byte(key), err\n\t}\n\n\trow, ok := <-rowChan\n\n\tfor ok {\n\t\t// Key column should be the first and table key should be single-column key\n\t\tkey = row.GetColumns()[0].GetString_()\n\t\tkeyintc, _ := strconv.Atoi(key)\n\t\tif keyintc > keyint {\n\t\t\tkeyint = keyintc\n\t\t}\n\t\trow, ok = <-rowChan\n\t}\n\n\treturn []byte(strconv.Itoa(keyint)), nil\n}", "func (cache *LRUCache) GetMostRecentKey() (string, bool) {\n\tif len(cache.hash) == 0 {\n\t\treturn \"\", false\n\t}\n\n\treturn cache.curr.key, true\n}", "func (b *raftBadger) LastIndex() (uint64, error) {\n\tstore := b.gs.GetStore().(*badger.DB)\n\tlast := uint64(0)\n\tif err := store.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\t\topts.Reverse = true\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\t\t// see https://github.com/dgraph-io/badger/issues/436\n\t\t// and https://github.com/dgraph-io/badger/issues/347\n\t\tseekKey := append(dbLogPrefix, 0xFF)\n\t\tit.Seek(seekKey)\n\t\tif it.ValidForPrefix(dbLogPrefix) {\n\t\t\titem := it.Item()\n\t\t\tk := string(item.Key()[len(dbLogPrefix):])\n\t\t\tidx, err := strconv.ParseUint(k, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlast = idx\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\treturn last, nil\n}", "func (tc *sklImpl) GetMax(start, end roachpb.Key) (hlc.Timestamp, uuid.UUID) {\n\tvar val cacheValue\n\tif len(end) == 0 {\n\t\tval = tc.cache.LookupTimestamp(nonNil(start))\n\t} else {\n\t\tval = tc.cache.LookupTimestampRange(nonNil(start), end, excludeTo)\n\t}\n\treturn val.ts, val.txnID\n}", "func (entries Entries) max() (uint64, bool) {\n\tif len(entries) == 0 {\n\t\treturn 0, false\n\t}\n\n\treturn entries[len(entries)-1].Key(), true\n}", "func (l *LevelDB) LastIndex() (uint64, error) {\n\titer := l.db.NewIterator(&util.Range{Start: nil, Limit: nil}, nil)\n\tdefer iter.Release()\n\titer.Last()\n\titer.Prev()\n\n\tfor iter.Next() {\n\t\tkey := binary.LittleEndian.Uint64(iter.Key())\n\t\treturn key, nil\n\t}\n\n\treturn 0, nil\n}", "func TestIntMaxProperties(t *testing.T) {\n\tf := func(c intMaxTestCase) bool {\n\t\tvar (\n\t\t\tks []int\n\t\t\tvs []int\n\t\t)\n\t\tfor k, kVals := range c.valsByKey {\n\t\t\tfor _, v := range kVals {\n\t\t\t\tks = append(ks, k)\n\t\t\t\tvs = append(vs, v)\n\t\t\t}\n\t\t}\n\t\tslice := bigslice.Const(c.numShards, ks, vs)\n\t\tslice = IntMax(slice)\n\t\tscanner := slicetest.Run(t, slice)\n\t\tvar (\n\t\t\tk int\n\t\t\tmax int\n\t\t\tgot = make(map[int]int)\n\t\t)\n\t\tfor scanner.Scan(context.Background(), &k, &max) {\n\t\t\t// Each key exists in the input.\n\t\t\tinVs, ok := c.valsByKey[k]\n\t\t\tif !ok {\n\t\t\t\tt.Logf(\"key not in input: %v\", k)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// The maximum value exists in the input for the key.\n\t\t\tvar found bool\n\t\t\tfor _, inV := range inVs {\n\t\t\t\tif max == inV {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tt.Logf(\"value not found key inputs for key %v: %v\", k, max)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// No input for the key is greater than the computed maximum.\n\t\t\tfor _, inV := range inVs {\n\t\t\t\tif max < inV {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\t// No key is duplicated.\n\t\t\tif _, ok = got[k]; ok {\n\t\t\t\tt.Logf(\"duplicate k: %v\", k)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tgot[k] = max\n\t\t}\n\n\t\treturn true\n\t}\n\tc := quick.Config{MaxCount: 10}\n\tif err := quick.Check(f, &c); err != nil {\n\t\tt.Error(err)\n\t}\n}", "func MaxAckSeqKey(sourceChain, destinationChain string) []byte {\n\treturn []byte(MaxAckSeqPath(sourceChain, destinationChain))\n}", "func (cache *LRUCache) GetMostRecentKey() (string, bool) {\n\tif cache.listofMostRecent.head == nil {\n\t\treturn \"\", false\n\t}\n\treturn cache.listofMostRecent.head.key, true\n}", "func (n *Node) Max() int {\n\tif n.Right == nil {\n\t\treturn n.Key\n\t}\n\n\treturn n.Right.Max()\n}", "func FindNextGreatestToKey(k int64, l int64, h int64, s []int64) (int64, error) {\n\tintervalLength := h - l\n\tswitch {\n\tcase intervalLength == 0:\n\t\tswitch {\n\t\tcase s[h] > k:\n\t\t\treturn h, nil\n\t\tcase h+1 < int64(len(s)):\n\t\t\treturn h + 1, nil\n\t\tdefault:\n\t\t\treturn 0, errors.New(\"no elem > than key\")\n\t\t}\n\tcase intervalLength == 1:\n\t\tswitch {\n\t\tcase s[l] > k:\n\t\t\treturn l, nil\n\t\tcase s[h] > k:\n\t\t\treturn h, nil\n\t\tcase h+1 < int64(len(s)):\n\t\t\treturn h + 1, nil\n\t\tdefault:\n\t\t\treturn 0, errors.New(\"no elem > than key\")\n\t\t\t//no k\n\t\t}\n\tdefault:\n\t\tmidIntervalIndex := (h + l) / 2\n\t\tmid := s[midIntervalIndex]\n\t\tswitch {\n\t\tcase mid > k:\n\t\t\th = midIntervalIndex - 1\n\t\tcase mid <= k:\n\t\t\tl = midIntervalIndex + 1\n\t\t}\n\t\treturn FindNextGreatestToKey(k, l, h, s)\n\t}\n}", "func (t *Table) Biggest() y.Key { return t.biggest }", "func longestPrefix(k1, k2 []byte) int {\n\tlimit := min(len(k1), len(k2))\n\tfor i := 0; i < limit; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn limit\n}", "func (i *InmemStore) LastIndex() (uint64, error) {\n\ti.l.RLock()\n\tdefer i.l.RUnlock()\n\treturn i.highIndex, nil\n}", "func GetNodeMaxKeys(node []byte) uint32 {\n\tswitch GetNodeType(node) {\n\tcase TypeInternalNode:\n\t\t// For an internal node, the maximum key is always its right key.\n\t\treturn *InternalNodeKey(node, *InternalNodeNumKeys(node)-1)\n\tcase TypeLeafNode:\n\t\t// For a leaf node, it’s the key at the maximum index\n\t\treturn *LeafNodeKey(node, *LeafNodeNumCells(node)-1)\n\tdefault:\n\t\tfmt.Printf(\"Unkown node type\\n\")\n\t\tos.Exit(util.ExitFailure)\n\t\treturn 0\n\t}\n}", "func (h *hashLongestMatchQuickly) FindLongestMatch(dictionary *encoderDictionary, data []byte, ring_buffer_mask uint, distance_cache []int, cur_ix uint, max_length uint, max_backward uint, gap uint, max_distance uint, out *hasherSearchResult) {\n\tvar best_len_in uint = out.len\n\tvar cur_ix_masked uint = cur_ix & ring_buffer_mask\n\tvar key uint32 = h.HashBytes(data[cur_ix_masked:])\n\tvar compare_char int = int(data[cur_ix_masked+best_len_in])\n\tvar min_score uint = out.score\n\tvar best_score uint = out.score\n\tvar best_len uint = best_len_in\n\tvar cached_backward uint = uint(distance_cache[0])\n\tvar prev_ix uint = cur_ix - cached_backward\n\tvar bucket []uint32\n\tout.len_code_delta = 0\n\tif prev_ix < cur_ix {\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char == int(data[prev_ix+best_len]) {\n\t\t\tvar len uint = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScoreUsingLastDistance(uint(len))\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = uint(len)\n\t\t\t\t\tout.distance = cached_backward\n\t\t\t\t\tout.score = best_score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t\tif h.bucketSweep == 1 {\n\t\t\t\t\t\th.buckets[key] = uint32(cur_ix)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.bucketSweep == 1 {\n\t\tvar backward uint\n\t\tvar len uint\n\n\t\t/* Only one to look for, don't bother to prepare for a loop. */\n\t\tprev_ix = uint(h.buckets[key])\n\n\t\th.buckets[key] = uint32(cur_ix)\n\t\tbackward = cur_ix - prev_ix\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char != int(data[prev_ix+best_len_in]) {\n\t\t\treturn\n\t\t}\n\n\t\tif backward == 0 || backward > max_backward {\n\t\t\treturn\n\t\t}\n\n\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\tif len >= 4 {\n\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\tif best_score < score {\n\t\t\t\tout.len = uint(len)\n\t\t\t\tout.distance = backward\n\t\t\t\tout.score = score\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbucket = h.buckets[key:]\n\t\tvar i int\n\t\tprev_ix = uint(bucket[0])\n\t\tbucket = bucket[1:]\n\t\tfor i = 0; i < h.bucketSweep; (func() { i++; tmp3 := bucket; bucket = bucket[1:]; prev_ix = uint(tmp3[0]) })() {\n\t\t\tvar backward uint = cur_ix - prev_ix\n\t\t\tvar len uint\n\t\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\t\tif compare_char != int(data[prev_ix+best_len]) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif backward == 0 || backward > max_backward {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = best_len\n\t\t\t\t\tout.distance = backward\n\t\t\t\t\tout.score = score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.useDictionary && min_score == out.score {\n\t\tsearchInStaticDictionary(dictionary, h, data[cur_ix_masked:], max_length, max_backward+gap, max_distance, out, true)\n\t}\n\n\th.buckets[key+uint32((cur_ix>>3)%uint(h.bucketSweep))] = uint32(cur_ix)\n}", "func MaxKeys(value int) Option {\n\treturn addParam(\"maxkeys\", strconv.Itoa(value))\n}", "func (ls *LevelDBStore) LastIndex() (uint64, error) {\n\tls.rwMtx.Lock()\n\tdefer ls.rwMtx.Unlock()\n\titer := ls.ldb.NewIterator(nil, nil)\n\tdefer iter.Release()\n\tif iter.Last() {\n\t\tkey := iter.Key()\n\t\treturn bytesToUint64(key), nil\n\t}\n\treturn 0, nil\n}", "func calcUpperBound(prefix string) []byte {\n\tif len(prefix) == 0 {\n\t\treturn []byte{}\n\t}\n\n\tp := []byte(prefix)\n\n\tp[len(p)-1] = p[len(p)-1] + 1\n\treturn p\n}", "func MaxKeys(max int) Option {\n\treturn func(lc *memoryCache) error {\n\t\tlc.maxKeys = max\n\t\treturn nil\n\t}\n}", "func MaxKeys(max int) Option {\n\treturn func(lc *loadingCache) error {\n\t\tlc.maxKeys = max\n\t\treturn nil\n\t}\n}", "func (ms *MemoryStorage) LastIndex() (uint64, error) {\n\tms.Lock()\n\tdefer ms.Unlock()\n\treturn ms.lastIndex(), nil\n}", "func (n *Node) Maximum() ([]byte, interface{}, bool) {\n\tfor {\n\t\tif num := len(n.edges); num > 0 {\n\t\t\tn = n.edges[num-1].node\n\t\t\tcontinue\n\t\t}\n\t\tif n.isLeaf() {\n\t\t\treturn n.leaf.key, n.leaf.val, true\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil, nil, false\n}", "func TestPrefixEndKey(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\ttestData := []struct {\n\t\tprefix, expEnd proto.Key\n\t}{\n\t\t{proto.KeyMin, proto.KeyMax},\n\t\t{proto.Key(\"0\"), proto.Key(\"1\")},\n\t\t{proto.Key(\"a\"), proto.Key(\"b\")},\n\t\t{proto.Key(\"db0\"), proto.Key(\"db1\")},\n\t\t{proto.Key(\"\\xfe\"), proto.Key(\"\\xff\")},\n\t\t{proto.KeyMax, proto.KeyMax},\n\t\t{proto.Key(\"\\xff\\xff\"), proto.Key(\"\\xff\\xff\")},\n\t}\n\n\tfor i, test := range testData {\n\t\tif !test.prefix.PrefixEnd().Equal(test.expEnd) {\n\t\t\tt.Errorf(\"%d: %q end key %q != %q\", i, test.prefix, test.prefix.PrefixEnd(), test.expEnd)\n\t\t}\n\t}\n}", "func MaxKeys(max int) Option {\n\treturn func(lc cacheWithOpts) error {\n\t\treturn lc.setMaxKeys(max)\n\t}\n}", "func (bst *StringBinarySearchTree) Max() *string {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\tn := bst.root\n\tif n == nil {\n\t\treturn nil\n\t}\n\tfor {\n\t\tif n.right == nil {\n\t\t\treturn &n.value\n\t\t}\n\t\tn = n.right\n\t}\n}", "func (p *partitionImpl) FindLastRowKey(keyBuf []byte, key uint64, keyfn sif.KeyingOperation) (int, error) {\n\t// find the first matching uint64 key\n\tfirstKey, err := p.FindFirstRowKey(keyBuf, key, keyfn) // this will error with missing key if it doesn't exist\n\tif err != nil {\n\t\treturn firstKey, err\n\t}\n\tlastKey := firstKey\n\t// iterate over each row with a matching key to find the last one with identical key bytes\n\tfor i := firstKey + 1; i < p.GetNumRows(); i++ {\n\t\tif k, err := p.GetKey(i); err != nil {\n\t\t\treturn -1, err\n\t\t} else if k != key {\n\t\t\tbreak // current key isn't the same, break out\n\t\t}\n\t\trowKey, err := keyfn(&rowImpl{\n\t\t\tmeta: p.GetRowMeta(i),\n\t\t\tdata: p.GetRowData(i),\n\t\t\tvarData: p.GetVarRowData(i),\n\t\t\tserializedVarData: p.GetSerializedVarRowData(i),\n\t\t\tschema: p.GetCurrentSchema(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t} else if reflect.DeepEqual(keyBuf, rowKey) {\n\t\t\tlastKey = i\n\t\t} else {\n\t\t\tbreak // current key isn't the same, break out\n\t\t}\n\t}\n\treturn lastKey, nil\n}", "func MaxKeys(max int) Option {\n\treturn func(lc *cacheImpl) error {\n\t\tlc.maxKeys = max\n\t\treturn nil\n\t}\n}", "func FixMaxEntryIndex(rdb *Store, profile *pb.Profile) error {\n\tuuid1, err := uuid.FromString(profile.Uuid)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// MAX Delimiter Key\n\tkey := MaxUUIDFlakeKey(TableEntryIndex, uuid1)\n\treturn rdb.Put(key.Bytes(), []byte(\"0000\"))\n}", "func ExampleClient_TdMax() {\n\thost := \"localhost:6379\"\n\tvar client = redisbloom.NewClient(host, \"nohelp\", nil)\n\n\tkey := \"example\"\n\t_, err := client.TdCreate(key, 10)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tsamples := map[float64]float64{1.0: 1.0, 2.0: 2.0, 3.0: 3.0}\n\t_, err = client.TdAdd(key, samples)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tmax, err := client.TdMax(key)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(max)\n\t// Output: 3\n}", "func (idx *Tree) MinKey(searchPrefix []byte) (v uint64, ok bool) {\n\traw, _ := idx.partialSearch(searchPrefix)\n\tif raw == 0 {\n\t\treturn 0, false\n\t}\n\tif isLeaf(raw) {\n\t\treturn getLeafValue(raw), true\n\t}\n\t// now find the min\nsearchLoop:\n\tfor {\n\t\t_, node, count, prefixLen := explodeNode(raw)\n\t\tblock := int(node >> blockSlotsShift)\n\t\toffset := int(node & blockSlotsOffsetMask)\n\t\tdata := idx.blocks[block].data[offset:]\n\t\tvar prefixSlots int\n\t\tif prefixLen > 0 {\n\t\t\tif prefixLen == 255 {\n\t\t\t\tprefixLen = int(data[0])\n\t\t\t\tprefixSlots = (prefixLen + 15) >> 3\n\t\t\t} else {\n\t\t\t\tprefixSlots = (prefixLen + 7) >> 3\n\t\t\t}\n\t\t\tdata = data[prefixSlots:]\n\t\t}\n\t\tif count >= fullAllocFrom {\n\t\t\t// find min, iterate from bottom\n\t\t\tfor k := range data[:count] {\n\t\t\t\ta := atomic.LoadUint64(&data[k])\n\t\t\t\tif a != 0 {\n\t\t\t\t\tif isLeaf(a) {\n\t\t\t\t\t\treturn getLeafValue(a), true\n\t\t\t\t\t}\n\t\t\t\t\traw = a\n\t\t\t\t\tcontinue searchLoop\n\t\t\t\t}\n\t\t\t}\n\t\t\t// BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree!\n\t\t\treturn 0, false\n\t\t}\n\t\t// load first child (since they are ordered)\n\t\ta := atomic.LoadUint64(&data[0])\n\t\tif isLeaf(a) {\n\t\t\treturn getLeafValue(a), true\n\t\t}\n\t\traw = a\n\t}\n}", "func GetMaxIndexes() int {\r\n\treturn converter.StrToInt(SysString(MaxIndexes))\r\n}", "func _enumerateLimitedKeysReversedForPrefix(db *badger.DB, dbPrefix []byte, limit uint64) (_keysFound [][]byte, _valsFound [][]byte) {\n\tkeysFound := [][]byte{}\n\tvalsFound := [][]byte{}\n\n\tdbErr := db.View(func(txn *badger.Txn) error {\n\t\tvar err error\n\t\tkeysFound, valsFound, err = _enumerateLimitedKeysReversedForPrefixWithTxn(txn, dbPrefix, limit)\n\t\treturn err\n\t})\n\tif dbErr != nil {\n\t\tglog.Errorf(\"_enumerateKeysForPrefix: Problem fetching keys and vlaues from db: %v\", dbErr)\n\t\treturn nil, nil\n\t}\n\n\treturn keysFound, valsFound\n}", "func (b *BadgerStore) LastIndex() (uint64, error) {\n\treturn b.firstIndex(true)\n}", "func (b *BadgerStore) LastIndex() (uint64, error) {\n\treturn b.firstIndex(true)\n}", "func assertLongestSuffix(t *testing.T, tree *Tree, key string, expectedFound bool) {\n\tmatchedKey, value, found := tree.LongestSuffix([]byte(key))\n\tassert.Equal(t, expectedFound, found)\n\tif expectedFound && value != nil {\n\t\tassert.Equal(t, string(matchedKey), value.(string))\n\t}\n}", "func (c *Client) BZPopMax(_ context.Context, timeout time.Duration, keys ...string) *redis.ZWithKeyCmd {\n\treturn c.cli.BZPopMax(timeout, keys...)\n}", "func (p *MessagePartition) calculateMaxMessageIdFromIndex(fileId uint64) (uint64, error) {\n\tstat, err := os.Stat(p.indexFilenameByMessageId(fileId))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tentriesInIndex := uint64(stat.Size() / int64(INDEX_ENTRY_SIZE))\n\n\treturn (entriesInIndex - 1 + fileId), nil\n}", "func (m *Matcher) GetLongest(sw *util.SlidingWindow) (*matcher.Encoded, error) {\n\tlongestMatch := 0\n\tstartSearch := -1\n\tstartLookAhead := -1\n\t//fmt.Println(\"***********************************************\")\n\t//fmt.Printf(\"finding longest match!!\\nSearch<head: %v, tail:%v, numElems: %v>, Look Ahead<head: %v, tail:%v, numElems: %v>\\n\",\n\t//\tsw.Search.GetFront(), sw.Search.GetRear(), sw.Search.GetCount(),\n\t//\tsw.LookAhead.GetFront(), sw.LookAhead.GetRear(), sw.LookAhead.GetCount())\n\n\t//fmt.Println(\"Search isEmpty:\", sw.Search.IsEmpty(), \" Look Ahead isEmpty:\", sw.LookAhead.IsEmpty())\n\n\tif !sw.Search.IsEmpty() && !sw.LookAhead.IsEmpty() {\n\t\tfor i := int(sw.Search.GetFront()); i != int(sw.Search.GetRear()); i = (i + 1) % int(sw.Search.GetSize()) {\n\t\t\tcounter := 0\n\t\t\tj := int(sw.LookAhead.GetFront())\n\t\t\tfor sw.Search.GetBuffer()[i+counter] == sw.LookAhead.GetBuffer()[j+counter] {\n\t\t\t\tcounter++\n\t\t\t\tif ((i + counter) >= int(sw.Search.GetSize())) || ((j + counter) >= int(sw.LookAhead.GetSize())) {\n\t\t\t\t\t//fmt.Println(\"breaking!!!\")\n\t\t\t\t\tbreak\n\t\t\t\t} else if counter > longestMatch {\n\t\t\t\t\tlongestMatch = counter\n\t\t\t\t\tstartSearch = i\n\t\t\t\t\tstartLookAhead = j\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//fmt.Println(\"found longest match =\", longestMatch)\n\t//fmt.Println(\"***********************************************\")\n\n\t// If the longest match is less than 3, then just ignore it\n\tif longestMatch <= util.MaxUncompressed {\n\t\tdatum, err := sw.LookAhead.Peek()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &matcher.Encoded{\n\t\t\tType: matcher.UNCOMPRESSED,\n\t\t\tDatum: datum,\n\t\t\tOffset: 0,\n\t\t\tLength: 0,\n\t\t}, nil\n\t}\n\n\t//fmt.Printf(\"longest match found!! search start idx: %v, look ahead start idx: %v\\n\",\n\t//\tstartSearch, startLookAhead)\n\t// If not, then calculate the offset and return\n\t// offset = dist of startSearch from search.rear + dist of startLookAhead from lookahead.front\n\toffset := sw.Search.GetDist(int32(startSearch), sw.Search.GetRear()) +\n\t\tsw.LookAhead.GetDist(sw.LookAhead.GetFront(), int32(startLookAhead)) - 1\n\n\treturn &matcher.Encoded{\n\t\tType: matcher.COMPRESSED,\n\t\tOffset: offset,\n\t\tLength: uint8(longestMatch),\n\t}, nil\n}", "func (s *GoSort) FindMaxElementAndIndex() (interface{},int) {\n var index = 0\n \n for i := 1; i < s.Len(); i++ {\n if s.GreaterThan(i, index) {\n index = i\n }\n }\n return s.values[index], index\n}", "func (bst *BinarySearch) Max() (int, error) {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\n\tn := bst.root\n\tif n == nil {\n\t\treturn 0, fmt.Errorf(\"max: no nodes exist in tree\")\n\t}\n\tfor {\n\t\tif n.right == nil {\n\t\t\treturn n.value, nil\n\t\t}\n\t\tn = n.right\n\t}\n}", "func maxNamespace(hash []byte, size namespace.IDSize) []byte {\n\tmax := make([]byte, 0, size)\n\treturn append(max, hash[size:size*2]...)\n}", "func findLongestPrefix(names []string) int {\n\tif len(names) < 1 {\n\t\treturn 0\n\t}\n\treaders := make([]*strings.Reader, 0, len(names))\n\tfor _, m := range names {\n\t\treaders = append(readers, strings.NewReader(m))\n\t}\n\n\tfor {\n\t\trune0, _, err := readers[0].ReadRune()\n\t\tif err != nil {\n\t\t\treturn int(readers[0].Size())\n\t\t}\n\t\tfor _, re := range readers[1:] {\n\t\t\tr, _, err := re.ReadRune()\n\t\t\tif err != nil {\n\t\t\t\treturn int(re.Size())\n\t\t\t}\n\t\t\tif r != rune0 {\n\t\t\t\tre.UnreadRune()\n\t\t\t\treturn int(re.Size()) - re.Len()\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}", "func (px *Paxos) Max() int {\n\tkeys := px.sortedSeqs()\n\tif len(keys) == 0 {\n\t\treturn -1\n\t} else {\n\t\tsort.Ints(keys)\n\t}\n\treturn keys[len(keys)-1]\n}", "func getMaxID() int {\n\n\tif len(cdb.classMap) != 0 {\n\t\tkeys := make([]int, 0, len(cdb.classMap))\n\t\tfor k := range cdb.classMap {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Ints(keys)\n\t\treturn keys[len(keys)-1]\n\t}\n\n\treturn -1\n\n}", "func (o LookupManagedPrefixListResultOutput) MaxEntries() pulumi.IntOutput {\n\treturn o.ApplyT(func(v LookupManagedPrefixListResult) int { return v.MaxEntries }).(pulumi.IntOutput)\n}", "func (params *KeyParameters) MaxMsgBytes() int {\n\treturn (params.P.BitLen() / 8) - 4\n}", "func getLocationWithLongestPrefix(locations []Location) *Location {\n\tlongest := &locations[0]\n\tlength := len(locations[0].Prefix)\n\n\tfor _, location := range locations {\n\t\tif len(location.Prefix) > length {\n\t\t\tlongest, length = &location, len(location.Prefix)\n\t\t}\n\t}\n\n\treturn longest\n}", "func FindKthMax(nums []int, k int) (int, error) {\n\tindex := len(nums) - k\n\treturn kthNumber(nums, index)\n}", "func (t *tree) longestPrefix(k1, k2 string) int {\n\tmax := len(k1)\n\tif l := len(k2); l < max {\n\t\tmax = l\n\t}\n\tvar i int\n\tfor i = 0; i < max; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn i\n}", "func FindWords(prefix string, max string) []string {\n convertedMax, _ := strconv.ParseInt(max, 10, 8)\n var listOfWords []string\n listOfWords = trie.FindEntries(prefix, uint8(convertedMax))\n return listOfWords\n}", "func (s *OverflowShelf) PopMax(temp string) (maxOrderID uuid.UUID, found bool, err error) {\n\tvar orders map[uuid.UUID]float32\n\torders, err = s.getOrders(temp)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(orders) == 0 {\n\t\t// no orders for temp, return not found.\n\t\treturn\n\t}\n\n\tmaxDecayRate := float32(-1)\n\n\t// O(n) scan is quick for small sets. When size gets bigger,\n\t// use priority queues instead of slices to Store the orders.\n\tfor orderID, decayRate := range orders {\n\t\tif decayRate > maxDecayRate {\n\t\t\tmaxDecayRate = decayRate\n\t\t\tmaxOrderID = orderID\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tdelete(orders, maxOrderID)\n\treturn\n}", "func (t *Indexed) Max(i, j int) int {\n\treturn -1\n}", "func (k Keeper) GetLastValidatorPower(ctx sdk.Context, index string) (val types.LastValidatorPower, found bool) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.LastValidatorPowerKey))\n\n\tb := store.Get(types.KeyPrefix(index))\n\tif b == nil {\n\t\treturn val, false\n\t}\n\n\tk.cdc.MustUnmarshalBinaryBare(b, &val)\n\treturn val, true\n}", "func (i *LogStore) LastIndex() (uint64, error) {\n\ti.l.RLock()\n\tdefer i.l.RUnlock()\n\treturn i.highIndex, nil\n}", "func (k Keeper) GetMaxBlockLock(ctx sdk.Context) uint64 {\n\tparams := k.GetParams(ctx)\n\treturn params.MaxBlockLock\n}", "func (tree *RedBlack[K, V]) Max() (v alg.Pair[K, V], ok bool) {\n\tif max := tree.root.max(); max != nil {\n\t\treturn alg.Two(max.key, max.value), true\n\t}\n\treturn\n}", "func MostLikelyXorKey(cypherBlock []byte) byte {\n\tbestScore := 0.0\n\tvar winnerK byte\n\tfor k := 0; k < 255; k++ {\n\t\tdata := SingleCharXor(cypherBlock, byte(k))\n\t\tcMap := NewCharMap(data)\n\t\tscore := cMap.EnglishScore(true)\n\t\tif score >= bestScore {\n\t\t\t// give a preference to ascii letters\n\t\t\tif score == bestScore && IsASCIILetter(winnerK) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbestScore = score\n\t\t\twinnerK = byte(k)\n\t\t}\n\t}\n\n\treturn winnerK\n}", "func (w *WaterMark) LastIndex() uint64 {\n\treturn w.lastIndex.Load()\n}", "func (c *Signature) Max() int {\n\tif c.MaxValue == nil {\n\t\treturn 0\n\t}\n\treturn toolbox.AsInt(c.MaxValue)\n}", "func FindLastIndex(data, callback interface{}, args ...int) (int, error) {\n\tvar err error\n\n\tresult := func(err *error) int {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn -1\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn -1\n\t\t}\n\n\t\tcallbackValue, callbackType := inspectFunc(err, callback)\n\t\tif *err != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\tcallbackTypeNumIn := validateFuncInputForSliceLoop(err, callbackType, dataValue)\n\t\tif *err != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\tvalidateFuncOutputOneVarBool(err, callbackType, true)\n\t\tif *err != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn -1\n\t\t}\n\n\t\tendIndex := dataValueLen\n\t\tif len(args) > 0 {\n\t\t\tendIndex = args[0]\n\t\t}\n\n\t\tresult := -1\n\n\t\tforEachSliceStoppable(dataValue, dataValueLen, func(each reflect.Value, i int) bool {\n\t\t\tif i > endIndex {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tres := callFuncSliceLoop(callbackValue, each, i, callbackTypeNumIn)\n\t\t\tif res[0].Bool() {\n\t\t\t\tresult = i\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\tif result < 0 {\n\t\t\treturn result\n\t\t}\n\n\t\treturn result\n\t}(&err)\n\n\treturn result, err\n}", "func MaxValue(freqMap map[string]int) int {\n m := 0\n firstTimeThrough := true\n\n for _, value := range freqMap {\n if firstTimeThrough || value > m {\n m = value\n firstTimeThrough = false\n }\n }\n\n return m\n}", "func (k Keeper) MaxValidators(ctx sdk.Context) (res uint32) {\n\tk.paramspace.Get(ctx, types.KeyMaxValidators, &res)\n\treturn\n}", "func getLastKnownPosition(txn *badger.Txn, pn insolar.PulseNumber) (uint32, error) {\n\tkey := lastKnownRecordPositionKey{pn: pn}\n\n\tfullKey := append(key.Scope().Bytes(), key.ID()...)\n\n\titem, err := txn.Get(fullKey)\n\tif err != nil {\n\t\tif err == badger.ErrKeyNotFound {\n\t\t\treturn 0, ErrNotFound\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tbuff, err := item.ValueCopy(nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn binary.BigEndian.Uint32(buff), nil\n}", "func (na *NArray) MaxIdx() (float32, []int) {\n\n\tvar offset int\n\tmax := float32(-math.MaxFloat32)\n\tfor i := 0; i < len(na.Data); i++ {\n\t\tif na.Data[i] > max {\n\t\t\tmax = na.Data[i]\n\t\t\toffset = i\n\t\t}\n\t}\n\treturn max, na.ReverseIndex(offset)\n}", "func (tb *TimeBucket) Max() int64 { return tb.max }", "func (t *BinarySearchTree) FindMax() int {\n\tnode := t.root\n\tfor {\n\t\tif node.right != nil {\n\t\t\tnode = node.right\n\t\t} else {\n\t\t\treturn node.data\n\t\t}\n\t}\n}", "func Max(bs []byte) int {\n\tvar max int\n\tfor _, dist := range All(bs) {\n\t\tif dist > max {\n\t\t\tmax = dist\n\t\t}\n\t}\n\treturn max\n}", "func LastIndex(key string) string {\n\treturn key[strings.LastIndexAny(key, \"/\")+1:]\n}", "func GetHighestVersion(tags map[string]string) (*int64, error) {\n\tif tags == nil {\n\t\treturn nil, errNoKnownVersions\n\t}\n\tvar result *int64\n\tfor tag := range tags {\n\t\tversion, err := strconv.ParseInt(tag, 10, 64)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif result == nil || version > *result {\n\t\t\tresult = &version\n\t\t}\n\t}\n\tif result == nil {\n\t\treturn nil, errNoKnownVersions\n\t}\n\treturn result, nil\n}", "func getMaxName() string {\n\tl, err := filepath.Glob(\"*.cert\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to Glob *.pem: %s\", err)\n\t}\n\tres := []int{}\n\tfor _, k := range l {\n\t\tres = append(res, tonum(k))\n\t}\n\tmax := 0\n\tfor _, p := range res {\n\t\tif p > max {\n\t\t\tmax = p\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%d\", max+1)\n}", "func searchInDiskTables(dbDir string, maxIndex int, key []byte) ([]byte, bool, error) {\n\tfor index := maxIndex; index >= 0; index-- {\n\t\tvalue, exists, err := searchInDiskTable(dbDir, index, key)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to search in disk table with index %d: %w\", index, err)\n\t\t}\n\n\t\tif exists {\n\t\t\treturn value, exists, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}", "func (na *NArray) Max() float32 {\n\tif na == nil || len(na.Data) == 0 {\n\t\tpanic(\"unable to take max of nil or zero-sizes array\")\n\t}\n\treturn maxSliceElement(na.Data)\n}", "func (r *Redis) MaxSize() int64 {\n\treturn r.maxSize\n}", "func LastIndexOf(data interface{}, search interface{}, args ...int) (int, error) {\n\tvar err error\n\n\tresult := func(err *error) int {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn -1\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn -1\n\t\t}\n\n\t\tstartIndex := dataValueLen - 1\n\t\tif len(args) > 0 {\n\t\t\tstartIndex = args[0]\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn -1\n\t\t}\n\n\t\tresult := -1\n\n\t\tforEachSliceStoppable(dataValue, dataValueLen, func(each reflect.Value, i int) bool {\n\t\t\tif startIndex > -1 {\n\t\t\t\tiFromRight := startIndex - i\n\t\t\t\tif iFromRight > (dataValueLen-1) || iFromRight < 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\teachFromRight := dataValue.Index(iFromRight)\n\t\t\t\tif eachFromRight.Interface() == search && result == -1 {\n\t\t\t\t\tresult = iFromRight\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tiFromRight := dataValueLen + startIndex - i\n\t\t\t\tif iFromRight > (dataValueLen-1) || iFromRight < 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\teachFromRight := dataValue.Index(iFromRight)\n\t\t\t\tif eachFromRight.Interface() == search && result == -1 {\n\t\t\t\t\tresult = iFromRight\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\treturn result\n\t}(&err)\n\n\treturn result, err\n}", "func (master *MasterIndex) LastIndex() Index {\n\treturn master.indexCache[len(master.indexCache)-1]\n}", "func (transaction *TokenUpdateTransaction) GetMaxBackoff() time.Duration {\n\tif transaction.maxBackoff != nil {\n\t\treturn *transaction.maxBackoff\n\t}\n\n\treturn 8 * time.Second\n}", "func MaxIndex(vec mat.Vector) int {\n\tmax := math.Inf(-1)\n\tmaxIndex := -1\n\n\tfor i := 0; i < vec.Len(); i++ {\n\t\tvalue := vec.AtVec(i)\n\t\tif value > max {\n\t\t\tmax = value\n\t\t\tmaxIndex = i\n\t\t}\n\t}\n\n\treturn maxIndex\n}", "func MaxLen(n int) PktCnf1 {\n\treturn PktCnf1(n & 0xff)\n}", "func (r *radNode) getLast() *radNode {\n\tn := r.desc\n\tif n == nil {\n\t\treturn nil\n\t}\n\tif n.sis == nil {\n\t\treturn n\n\t}\n\tkey := string(n.prefix)\n\tfor d := n.sis; d != nil; d = d.sis {\n\t\tk := string(d.prefix)\n\t\tif k > key {\n\t\t\tn = d\n\t\t\tkey = k\n\t\t}\n\t}\n\treturn n\n}", "func (q *SimpleQueue) searchMaxExtID(ctx context.Context, source string, dt time.Time) (extID int64, ok bool, err *mft.Error) {\n\tblocks := make([]*SimpleQueueBlock, 0)\n\n\tif !q.mx.RTryLock(ctx) {\n\t\treturn extID, false, GenerateError(10027000)\n\t}\n\n\tfor i := len(q.Blocks) - 1; i >= 0; i-- {\n\t\tblocks = append(blocks, q.Blocks[i])\n\t\tif q.Blocks[i].Dt.Unix() < dt.Unix() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tq.mx.RUnlock()\n\tmaxID := int64(0)\n\tfor _, block := range blocks {\n\t\tif !block.mx.RTryLock(ctx) {\n\t\t\treturn extID, false, GenerateError(10027001)\n\t\t}\n\n\t\tif block.IsUnload {\n\t\t\terr = block.load(ctx, q)\n\t\t\tif err != nil {\n\t\t\t\treturn extID, false, err\n\t\t\t}\n\t\t} else {\n\t\t\tblock.LastGet = time.Now()\n\t\t}\n\n\t\tif len(block.Data) == 0 {\n\t\t\tblock.mx.RUnlock()\n\t\t\tcontinue\n\t\t}\n\n\t\tfor i := len(block.Data) - 1; i >= 0; i-- {\n\t\t\tif block.Data[i].Source == source {\n\t\t\t\tif maxID == 0 {\n\t\t\t\t\tmaxID = block.Data[i].ExternalID\n\t\t\t\t} else if maxID < block.Data[i].ExternalID {\n\t\t\t\t\tmaxID = block.Data[i].ExternalID\n\t\t\t\t}\n\t\t\t\tblock.mx.RUnlock()\n\t\t\t}\n\t\t}\n\n\t\tblock.mx.RUnlock()\n\t}\n\tif maxID != 0 {\n\t\treturn maxID, true, nil\n\t}\n\n\treturn extID, false, nil\n}", "func Max(Len int, Less func(i, j int) bool) int {\n\tmx := 0\n\tfor i := 1; i < Len; i++ {\n\t\tif Less(mx, i) {\n\t\t\tmx = i\n\t\t}\n\t}\n\treturn mx\n}", "func (_IUniswapV2Pair *IUniswapV2PairCallerSession) KLast() (*big.Int, error) {\r\n\treturn _IUniswapV2Pair.Contract.KLast(&_IUniswapV2Pair.CallOpts)\r\n}", "func (m *OrderedMap[K, V]) Max() *OrderedMapElement[K, V] {\n\treturn m.max(nil)\n}", "func NextLargerKey(key string) string {\n\treturn key + \"\\x00\" // the next string that is larger than key, but smaller than any other keys > key\n}" ]
[ "0.64017457", "0.63471687", "0.5947757", "0.5752474", "0.56805396", "0.55782866", "0.5567208", "0.55566853", "0.5465598", "0.54230475", "0.5320258", "0.53081363", "0.52548325", "0.52321553", "0.51663005", "0.515594", "0.51534414", "0.5117315", "0.5105535", "0.5103728", "0.5066215", "0.5051428", "0.49883723", "0.49680877", "0.4918796", "0.48976338", "0.48824608", "0.48644868", "0.48408487", "0.48233145", "0.48196343", "0.48148632", "0.48089647", "0.48060033", "0.48034284", "0.4797153", "0.4790417", "0.4777355", "0.4741937", "0.47248837", "0.4724738", "0.4721507", "0.4714758", "0.46947756", "0.46870172", "0.4661575", "0.46531954", "0.46435317", "0.46275347", "0.46275347", "0.46079528", "0.4576393", "0.456697", "0.45637247", "0.45523494", "0.4542613", "0.4530932", "0.45264518", "0.4508717", "0.45081908", "0.45030898", "0.4498837", "0.4496378", "0.44925576", "0.4483645", "0.44788378", "0.44483516", "0.4437768", "0.44250444", "0.44210643", "0.44064808", "0.4399684", "0.43917146", "0.43910456", "0.43669796", "0.4348235", "0.4347853", "0.43449336", "0.43229994", "0.43086445", "0.4304247", "0.42946216", "0.42764285", "0.42697185", "0.42643636", "0.42601842", "0.4248395", "0.423215", "0.4225136", "0.4218835", "0.41982841", "0.41920185", "0.4188973", "0.41654685", "0.41648984", "0.41627952", "0.41596484", "0.41397256", "0.41381666", "0.41349587" ]
0.76495737
0
MinKey returns the minimum key having the given searchPrefix, or the minimum key in the whole index if searchIndex is nil. Minimum means the first key in the lexicographic order. If keys are uint64 in BigEndian it is also the smallest number. If ok is false the index is empty.
MinKey возвращает минимальный ключ, соответствующий заданному searchPrefix, или минимальный ключ в целом по индексу, если searchIndex равен nil. Минимальным считается первый ключ в лексикографическом порядке. Если ключи являются uint64 в формате BigEndian, это также наименьшее число. Если ok имеет значение false, индекс пуст.
func (idx *Tree) MinKey(searchPrefix []byte) (v uint64, ok bool) { raw, _ := idx.partialSearch(searchPrefix) if raw == 0 { return 0, false } if isLeaf(raw) { return getLeafValue(raw), true } // now find the min searchLoop: for { _, node, count, prefixLen := explodeNode(raw) block := int(node >> blockSlotsShift) offset := int(node & blockSlotsOffsetMask) data := idx.blocks[block].data[offset:] var prefixSlots int if prefixLen > 0 { if prefixLen == 255 { prefixLen = int(data[0]) prefixSlots = (prefixLen + 15) >> 3 } else { prefixSlots = (prefixLen + 7) >> 3 } data = data[prefixSlots:] } if count >= fullAllocFrom { // find min, iterate from bottom for k := range data[:count] { a := atomic.LoadUint64(&data[k]) if a != 0 { if isLeaf(a) { return getLeafValue(a), true } raw = a continue searchLoop } } // BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree! return 0, false } // load first child (since they are ordered) a := atomic.LoadUint64(&data[0]) if isLeaf(a) { return getLeafValue(a), true } raw = a } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (tf tFiles) searchMin(icmp *iComparer, ikey internalKey) int {\n\treturn sort.Search(len(tf), func(i int) bool {\n\t\treturn icmp.Compare(tf[i].imin, ikey) >= 0\n\t})\n}", "func (t *binarySearchST) Min() interface{} {\n\tutils.AssertF(!t.IsEmpty(), \"called Min() with empty symbol table\")\n\treturn t.keys[0]\n}", "func MinKey() Val { return Val{t: bsontype.MinKey} }", "func (t *BinarySearch[T]) Min() (T, bool) {\n\tret := minimum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}", "func (this *AllOne) GetMinKey() string {\n\tif this.head.next != this.tail {\n\t\tfor k := range this.head.next.keys {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn \"\"\n}", "func (this *AllOne) GetMinKey() string {\n\tif this.Tail.Pre != this.Head {\n\t\tnmap := this.Tail.Pre.NodeMap\n\t\tret := \"\"\n\t\tfor k, _ := range nmap {\n\t\t\tret = k\n\t\t\tbreak\n\t\t}\n\t\treturn ret\n\t}\n\n\treturn \"\"\n}", "func (this *AllOne) GetMinKey() string {\n if len(this.m) == 0{\n return \"\"\n }\n return this.g[this.min][0].k\n}", "func (this *AllOne) GetMinKey() string {\n\tif this.tail == nil {\n\t\treturn \"\"\n\t}\n\tfor k := range this.tail.set {\n\t\treturn k\n\t}\n\treturn \"ERROR\"\n}", "func (vm *FstVM) PrefixSearch(input string) (int, []string) {\n\ttape, snap, _ := vm.run(input)\n\tif len(snap) == 0 {\n\t\treturn -1, nil\n\t}\n\tc := snap[len(snap)-1]\n\tpc := c.pc\n\tsz := int(vm.prog[pc] & valMask)\n\tpc++\n\tif sz == 0 {\n\t\treturn c.inp, []string{string(tape[0:c.tape])}\n\t}\n\ts := toInt(vm.prog[pc : pc+sz])\n\tpc += sz\n\tsz = int(vm.prog[pc])\n\tpc++\n\te := toInt(vm.prog[pc : pc+sz])\n\tvar outs []string\n\tfor i := s; i < e; i++ {\n\t\th := i\n\t\tfor vm.data[i] != 0 {\n\t\t\ti++\n\t\t}\n\t\tt := append(tape[0:c.tape], vm.data[h:i]...)\n\t\touts = append(outs, string(t))\n\t}\n\tpc += sz\n\treturn c.inp, outs\n}", "func (t *Trie) GetShortestPrefix(key string) interface{} {\n\treturn t.getShortestPrefix(key, false)\n}", "func (p *partitionImpl) FindFirstKey(key uint64) (int, error) {\n\tl := 0\n\tr := p.GetNumRows() - 1\n\tfor l <= r {\n\t\tm := (l + r) >> 1\n\t\tif key > p.keys[m] {\n\t\t\tl = m + 1\n\t\t} else if key < p.keys[m] {\n\t\t\tr = m - 1\n\t\t} else if l != m {\n\t\t\tr = m\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif l < len(p.keys) && key == p.keys[l] {\n\t\treturn l, nil\n\t}\n\treturn l, errors.MissingKeyError{}\n}", "func (st *RedBlackBST) Min() Key {\n\tif st.IsEmpty() {\n\t\tpanic(\"call Min on empty RedBlackbst\")\n\t}\n\treturn st.min(st.root).key\n}", "func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) {\n\tvar last *leafNode\n\tsearch := k\n\tfor {\n\t\t// Look for a leaf node\n\t\tif n.isLeaf() {\n\t\t\tlast = n.leaf\n\t\t}\n\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif last != nil {\n\t\treturn last.key, last.val, true\n\t}\n\treturn nil, nil, false\n}", "func FindKthMin(nums []int, k int) (int, error) {\n\tindex := k - 1\n\treturn kthNumber(nums, index)\n}", "func (tree *avlBetterTree) MinKey() (key string, value interface{}, exist bool) {\n\ttree.Lock()\n\tdefer tree.Unlock()\n\tif tree.root == nil {\n\t\t// 如果是空树,返回空\n\t\treturn\n\t}\n\n\tnode := tree.root.minNode()\n\treturn node.k, node.v, true\n}", "func (t *BoundedTable) IndexPrefix() kv.Key {\n\treturn nil\n}", "func lowestMatch(op string) int {\n\tfor i, prec := range precs {\n\t\tfor _, op2 := range prec {\n\t\t\tif op == op2 {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func (n *Node) Min() int {\n\tif n.Left == nil {\n\t\treturn n.Key\n\t}\n\treturn n.Left.Min()\n}", "func (s *Store) FindPrefix(bucket, prefix []byte, next func(key, val []byte) bool) error {\n\treturn s.db.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket(bucket).Cursor()\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tif !next(k, v) {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (t *Trie) GetShortestPrefixRK(key string) interface{} {\n\treturn t.getShortestPrefix(key, true)\n}", "func (n *Node) Minimum() ([]byte, interface{}, bool) {\n\tfor {\n\t\tif n.isLeaf() {\n\t\t\treturn n.leaf.key, n.leaf.val, true\n\t\t}\n\t\tif len(n.edges) > 0 {\n\t\t\tn = n.edges[0].node\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil, nil, false\n}", "func (bst *BinarySearch) Min() (int, error) {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\n\tn := bst.root\n\tif n == nil {\n\t\treturn 0, fmt.Errorf(\"min: no nodes exist in tree\")\n\t}\n\tfor {\n\t\tif n.left == nil {\n\t\t\treturn n.value, nil\n\t\t}\n\t\tn = n.left\n\t}\n}", "func (bst *StringBinarySearchTree) Min() *string {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\tn := bst.root\n\tif n == nil {\n\t\treturn nil\n\t}\n\tfor {\n\t\tif n.left == nil {\n\t\t\treturn &n.value\n\t\t}\n\t\tn = n.left\n\t}\n}", "func (n *Node) min() int {\n\tif n.left == nil {\n\t\treturn n.key\n\t}\n\treturn n.left.min()\n}", "func (t *ArtTree) PrefixSearch(key []byte) []interface{} {\n\tret := make([]interface{}, 0)\n\tfor r := range t.PrefixSearchChan(key) {\n\t\tret = append(ret, r.Value)\n\t}\n\treturn ret\n}", "func searchInSparseIndex(r io.Reader, searchKey []byte) (int, int, bool, error) {\n\tfrom := -1\n\tfor {\n\t\tkey, value, err := decode(r)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn 0, 0, false, fmt.Errorf(\"failed to read: %w\", err)\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn from, 0, from != -1, nil\n\t\t}\n\t\toffset := decodeInt(value)\n\n\t\tcmp := bytes.Compare(key, searchKey)\n\t\tif cmp == 0 {\n\t\t\treturn offset, offset, true, nil\n\t\t} else if cmp < 0 {\n\t\t\tfrom = offset\n\t\t} else if cmp > 0 {\n\t\t\tif from == -1 {\n\t\t\t\t// if the first key in the sparse index is larger than\n\t\t\t\t// the search key, it means there is no key\n\t\t\t\treturn 0, 0, false, nil\n\t\t\t} else {\n\t\t\t\treturn from, offset, true, nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (vt *perfSchemaTable) IndexPrefix() kv.Key {\n\treturn nil\n}", "func (s *GoSort) FindMinElementAndIndex() (interface{}, int) {\n var index = 0\n \n for i := 1; i < s.Len(); i++ {\n if s.LessThan(i, index) {\n index = i\n }\n }\n return s.values[index], index\n}", "func (sk *SkipList) PrefixScan(prefix store.Key, n int) []interface{} {\n\tx := sk.head\n\tfor i := sk.level - 1; i >= 0; i-- {\n\t\tfor x.next[i] != nil && x.next[i].key.Less(prefix) {\n\t\t\tx = x.next[i]\n\t\t}\n\t}\n\t//now x is the biggest element which is less than key\n\tx = x.next[0]\n\tvar res []interface{}\n\tfor n > 0 && x != nil && x.key.HasPrefix(prefix) {\n\t\tres = append(res, x.key)\n\t\tn--\n\t\tx = x.next[0]\n\t}\n\treturn res\n}", "func (t *Tree)FindMin()(int,bool){\n\tcurr := t.root\n\tif curr==nil{\n\t\treturn 0,false\n\t}\n\tfor curr.left !=nil{\n\t\tcurr = curr.left\n\t}\n\treturn curr.data,true\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (t *tableCommon) FirstKey() kv.Key {\n\ttrace_util_0.Count(_tables_00000, 64)\n\treturn t.RecordKey(math.MinInt64)\n}", "func (idx *Tree) MaxKey(searchPrefix []byte) (v uint64, ok bool) {\n\traw, _ := idx.partialSearch(searchPrefix)\n\tif raw == 0 {\n\t\treturn 0, false\n\t}\n\tif isLeaf(raw) {\n\t\treturn getLeafValue(raw), true\n\t}\n\t// now find the max\nsearchLoop:\n\tfor {\n\t\t_, node, count, prefixLen := explodeNode(raw)\n\t\tblock := int(node >> blockSlotsShift)\n\t\toffset := int(node & blockSlotsOffsetMask)\n\t\tdata := idx.blocks[block].data[offset:]\n\t\tvar prefixSlots int\n\t\tif prefixLen > 0 {\n\t\t\tif prefixLen == 255 {\n\t\t\t\tprefixLen = int(data[0])\n\t\t\t\tprefixSlots = (prefixLen + 15) >> 3\n\t\t\t} else {\n\t\t\t\tprefixSlots = (prefixLen + 7) >> 3\n\t\t\t}\n\t\t\tdata = data[prefixSlots:]\n\t\t}\n\t\tif count >= fullAllocFrom {\n\t\t\t// find max, iterate from top\n\t\t\tfor k := 255; k >= 0; k-- {\n\t\t\t\ta := atomic.LoadUint64(&data[k])\n\t\t\t\tif a != 0 {\n\t\t\t\t\tif isLeaf(a) {\n\t\t\t\t\t\treturn getLeafValue(a), true\n\t\t\t\t\t}\n\t\t\t\t\traw = a\n\t\t\t\t\tcontinue searchLoop\n\t\t\t\t}\n\t\t\t}\n\t\t\t// BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree!\n\t\t\treturn 0, false\n\t\t}\n\t\t// load the last child (since they are ordered)\n\t\ta := atomic.LoadUint64(&data[count-1])\n\t\tif isLeaf(a) {\n\t\t\treturn getLeafValue(a), true\n\t\t}\n\t\traw = a\n\t}\n}", "func (t *BinarySearchTree) FindMin() int {\n\tnode := t.root\n\tfor {\n\t\tif node.left != nil {\n\t\t\tnode = node.left\n\t\t} else {\n\t\t\treturn node.data\n\t\t}\n\t}\n}", "func (t *RbTree[K, V]) FindLowerBoundNode(key K) *Node[K, V] {\n\treturn t.findLowerBoundNode(t.root, key)\n}", "func (l *LevelDB) FirstIndex() (uint64, error) {\n\titer := l.db.NewIterator(&util.Range{Start: nil, Limit: nil}, nil)\n\tdefer iter.Release()\n\n\tfor iter.Next() {\n\t\tkey := binary.LittleEndian.Uint64(iter.Key())\n\t\treturn key, nil\n\t}\n\n\treturn 0, nil\n}", "func prefixIndex(addr uint8, prefixLen int) int {\n\t// the prefixIndex of addr/prefixLen is the prefixLen most significant bits\n\t// of addr, with a 1 tacked onto the left-hand side. For example:\n\t//\n\t// - 0/0 is 1: 0 bits of the addr, with a 1 tacked on\n\t// - 42/8 is 1_00101010 (298): all bits of 42, with a 1 tacked on\n\t// - 48/4 is 1_0011 (19): 4 most-significant bits of 48, with a 1 tacked on\n\treturn (int(addr) >> (8 - prefixLen)) + (1 << prefixLen)\n}", "func (tree *RedBlack[K, V]) Min() (v alg.Pair[K, V], ok bool) {\n\tif min := tree.root.min(); min != nil {\n\t\treturn alg.Two(min.key, min.value), true\n\t}\n\treturn\n}", "func (i *InmemStore) FirstIndex() (uint64, error) {\n\ti.l.RLock()\n\tdefer i.l.RUnlock()\n\treturn i.lowIndex, nil\n}", "func (m *Memory) FirstIndex() (uint64, error) {\n\tfirst := m.kvstore[KeyFirstIndex]\n\treturn first, nil\n}", "func longestPrefix(k1, k2 []byte) int {\n\tlimit := min(len(k1), len(k2))\n\tfor i := 0; i < limit; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn limit\n}", "func ExampleClient_TdMin() {\n\thost := \"localhost:6379\"\n\tvar client = redisbloom.NewClient(host, \"nohelp\", nil)\n\n\tkey := \"example\"\n\t_, err := client.TdCreate(key, 10)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tsamples := map[float64]float64{1.0: 1.0, 2.0: 2.0, 3.0: 3.0}\n\t_, err = client.TdAdd(key, samples)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tmin, err := client.TdMin(key)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(min)\n\t// Output: 1\n}", "func (c *Client) WatchPrefix(ctx context.Context, prefix string, opts ...easykv.WatchOption) (uint64, error) {\n\tvar options easykv.WatchOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\trespChan := make(chan watchResponse)\n\tgo func() {\n\t\topts := api.QueryOptions{\n\t\t\tWaitIndex: options.WaitIndex,\n\t\t}\n\t\t_, meta, err := c.client.List(prefix, &opts)\n\t\tif err != nil {\n\t\t\trespChan <- watchResponse{options.WaitIndex, err}\n\t\t\treturn\n\t\t}\n\t\trespChan <- watchResponse{meta.LastIndex, err}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn options.WaitIndex, easykv.ErrWatchCanceled\n\t\tcase r := <-respChan:\n\t\t\treturn r.waitIndex, r.err\n\t\t}\n\t}\n}", "func (t *Table) Smallest() y.Key { return t.smallest }", "func (t *BPTree) PrefixSearchScan(prefix []byte, reg string, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\trgx, err := regexp.Compile(reg)\n\tif err != nil {\n\t\treturn nil, off, ErrBadRegexp\n\t}\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixSearchScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !rgx.Match(bytes.TrimPrefix(n.Keys[i], prefix)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (c *KVClient) PathPrefixSearch(prefix string) (map[string]*domain.Package, error) {\n\tpkgs := map[string]*domain.Package{}\n\terr := c.be.Update(func(tx Transaction) error {\n\t\tvar (\n\t\t\tprefixBs = []byte(prefix)\n\t\t\tcursor = tx.Cursor(TablePackages)\n\t\t\terrs = []error{}\n\t\t)\n\t\tdefer cursor.Close()\n\t\tfor k, v := cursor.Seek(prefixBs).Data(); cursor.Err() == nil && k != nil && bytes.HasPrefix(k, prefixBs); k, v = cursor.Next().Data() {\n\t\t\tpkg := &domain.Package{}\n\t\t\tif err := proto.Unmarshal(v, pkg); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpkgs[pkg.Path] = pkg\n\t\t}\n\t\tif err := errorlib.Merge(errs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := cursor.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn pkgs, err\n\t}\n\tif len(pkgs) == 0 {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\treturn pkgs, nil\n}", "func SmallestWindow(s string, t string) string {\n\tstr := []byte(s)\n\ttst := []byte(t)\n\ttmap := make(map[byte]bool)\n\tfor _, val := range tst {\n\t\ttmap[val] = true\n\t}\n\ttype pair struct {\n\t\tval byte\n\t\tidx int\n\t}\n\tvar arr []pair\n\tfor idx, val := range str {\n\t\tif _, ok := tmap[val]; ok {\n\t\t\tarr = append(arr, pair{val, idx})\n\t\t}\n\t}\n\tfmt.Println(arr)\n\t//Now min window\n\tleft := 0\n\tright := 0\n\trequired := len(tmap)\n\tminwindow := math.MaxInt32\n\tvar startIdx, endIdx int\n\tkmap := make(map[byte]int)\n\n\tfor right < len(arr) {\n\t\tkmap[arr[right].val] += 1\n\t\tfmt.Println(\"Kmap Len: \", len(kmap))\n\t\tfor required == len(kmap) && left < right {\n\t\t\tfmt.Println(\"Kmap Len: \", len(kmap), \"Required: \", required)\n\t\t\tlength := arr[right].idx - arr[left].idx\n\n\t\t\tif minwindow > length {\n\t\t\t\tminwindow = length\n\t\t\t\tstartIdx = arr[left].idx\n\t\t\t\tendIdx = arr[right].idx\n\t\t\t}\n\t\t\tkmap[arr[left].val] -= 1\n\t\t\tif kmap[arr[left].val] == 0 {\n\t\t\t\tdelete(kmap, arr[left].val)\n\t\t\t}\n\t\t\tleft++\n\t\t}\n\t\tright++\n\t}\n\treturn string(str[startIdx : endIdx+1])\n}", "func prefixIsLessThan(b []byte, s string) bool {\n\tfor i := 0; i < len(s); i++ {\n\t\tif i >= len(b) {\n\t\t\treturn true\n\t\t}\n\t\tif b[i] != s[i] {\n\t\t\treturn b[i] < s[i]\n\t\t}\n\t}\n\treturn false\n}", "func (p *partitionImpl) FindFirstRowKey(keyBuf []byte, key uint64, keyfn sif.KeyingOperation) (int, error) {\n\t// find the first matching uint64 key\n\tfirstKey, err := p.FindFirstKey(key)\n\tif err != nil {\n\t\treturn firstKey, err\n\t}\n\t// iterate over each row with a matching key to find the first one with identical key bytes\n\tfor i := firstKey; i < p.GetNumRows(); i++ {\n\t\tif k, err := p.GetKey(i); err != nil || k != key {\n\t\t\treturn -1, err\n\t\t}\n\t\trowKey, err := keyfn(&rowImpl{\n\t\t\tmeta: p.GetRowMeta(i),\n\t\t\tdata: p.GetRowData(i),\n\t\t\tvarData: p.GetVarRowData(i),\n\t\t\tserializedVarData: p.GetSerializedVarRowData(i),\n\t\t\tschema: p.GetCurrentSchema(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t} else if reflect.DeepEqual(keyBuf, rowKey) {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn firstKey, errors.MissingKeyError{}\n}", "func (na *NArray) MinIdx() (float32, []int) {\n\n\tvar offset int\n\tmin := float32(math.MaxFloat32)\n\tfor i := 0; i < len(na.Data); i++ {\n\t\tif na.Data[i] < min {\n\t\t\tmin = na.Data[i]\n\t\t\toffset = i\n\t\t}\n\t}\n\treturn min, na.ReverseIndex(offset)\n}", "func (na *NArray) Min() float32 {\n\tif na == nil || len(na.Data) == 0 {\n\t\tpanic(\"unable to take min of nil or zero-sizes array\")\n\t}\n\treturn minSliceElement(na.Data)\n}", "func (table *Table) SearchFirst(searchValues ...interface{}) (int, error) {\n\n\terr := table.checkSearchArguments(searchValues...)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\trowIndex, err := table.searchByKeysFirst(searchValues)\n\n\treturn rowIndex, err\n}", "func minIndex(slice []float64) int {\n\tif len(slice) == 0 {\n\t\treturn -1\n\t}\n\tmin := slice[0]\n\tminIndex := 0\n\tfor index := 0; index < len(slice); index++ {\n\t\tif slice[index] < min {\n\t\t\tmin = slice[index]\n\t\t\tminIndex = index\n\t\t}\n\t}\n\treturn minIndex\n}", "func (r Uint32Slice) Search(x uint32) int { return SearchUint32s(r, x) }", "func (o MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationPropertiesPtrOutput) ObjectKeyPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationProperties) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ObjectKeyPrefix\n\t}).(pulumi.StringPtrOutput)\n}", "func GetMinValue(ft *types.FieldType) (min types.Datum) {\n\tswitch ft.Tp {\n\tcase mysql.TypeTiny, mysql.TypeShort, mysql.TypeInt24, mysql.TypeLong, mysql.TypeLonglong:\n\t\tif mysql.HasUnsignedFlag(ft.Flag) {\n\t\t\tmin.SetUint64(0)\n\t\t} else {\n\t\t\tmin.SetInt64(types.IntergerSignedLowerBound(ft.Tp))\n\t\t}\n\tcase mysql.TypeFloat:\n\t\tmin.SetFloat32(float32(-types.GetMaxFloat(ft.Flen, ft.Decimal)))\n\tcase mysql.TypeDouble:\n\t\tmin.SetFloat64(-types.GetMaxFloat(ft.Flen, ft.Decimal))\n\tcase mysql.TypeString, mysql.TypeVarString, mysql.TypeVarchar, mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob:\n\t\tval := types.MinNotNullDatum()\n\t\tbytes, err := codec.EncodeKey(nil, nil, val)\n\t\t// should not happen\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Error(\"encode key fail\", zap.Error(err))\n\t\t}\n\t\tmin.SetBytes(bytes)\n\tcase mysql.TypeNewDecimal:\n\t\tmin.SetMysqlDecimal(types.NewMaxOrMinDec(true, ft.Flen, ft.Decimal))\n\tcase mysql.TypeDuration:\n\t\tmin.SetMysqlDuration(types.Duration{Duration: types.MinTime})\n\tcase mysql.TypeDate, mysql.TypeDatetime, mysql.TypeTimestamp:\n\t\tif ft.Tp == mysql.TypeDate || ft.Tp == mysql.TypeDatetime {\n\t\t\tmin.SetMysqlTime(types.Time{Time: types.MinDatetime, Type: ft.Tp})\n\t\t} else {\n\t\t\tmin.SetMysqlTime(types.MinTimestamp)\n\t\t}\n\t}\n\treturn\n}", "func GetPrefixIfLocked(ctx context.Context, prefix string, lock KVLocker) (string, *string, error) {\n\tk, bv, err := Client().GetPrefixIfLocked(ctx, prefix, lock)\n\tTrace(\"GetPrefixIfLocked\", err, logrus.Fields{fieldPrefix: prefix, fieldKey: k, fieldValue: string(bv)})\n\tif bv == nil {\n\t\treturn k, nil, err\n\t}\n\tv := string(bv)\n\treturn k, &v, err\n}", "func (t *BPTree) PrefixScan(prefix []byte, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (f *FibonacciHeap) FindMin() (Value, error) {\n\tif !f.IsEmpty() {\n\t\treturn f.min.key, nil\n\t} else {\n\t\treturn nil, errors.New(\"unable to get minimum from an empty heap\")\n\t}\n}", "func (b *BinarySearch) kthSmallest(matrix [][]int, k int) int {\n\tm, n := len(matrix), len(matrix[0])\n\tl, h := matrix[0][0], matrix[m-1][n-1]\n\n\tvar mid int\n\tvar cnt int\n\tfor l <= h {\n\t\tmid = l + (h-l)/2\n\t\tcnt = 0\n\t\tfor i := 0; i < m; i++ {\n\t\t\tfor j := 0; j < n && matrix[i][j] <= mid; j++ {\n\t\t\t\tcnt++\n\t\t\t}\n\t\t}\n\t\tif cnt < k {\n\t\t\tl = mid + 1\n\t\t} else {\n\t\t\th = mid - 1\n\t\t}\n\t}\n\treturn l\n}", "func MinUint32(x, min uint32) uint32 { return x }", "func (o DatabaseOutput) KeyPrefix() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Database) pulumi.StringOutput { return v.KeyPrefix }).(pulumi.StringOutput)\n}", "func (t *Indexed) Min(i, j int) int {\n\treturn -1\n}", "func RoundMin(k float64) MinFunc {\n\treturn func(a, b float64) float64 {\n\t\tu := V2{k - a, k - b}.Max(V2{0, 0})\n\t\treturn Max(k, Min(a, b)) - u.Length()\n\t}\n}", "func (da *DoubleArray) PrefixLookup(key string) ([]string, []int) {\n\tkeys := make([]string, 0)\n\tvalues := make([]int, 0)\n\n\tnpos := 0\n\tdepth := 0\n\n\tfor ; depth < len(key); depth++ {\n\t\tif da.array[npos].base < 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tbase := da.array[npos].base\n\n\t\tif da.array[base].check == npos {\n\t\t\tkeys = append(keys, key[:depth])\n\t\t\tvalues = append(values, da.array[base].base)\n\t\t}\n\n\t\tcpos := base ^ int(key[depth])\n\t\tif da.array[cpos].check != npos {\n\t\t\treturn keys, values\n\t\t}\n\t\tnpos = cpos\n\t}\n\n\tbase := da.array[npos].base\n\n\tif base >= 0 {\n\t\tif da.array[base].check == npos {\n\t\t\tkeys = append(keys, key[:depth])\n\t\t\tvalues = append(values, da.array[base].base)\n\t\t}\n\t\treturn keys, values\n\t}\n\n\ttpos := -base\n\tfor ; depth < len(key); depth++ {\n\t\tif da.tail[tpos] != key[depth] {\n\t\t\treturn keys, values\n\t\t}\n\t\ttpos++\n\t}\n\n\tif da.tail[tpos] == terminator {\n\t\tkeys = append(keys, key[:depth])\n\t\tvalues = append(values, da.getValue(tpos+1))\n\t}\n\n\treturn keys, values\n}", "func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {\n\tsearch := prefix\n\tfor {\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\n\t\t} else if bytes.HasPrefix(n.prefix, search) {\n\t\t\t// Child may be under our search prefix\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func KeyLT(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.LT(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func MinPos32(a, b float32) float32 {\n\tif a > 0.0 && b > 0.0 {\n\t\treturn Min32(a, b)\n\t} else if a > 0.0 {\n\t\treturn a\n\t} else if b > 0.0 {\n\t\treturn b\n\t}\n\treturn a\n}", "func (i *blockIter) SeekLT(key []byte, flags base.SeekLTFlags) (*InternalKey, base.LazyValue) {\n\tif invariants.Enabled && i.isDataInvalidated() {\n\t\tpanic(errors.AssertionFailedf(\"invalidated blockIter used\"))\n\t}\n\n\ti.clearCache()\n\t// Find the index of the smallest restart point whose key is >= the key\n\t// sought; index will be numRestarts if there is no such restart point.\n\ti.offset = 0\n\tvar index int32\n\n\t{\n\t\t// NB: manually inlined sort.Search is ~5% faster.\n\t\t//\n\t\t// Define f(-1) == false and f(n) == true.\n\t\t// Invariant: f(index-1) == false, f(upper) == true.\n\t\tupper := i.numRestarts\n\t\tfor index < upper {\n\t\t\th := int32(uint(index+upper) >> 1) // avoid overflow when computing h\n\t\t\t// index ≤ h < upper\n\t\t\toffset := decodeRestart(i.data[i.restarts+4*h:])\n\t\t\t// For a restart point, there are 0 bytes shared with the previous key.\n\t\t\t// The varint encoding of 0 occupies 1 byte.\n\t\t\tptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(offset+1))\n\n\t\t\t// Decode the key at that restart point, and compare it to the key\n\t\t\t// sought. See the comment in readEntry for why we manually inline the\n\t\t\t// varint decoding.\n\t\t\tvar v1 uint32\n\t\t\tif a := *((*uint8)(ptr)); a < 128 {\n\t\t\t\tv1 = uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 1)\n\t\t\t} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {\n\t\t\t\tv1 = uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 2)\n\t\t\t} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {\n\t\t\t\tv1 = uint32(c)<<14 | uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 3)\n\t\t\t} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {\n\t\t\t\tv1 = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 4)\n\t\t\t} else {\n\t\t\t\td, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))\n\t\t\t\tv1 = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 5)\n\t\t\t}\n\n\t\t\tif *((*uint8)(ptr)) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 1)\n\t\t\t} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 2)\n\t\t\t} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 3)\n\t\t\t} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 4)\n\t\t\t} else {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 5)\n\t\t\t}\n\n\t\t\t// Manually inlining part of base.DecodeInternalKey provides a 5-10%\n\t\t\t// speedup on BlockIter benchmarks.\n\t\t\ts := getBytes(ptr, int(v1))\n\t\t\tvar k []byte\n\t\t\tif n := len(s) - 8; n >= 0 {\n\t\t\t\tk = s[:n:n]\n\t\t\t}\n\t\t\t// Else k is invalid, and left as nil\n\n\t\t\tif i.cmp(key, k) > 0 {\n\t\t\t\t// The search key is greater than the user key at this restart point.\n\t\t\t\t// Search beyond this restart point, since we are trying to find the\n\t\t\t\t// first restart point with a user key >= the search key.\n\t\t\t\tindex = h + 1 // preserves f(i-1) == false\n\t\t\t} else {\n\t\t\t\t// k >= search key, so prune everything after index (since index\n\t\t\t\t// satisfies the property we are looking for).\n\t\t\t\tupper = h // preserves f(j) == true\n\t\t\t}\n\t\t}\n\t\t// index == upper, f(index-1) == false, and f(upper) (= f(index)) == true\n\t\t// => answer is index.\n\t}\n\n\t// index is the first restart point with key >= search key. Define the keys\n\t// between a restart point and the next restart point as belonging to that\n\t// restart point. Note that index could be equal to i.numRestarts, i.e., we\n\t// are past the last restart.\n\t//\n\t// Since keys are strictly increasing, if index > 0 then the restart point\n\t// at index-1 will be the first one that has some keys belonging to it that\n\t// are less than the search key. If index == 0, then all keys in this block\n\t// are larger than the search key, so there is no match.\n\ttargetOffset := i.restarts\n\tif index > 0 {\n\t\ti.offset = decodeRestart(i.data[i.restarts+4*(index-1):])\n\t\tif index < i.numRestarts {\n\t\t\ttargetOffset = decodeRestart(i.data[i.restarts+4*(index):])\n\t\t}\n\t} else if index == 0 {\n\t\t// If index == 0 then all keys in this block are larger than the key\n\t\t// sought.\n\t\ti.offset = -1\n\t\ti.nextOffset = 0\n\t\treturn nil, base.LazyValue{}\n\t}\n\n\t// Iterate from that restart point to somewhere >= the key sought, then back\n\t// up to the previous entry. The expectation is that we'll be performing\n\t// reverse iteration, so we cache the entries as we advance forward.\n\ti.nextOffset = i.offset\n\n\tfor {\n\t\ti.offset = i.nextOffset\n\t\ti.readEntry()\n\t\t// When hidden keys are common, there is additional optimization possible\n\t\t// by not caching entries that are hidden (note that some calls to\n\t\t// cacheEntry don't decode the internal key before caching, but checking\n\t\t// whether a key is hidden does not require full decoding). However, we do\n\t\t// need to use the blockEntry.offset in the cache for the first entry at\n\t\t// the reset point to do the binary search when the cache is empty -- so\n\t\t// we would need to cache that first entry (though not the key) even if\n\t\t// was hidden. Our current assumption is that if there are large numbers\n\t\t// of hidden keys we will be able to skip whole blocks (using block\n\t\t// property filters) so we don't bother optimizing.\n\t\thiddenPoint := i.decodeInternalKey(i.key)\n\n\t\t// NB: we don't use the hiddenPoint return value of decodeInternalKey\n\t\t// since we want to stop as soon as we reach a key >= ikey.UserKey, so\n\t\t// that we can reverse.\n\t\tif i.cmp(i.ikey.UserKey, key) >= 0 {\n\t\t\t// The current key is greater than or equal to our search key. Back up to\n\t\t\t// the previous key which was less than our search key. Note that this for\n\t\t\t// loop will execute at least once with this if-block not being true, so\n\t\t\t// the key we are backing up to is the last one this loop cached.\n\t\t\treturn i.Prev()\n\t\t}\n\n\t\tif i.nextOffset >= targetOffset {\n\t\t\t// We've reached the end of the current restart block. Return the\n\t\t\t// current key if not hidden, else call Prev().\n\t\t\t//\n\t\t\t// When the restart interval is 1, the first iteration of the for loop\n\t\t\t// will bring us here. In that case ikey is backed by the block so we\n\t\t\t// get the desired key stability guarantee for the lifetime of the\n\t\t\t// blockIter. That is, we never cache anything and therefore never\n\t\t\t// return a key backed by cachedBuf.\n\t\t\tif hiddenPoint {\n\t\t\t\treturn i.Prev()\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\ti.cacheEntry()\n\t}\n\n\tif !i.valid() {\n\t\treturn nil, base.LazyValue{}\n\t}\n\tif !i.lazyValueHandling.hasValuePrefix ||\n\t\tbase.TrailerKind(i.ikey.Trailer) != InternalKeyKindSet {\n\t\ti.lazyValue = base.MakeInPlaceValue(i.val)\n\t} else if i.lazyValueHandling.vbr == nil || !isValueHandle(valuePrefix(i.val[0])) {\n\t\ti.lazyValue = base.MakeInPlaceValue(i.val[1:])\n\t} else {\n\t\ti.lazyValue = i.lazyValueHandling.vbr.getLazyValueForPrefixAndValueHandle(i.val)\n\t}\n\treturn &i.ikey, i.lazyValue\n}", "func (o MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationPropertiesOutput) ObjectKeyPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationProperties) *string {\n\t\treturn v.ObjectKeyPrefix\n\t}).(pulumi.StringPtrOutput)\n}", "func WithCursorHintPrefix(prefix string) CursorHint {\n\treturn func(o *CursorHints) {\n\t\to.KeyPrefix = &prefix\n\t}\n}", "func Min(Len int, Less func(i, j int) bool) int {\n\tmn := 0\n\tfor i := 1; i < Len; i++ {\n\t\tif Less(i, mn) {\n\t\t\tmn = i\n\t\t}\n\t}\n\treturn mn\n}", "func (t *tableCommon) IndexPrefix() kv.Key {\n\ttrace_util_0.Count(_tables_00000, 62)\n\treturn t.indexPrefix\n}", "func minNamespace(hash []byte, size namespace.IDSize) []byte {\n\tmin := make([]byte, 0, size)\n\treturn append(min, hash[:size]...)\n}", "func (klq *K8sLabelQuery) FirstIDX(ctx context.Context) uint {\n\tid, err := klq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func MinInt32(x, min int32) int32 { return x }", "func (i *blockIter) SeekPrefixGE(\n\tprefix, key []byte, flags base.SeekGEFlags,\n) (*base.InternalKey, base.LazyValue) {\n\t// This should never be called as prefix iteration is handled by sstable.Iterator.\n\tpanic(\"pebble: SeekPrefixGE unimplemented\")\n}", "func (n *nodeHeader) prefix() []byte {\n\tpLen, pBytes := n.prefixFields()\n\n\tif *pLen <= maxPrefixLen {\n\t\t// We have the whole prefix from the node\n\t\treturn pBytes[0:*pLen]\n\t}\n\n\t// Prefix is too long for node, we have to go find it from the leaf\n\tminLeaf := n.minChild().leafNode()\n\treturn minLeaf.key[0:*pLen]\n}", "func readableGetSmallest(r *ring.Ring) (float64, error) {\n // index 0 = smallest\n // index 1 = second smallest\n // index 2 = third smallest\n var index int = 0\n return flexibleGetSmallest(r, index)\n}", "func getStartIndex(st int32, a []int32) int {\n\tif st <= a[0] {\n\t\treturn 0 // st a[0]......a[len(a) - 1]\n\t}\n\tif st == a[len(a)-1] {\n\t\treturn len(a) - 1\n\t}\n\tif st > a[len(a)-1] {\n\t\treturn -1 // a[0]......a[len(a) - 1] st\n\t}\n\treturn sort.Search(len(a), func(i int) bool {\n\t\treturn a[i] >= st // a[0], a[1], st, a[2], a[3]....a[len(a) - 1]\n\t})\n}", "func searchToken(tokens []uint32, key uint32) int {\n\ti := sort.Search(len(tokens), func(x int) bool {\n\t\treturn tokens[x] > key\n\t})\n\tif i >= len(tokens) {\n\t\ti = 0\n\t}\n\treturn i\n}", "func Min(a, b uint32) uint32 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func (c *Signature) Min() int {\n\tif c.MinValue == nil {\n\t\treturn 0\n\t}\n\treturn toolbox.AsInt(c.MinValue)\n}", "func (t *tree) longestPrefix(k1, k2 string) int {\n\tmax := len(k1)\n\tif l := len(k2); l < max {\n\t\tmax = l\n\t}\n\tvar i int\n\tfor i = 0; i < max; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn i\n}", "func (ksq *KqiSourceQuery) FirstIDX(ctx context.Context) int {\n\tid, err := ksq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (o ClusterNodeGroupOptionsPtrOutput) MinSize() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ClusterNodeGroupOptions) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MinSize\n\t}).(pulumi.IntPtrOutput)\n}", "func (km KeyValueMap) Prefix() string {\n\treturn km[kmPrefix]\n}", "func (i *BTreeIndex) Keys(from string, n int) []string {\r\n\ti.RLock()\r\n\tdefer i.RUnlock()\r\n\r\n\tif i.BTree == nil || i.LessFunction == nil {\r\n\t\tpanic(\"uninitialized index\")\r\n\t}\r\n\r\n\tif i.BTree.Len() <= 0 {\r\n\t\treturn []string{}\r\n\t}\r\n\r\n\tbtreeFrom := btreeString{s: from, l: i.LessFunction}\r\n\tskipFirst := true\r\n\tif len(from) <= 0 || !i.BTree.Has(btreeFrom) {\r\n\t\t// no such key, so fabricate an always-smallest item\r\n\t\tbtreeFrom = btreeString{s: \"\", l: func(string, string) bool { return true }}\r\n\t\tskipFirst = false\r\n\t}\r\n\r\n\tkeys := []string{}\r\n\titerator := func(i btree.Item) bool {\r\n\t\tkeys = append(keys, i.(btreeString).s)\r\n\t\treturn len(keys) < n\r\n\t}\r\n\ti.BTree.AscendGreaterOrEqual(btreeFrom, iterator)\r\n\r\n\tif skipFirst && len(keys) > 0 {\r\n\t\tkeys = keys[1:]\r\n\t}\r\n\r\n\treturn keys\r\n}", "func (o BucketLifecycleRuleItemConditionPtrOutput) MatchesPrefix() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *BucketLifecycleRuleItemCondition) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MatchesPrefix\n\t}).(pulumi.StringArrayOutput)\n}", "func kthSmallest(root *TreeNode, k int) int {\n\tif root == nil {\n\t\treturn -1\n\t}\n\n\tarr := make([]int, 0)\n\tinorder230(root, &arr, k)\n\treturn arr[k-1]\n}", "func BinarySearch(src []int, key int) bool {\n\tstart := 0\n\tend := len(src) - 1\n\tfor start <= end {\n\t\tmid := (start + end) / 2\n\t\ttmp := src[mid]\n\t\tif tmp == key {\n\t\t\treturn true\n\t\t} else if key < tmp {\n\t\t\tend = mid - 1\n\t\t} else {\n\t\t\tstart = mid + 1\n\t\t}\n\t}\n\treturn false\n}", "func getCommonPrefix(p []string, f []int, lmin int) string {\n r := []rune(p[f[0]])\n newR := make([]rune, lmin)\n for j := 0; j < lmin; j++ {\n newR[j] = r[j]\n }\n return string(newR)\n}", "func min_index(row []int) int {\n\tvar min int = math.MaxInt8\n\tvar ind int = -1\n\n\tfor i := 0; i < len(row); i++ {\n\t\tif row[i] < min {\n\t\t\tmin = row[i]\n\t\t\tind = i\n\t\t}\n\t}\n\n\treturn ind\n}", "func (t *BoundedTable) FirstKey() kv.Key {\n\treturn t.RecordKey(0)\n}", "func KeyHasPrefix(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.HasPrefix(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func (root *TreeNode) minValueNode() *TreeNode {\n\tif root.left == nil {\n\t\t// If no left element is available, we are at the smallest key\n\t\t// so we return ourself\n\t\treturn root\n\t}\n\n\treturn root.left.minValueNode()\n}", "func (b *raftBadger) FirstIndex() (uint64, error) {\n\tfirst := uint64(0)\n\terr := b.gs.GetStore().(*badger.DB).View(func(txn *badger.Txn) error {\n\t\tit := txn.NewIterator(badger.DefaultIteratorOptions)\n\t\tdefer it.Close()\n\t\tit.Seek(dbLogPrefix)\n\t\tif it.ValidForPrefix(dbLogPrefix) {\n\t\t\titem := it.Item()\n\t\t\tk := string(item.Key()[len(dbLogPrefix):])\n\t\t\tidx, err := strconv.ParseUint(k, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfirst = idx\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn first, nil\n}", "func ExampleUInt32_setMin() {\n\tfmt.Print(chance.UInt32(chance.SetUInt32Min(10)))\n\t// Output: 1532597480\n}", "func (o *V0037JobProperties) GetMinimumNodesOk() (*bool, bool) {\n\tif o == nil || o.MinimumNodes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.MinimumNodes, true\n}" ]
[ "0.6254368", "0.5750522", "0.57202524", "0.5673002", "0.5619895", "0.55524933", "0.5537136", "0.5501438", "0.5443638", "0.5435102", "0.540519", "0.536403", "0.53208256", "0.5270773", "0.51773477", "0.5168706", "0.5153912", "0.51201713", "0.51032627", "0.510243", "0.50744075", "0.50491226", "0.5026225", "0.49616006", "0.49611366", "0.4907176", "0.49006286", "0.48840016", "0.48546994", "0.48435682", "0.48306432", "0.48306432", "0.4823679", "0.48196402", "0.48028794", "0.47918767", "0.47632122", "0.47604445", "0.47491837", "0.47442335", "0.4735139", "0.47307506", "0.4726546", "0.47172824", "0.47132656", "0.47088352", "0.47039577", "0.46747816", "0.46317807", "0.46310413", "0.46273685", "0.46149272", "0.46140337", "0.46133894", "0.4611012", "0.4607212", "0.46057096", "0.45981407", "0.45914584", "0.45688185", "0.4557692", "0.45544726", "0.45523125", "0.4549096", "0.45374966", "0.45358345", "0.4518468", "0.45128992", "0.45086417", "0.4508342", "0.4508234", "0.44984207", "0.44957712", "0.44815263", "0.44774392", "0.44648033", "0.4462917", "0.44580716", "0.44541487", "0.44400644", "0.44393623", "0.44343975", "0.44310525", "0.4427767", "0.44251835", "0.44251296", "0.44199437", "0.44084477", "0.44069612", "0.4406752", "0.4406131", "0.44055223", "0.4391425", "0.4389563", "0.4389207", "0.43891466", "0.4388766", "0.43887168", "0.43864638", "0.43797892" ]
0.7585947
0
Count returns the number of nodes and leaves in the part of tree having the given prefix, or the whole tree if searchPrefix is nil.
Count возвращает количество узлов и листьев в части дерева, имеющей заданный префикс, или всё дерево, если searchPrefix равно nil.
func (idx *Tree) Count(searchPrefix []byte) (nodes, leaves int) { return NewCounter(idx).Count(searchPrefix) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *DB) CountPrefix(prefix interface{}, value interface{}, count *int) error {\n\treturn db.bolt.View(func(tx *bolt.Tx) error {\n\t\treturn db.CountPrefixTx(tx, prefix, value, count)\n\t})\n}", "func (db *DB) CountPrefixTx(tx *bolt.Tx, prefix interface{}, value interface{}, count *int) error {\n\t*count = 0\n\tbb := db.bucket(value)\n\tb := tx.Bucket(bb)\n\tif b == nil {\n\t\treturn nil\n\t}\n\n\tpb, err := db.encode(prefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc := b.Cursor()\n\tfor k, _ := c.Seek(pb); k != nil && bytes.HasPrefix(k, pb); k, _ = c.Next() {\n\t\t*count++\n\t}\n\treturn nil\n}", "func (n *Node) HasPrefix(prefix string) (*Node, error) {\n\tletters := []rune(prefix)\n\tcurrent := n\n\tfor i := 0; current != nil && i < len(letters); i++ {\n\t\tcurrent = current.GetChild(letters[i])\n\t}\n\tif current == nil {\n\t\terr := fmt.Errorf(\"%s not found\", prefix)\n\t\treturn nil, err\n\t}\n\treturn current, nil\n}", "func (t *Trie) FindWithPrefix(p string) (counts map[string]int) {\n\tcounts = make(map[string]int)\n\tcharIdx := p[0] - 'a'\n\tt.children[charIdx].findWithPrefix(p, &counts)\n\treturn\n}", "func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {\n\tsearch := prefix\n\tfor {\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\n\t\t} else if bytes.HasPrefix(n.prefix, search) {\n\t\t\t// Child may be under our search prefix\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (t *BPTree) PrefixScan(prefix []byte, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (t *BPTree) PrefixSearchScan(prefix []byte, reg string, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\trgx, err := regexp.Compile(reg)\n\tif err != nil {\n\t\treturn nil, off, ErrBadRegexp\n\t}\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixSearchScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !rgx.Match(bytes.TrimPrefix(n.Keys[i], prefix)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (vm *FstVM) PrefixSearch(input string) (int, []string) {\n\ttape, snap, _ := vm.run(input)\n\tif len(snap) == 0 {\n\t\treturn -1, nil\n\t}\n\tc := snap[len(snap)-1]\n\tpc := c.pc\n\tsz := int(vm.prog[pc] & valMask)\n\tpc++\n\tif sz == 0 {\n\t\treturn c.inp, []string{string(tape[0:c.tape])}\n\t}\n\ts := toInt(vm.prog[pc : pc+sz])\n\tpc += sz\n\tsz = int(vm.prog[pc])\n\tpc++\n\te := toInt(vm.prog[pc : pc+sz])\n\tvar outs []string\n\tfor i := s; i < e; i++ {\n\t\th := i\n\t\tfor vm.data[i] != 0 {\n\t\t\ti++\n\t\t}\n\t\tt := append(tape[0:c.tape], vm.data[h:i]...)\n\t\touts = append(outs, string(t))\n\t}\n\tpc += sz\n\treturn c.inp, outs\n}", "func (t *ArtTree) PrefixSearch(key []byte) []interface{} {\n\tret := make([]interface{}, 0)\n\tfor r := range t.PrefixSearchChan(key) {\n\t\tret = append(ret, r.Value)\n\t}\n\treturn ret\n}", "func (tr *d8RTree) Count() int {\n\tvar count int\n\td8countRec(tr.root, &count)\n\treturn count\n}", "func (d *Driver) Count(ctx context.Context, prefix string) (revRet int64, count int64, err error) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tdur := time.Since(start)\n\t\tfStr := \"COUNT %s => rev=%d, count=%d, err=%v, duration=%s\"\n\t\td.logMethod(dur, fStr, prefix, revRet, count, err, dur)\n\t}()\n\n\tentries, err := d.getKeys(ctx, prefix, false)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\t// current revision\n\tcurrentRev, err := d.currentRevision()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn currentRev, int64(len(entries)), nil\n}", "func (t *Trie) Search(w string) int {\n\tcur := t.root\n\tfor _, c := range []byte(w) {\n\t\ti := c - 'a'\n\t\tif cur.children[i] == nil {\n\t\t\treturn 0\n\t\t}\n\t\tcur = cur.children[i]\n\t}\n\treturn cur.count\n}", "func (n IPv4Network) GetPrefixLength() int {\n\tslice := strings.Split(n.CIDR, \"/\")\n\tlen, _ := strconv.Atoi(slice[1])\n\treturn len\n}", "func (t *Trie) HasPrefix(word string) bool {\n\tnode := t.root.nodeByPrefix(word)\n\tif node == nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.root\n for _, r := range prefix {\n child, existed := node.children[r]\n if !existed {\n return false\n }\n node = child\n }\n return true\n}", "func (tr *d19RTree) Count() int {\n\tvar count int\n\td19countRec(tr.root, &count)\n\treturn count\n}", "func (t *Trie) Len() uint32 {\n\tif t.root == nil {\n\t\treturn 0\n\t}\n\treturn t.root.count\n}", "func (tr *d10RTree) Count() int {\n\tvar count int\n\td10countRec(tr.root, &count)\n\treturn count\n}", "func (t *Tree) Count() (int, error) {\n\tif t == nil {\n\t\treturn 0, errors.New(errors.KsiInvalidArgumentError)\n\t}\n\n\treturn len(t.leafs), nil\n}", "func (tr *d3RTree) Count() int {\n\tvar count int\n\td3countRec(tr.root, &count)\n\treturn count\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (tr *d13RTree) Count() int {\n\tvar count int\n\td13countRec(tr.root, &count)\n\treturn count\n}", "func (tr *d14RTree) Count() int {\n\tvar count int\n\td14countRec(tr.root, &count)\n\treturn count\n}", "func (pf *pebbleFetcher) fetchRangeWithPrefix() (int, error) {\n\tvar lowerBound, middleBound, upperBound []byte\n\n\tif pf.opts.Prefix != \"\" {\n\t\tlowerBound = []byte(pf.opts.Prefix)\n\t\tmiddleBound = lowerBound\n\t\tupperBound = calcUpperBound(pf.opts.Prefix)\n\n\t\tif pf.opts.CurrentDir != \"\" && pf.opts.CurrentDir != pf.opts.Prefix {\n\t\t\tmiddleBound = []byte(pf.opts.CurrentDir)\n\t\t}\n\t}\n\n\tvar err error\n\tpf.count, err = pf.fetchRange(middleBound, upperBound)\n\tif err != nil {\n\t\treturn pf.count, err\n\t}\n\n\treturn pf.fetchRange(lowerBound, middleBound)\n\n}", "func (tr *d11RTree) Count() int {\n\tvar count int\n\td11countRec(tr.root, &count)\n\treturn count\n}", "func (tr *d1RTree) Count() int {\n\tvar count int\n\td1countRec(tr.root, &count)\n\treturn count\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.searchPrefix(prefix)\n \n return node != nil\n}", "func (tr *d12RTree) Count() int {\n\tvar count int\n\td12countRec(tr.root, &count)\n\treturn count\n}", "func Count(root *Node) int {\n\t// base case\n\tif root == nil{\n\t\treturn 0\n\t}\n\n\t// 自己加上子树的节点数就是整棵树的节点数\n\treturn 1 + Count(root.Left) + Count(root.Right)\n}", "func (tr *d6RTree) Count() int {\n\tvar count int\n\td6countRec(tr.root, &count)\n\treturn count\n}", "func (t *TST) Prefix(p string) []string {\n\tif p == \"\" {\n\t\treturn nil\n\t}\n\tn := t.root.get(p)\n\tif n == nil {\n\t\treturn nil // nothing has this prefix\n\t}\n\tmatches := []string{}\n\tif n.val != nil {\n\t\tmatches = append(matches, p)\n\t}\n\tn.eqkid.rprefix(p, &matches)\n\tif len(matches) > 0 {\n\t\treturn matches\n\t}\n\treturn nil\n}", "func (tr *d4RTree) Count() int {\n\tvar count int\n\td4countRec(tr.root, &count)\n\treturn count\n}", "func (q treeQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count trees rows\")\n\t}\n\n\treturn count, nil\n}", "func (c *Client) WatchPrefix(ctx context.Context, prefix string, opts ...easykv.WatchOption) (uint64, error) {\n\tvar options easykv.WatchOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\trespChan := make(chan watchResponse)\n\tgo func() {\n\t\topts := api.QueryOptions{\n\t\t\tWaitIndex: options.WaitIndex,\n\t\t}\n\t\t_, meta, err := c.client.List(prefix, &opts)\n\t\tif err != nil {\n\t\t\trespChan <- watchResponse{options.WaitIndex, err}\n\t\t\treturn\n\t\t}\n\t\trespChan <- watchResponse{meta.LastIndex, err}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn options.WaitIndex, easykv.ErrWatchCanceled\n\t\tcase r := <-respChan:\n\t\t\treturn r.waitIndex, r.err\n\t\t}\n\t}\n}", "func (t *Tree) Count() int {\n\tif t.root != nil {\n\t\treturn t.root.size\n\t}\n\n\treturn 0\n}", "func PrefixDetector(prefix string, handler Handler) Detector {\n\treturn Detector{\n\t\tNeeded: len([]byte(prefix)),\n\t\tTest: func(b []byte) bool { return string(b) == prefix },\n\t\tHandler: handler,\n\t}\n}", "func (tr *d18RTree) Count() int {\n\tvar count int\n\td18countRec(tr.root, &count)\n\treturn count\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcur := this.root\n\n\t// go through prefix\n\tfor _, c := range prefix {\n\t\t// check if in children\n\t\tif child, ok := cur.children[c]; ok {\n\t\t\t// set cur\n\t\t\tcur = child\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// no probs\n\treturn true\n}", "func (o NetworkInterfaceOutput) Ipv4PrefixCount() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.IntPtrOutput { return v.Ipv4PrefixCount }).(pulumi.IntPtrOutput)\n}", "func (tr *d17RTree) Count() int {\n\tvar count int\n\td17countRec(tr.root, &count)\n\treturn count\n}", "func (t *Trie) existsPrefix(prefix string, validWord bool) bool {\n\trunner := t.Root\n\n\tfor _, currChar := range prefix {\n\t\tif _, ok := runner.Children[currChar]; !ok {\n\t\t\treturn false\n\t\t}\n\t\trunner = runner.Children[currChar]\n\t}\n\n\tif validWord && !runner.IsWord {\n\t\treturn false\n\t}\n\treturn true\n}", "func (tr *d7RTree) Count() int {\n\tvar count int\n\td7countRec(tr.root, &count)\n\treturn count\n}", "func (tr *d9RTree) Count() int {\n\tvar count int\n\td9countRec(tr.root, &count)\n\treturn count\n}", "func (t *Trie) FindPrefixes(key string, f Visitor) {\n\tcur := t.root\n\tif cur.value != nil && !f(\"\", cur.value) {\n\t\treturn\n\t}\n\n\tfor i, r := range key {\n\t\tnext, ok := cur.children[r]\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tif next.value != nil && !f(key[:(i+1)], next.value) {\n\t\t\treturn\n\t\t}\n\t\tcur = next\n\t}\n}", "func HasPrefix(prefix, operand string) bool { return strings.HasPrefix(operand, prefix) }", "func (tr *d20RTree) Count() int {\n\tvar count int\n\td20countRec(tr.root, &count)\n\treturn count\n}", "func (this *Trie) Search(word string) bool {\n node := this.searchPrefix(word)\n \n return node != nil && node.isEnd\n}", "func (trie *Trie) Count() int {\n\tcount := 0\n\tfor _, child := range trie.children {\n\t\tif child.isLeaf == true {\n\t\t\tcount++\n\t\t}\n\n\t\tcount += child.Count()\n\t}\n\n\treturn count\n}", "func (b *Builder) HasPrefix(rhs interface{}) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.HasPrefix(rhs))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}", "func (r *Root) Count() (c *CountResult) {\n\tc = new(CountResult)\n\tc.Add(r.Roots.BookmarkBar.Name, len(r.Roots.BookmarkBar.Children))\n\tc.Add(r.Roots.Other.Name, len(r.Roots.Other.Children))\n\tc.Add(r.Roots.Synced.Name, len(r.Roots.Synced.Children))\n\n\treturn\n}", "func (n *NodeServiceImpl) Count(namespace string) (map[string]int, error) {\n\tlist, err := n.List(namespace, &models.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn map[string]int{\n\t\tplugin.QuotaNode: len(list.Items),\n\t}, nil\n}", "func (t *Tree) Count() int {\n\t// Only test the Left node (this binary tree is expected to be complete).\n\tif t.Left == nil {\n\t\treturn 1\n\t}\n\treturn 1 + t.Right.Count() + t.Left.Count()\n}", "func (tr *d16RTree) Count() int {\n\tvar count int\n\td16countRec(tr.root, &count)\n\treturn count\n}", "func prefixIndex(addr uint8, prefixLen int) int {\n\t// the prefixIndex of addr/prefixLen is the prefixLen most significant bits\n\t// of addr, with a 1 tacked onto the left-hand side. For example:\n\t//\n\t// - 0/0 is 1: 0 bits of the addr, with a 1 tacked on\n\t// - 42/8 is 1_00101010 (298): all bits of 42, with a 1 tacked on\n\t// - 48/4 is 1_0011 (19): 4 most-significant bits of 48, with a 1 tacked on\n\treturn (int(addr) >> (8 - prefixLen)) + (1 << prefixLen)\n}", "func (tr *d15RTree) Count() int {\n\tvar count int\n\td15countRec(tr.root, &count)\n\treturn count\n}", "func (c *Client) WatchPrefix(ctx context.Context, prefix string, opts ...easykv.WatchOption) (uint64, error) {\n\tif c.isURL {\n\t\t// watch is not supported for urls\n\t\treturn 0, easykv.ErrWatchNotSupported\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer watcher.Close()\n\n\terr = watcher.Add(c.filepath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-watcher.Events:\n\t\t\tif event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Remove == fsnotify.Remove {\n\t\t\t\treturn 1, nil\n\t\t\t}\n\t\tcase err := <-watcher.Errors:\n\t\t\treturn 0, err\n\t\tcase <-ctx.Done():\n\t\t\treturn 0, easykv.ErrWatchCanceled\n\t\t}\n\t}\n}", "func (t *Trie) StartWith(prefix string) bool {\n\tcurr := t.Root\n\tfor _, char := range prefix {\n\t\tif _, ok := curr.Children[char]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcurr = curr.Children[char]\n\t}\n\treturn true\n}", "func (tr *d2RTree) Count() int {\n\tvar count int\n\td2countRec(tr.root, &count)\n\treturn count\n}", "func (s *Store) FindPrefix(bucket, prefix []byte, next func(key, val []byte) bool) error {\n\treturn s.db.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket(bucket).Cursor()\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tif !next(k, v) {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (t *TrieNode) Find(prefix string, max int) []int64 {\n\tt.mx.RLock()\n\tdefer t.mx.RUnlock()\n\n\tif len(t.children) == 0 || prefix == \"\" || max <= 0 {\n\t\treturn nil\n\t}\n\n\t// iterate through trie until at end of prefix\n\tprefixRunes := []rune(prefix)\n\ttriePointer := t\n\tfor _, s := range prefixRunes {\n\t\tif triePointer.children[s] == nil {\n\t\t\treturn nil\n\t\t}\n\t\ttriePointer = triePointer.children[s]\n\t}\n\n\t// create int64 slice\n\tvar returnSlice []int64\n\ttriePointer.findDFS(&returnSlice, max)\n\treturn returnSlice\n}", "func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteCondition {\n\treturn builder.Append(b, \"Prefixes\", Expr(sql, args...)).(DeleteBuilder)\n}", "func (n *nodeHeader) prefixFields() (*uint16, []byte) {\n\tswitch n.typ {\n\tcase typLeaf:\n\t\t// Leaves have no prefix\n\t\treturn nil, nil\n\tcase typNode4:\n\t\tn4 := n.node4()\n\t\treturn &n4.prefixLen, n4.prefix[:]\n\n\tcase typNode16:\n\t\tn16 := n.node16()\n\t\treturn &n16.prefixLen, n16.prefix[:]\n\n\tcase typNode48:\n\t\tn48 := n.node48()\n\t\treturn &n48.prefixLen, n48.prefix[:]\n\n\tcase typNode256:\n\t\tn256 := n.node256()\n\t\treturn &n256.prefixLen, n256.prefix[:]\n\t}\n\tpanic(\"invalid type\")\n}", "func (b UpdateBuilder) Prefix(sql string, args ...interface{}) UpdateCondition {\n\treturn builder.Append(b, \"Prefixes\", Expr(sql, args...)).(UpdateBuilder)\n}", "func (am *AppchainManager) CountAll(_ []byte) (bool, []byte) {\n\tok, value := am.Query(PREFIX)\n\tif !ok {\n\t\treturn true, []byte(\"0\")\n\t}\n\treturn true, []byte(strconv.Itoa(len(value)))\n}", "func (t *TrieNode) Len() int {\n\tt.mx.RLock()\n\tdefer t.mx.RUnlock()\n\treturn t.LenHelper()\n}", "func (tr *d5RTree) Count() int {\n\tvar count int\n\td5countRec(tr.root, &count)\n\treturn count\n}", "func PrefixLength(be Lister, t Type) (int, error) {\n\t// load all IDs of the given type\n\tlist, err := be.List(t)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tsort.Sort(list)\n\n\t// select prefixes of length l, test if the last one is the same as the current one\nouter:\n\tfor l := MinPrefixLength; l < IDSize; l++ {\n\t\tvar last ID\n\n\t\tfor _, id := range list {\n\t\t\tif bytes.Equal(last, id[:l]) {\n\t\t\t\tcontinue outer\n\t\t\t}\n\t\t\tlast = id[:l]\n\t\t}\n\n\t\treturn l, nil\n\t}\n\n\treturn IDSize, nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n\tnode := this.searchPrefix(prefix)\n\tif node == nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (n *nodeHeader) prefix() []byte {\n\tpLen, pBytes := n.prefixFields()\n\n\tif *pLen <= maxPrefixLen {\n\t\t// We have the whole prefix from the node\n\t\treturn pBytes[0:*pLen]\n\t}\n\n\t// Prefix is too long for node, we have to go find it from the leaf\n\tminLeaf := n.minChild().leafNode()\n\treturn minLeaf.key[0:*pLen]\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcur := this.Root\n\tfor _, c := range prefix {\n\t\tif _, ok := cur.Child[c]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcur = cur.Child[c]\n\t}\n\treturn true\n}", "func (triple *TripleNode) NodeCounts() (nodeCount, nilCount int) {\n\tvar leftCount, leftNilCount, middleCount, middleNilCount, rightCount, rightNilCount int\n\t// Handle left branch\n\tif triple.LeftChild == nil {\n\t\t// No left child\n\t\tleftNilCount = 1\n\t\tleftCount = 0\n\t} else {\n\t\t// There is a left child\n\t\tleftCount, leftNilCount = triple.LeftChild.NodeCounts()\n\t}\n\n\t// Handle middle branch\n\tif triple.MiddleChild == nil {\n\t\t// No middle child\n\t\tmiddleNilCount = 1\n\t\tmiddleCount = 0\n\t} else {\n\t\t// There is a middle child\n\t\tmiddleCount, middleNilCount = triple.MiddleChild.NodeCounts()\n\t}\n\n\t// Handle right branch\n\tif triple.RightChild == nil {\n\t\t// No right child\n\t\trightNilCount = 1\n\t\trightCount = 0\n\t} else {\n\t\t// There is a right child\n\t\trightCount, rightNilCount = triple.RightChild.NodeCounts()\n\t}\n\n\treturn 1 + leftCount + middleCount + rightCount, leftNilCount + middleNilCount + rightNilCount // + 1 is ourself\n}", "func (t *Trie) FindWithPrefix(prefix string) []string {\n\twords := make([]string, 0)\n\tn := t.find(prefix)\n\tif n == nil {\n\t\treturn words\n\t}\n\tsuffix := t.getSuffix(n)\n\tfor _, s := range suffix {\n\t\twords = append(words, prefix+s)\n\t}\n\treturn words\n}", "func (t *Trie) StartsWith(prefix string) bool {\n\tp := t.root\n\twordArr := []rune(prefix)\n\n\tfor i := 0; i < len(wordArr); i++ {\n\t\tif p.edges[wordArr[i]-'a'] == nil {\n\t\t\treturn false\n\t\t} else {\n\t\t\tp = p.edges[wordArr[i]-'a']\n\t\t}\n\t}\n\treturn true\n}", "func (id ID) PrefixLen() int {\n\tfor i, b := range id.EthAddress {\n\t\tif b != 0 {\n\t\t\treturn i*8 + bits.LeadingZeros8(uint8(b))\n\t\t}\n\t}\n\treturn len(id.EthAddress)*8 - 1\n}", "func (this *Trie) StartsWith(prefix string) bool {\n if len(prefix) == 0 {return true}\n if this == nil || this.path == nil || this.path[prefix[0] - 'a'] == nil {return false}\n if len(prefix) == 1 {return this.path[prefix[0] - 'a'] != nil}\n this = this.path[prefix[0] - 'a']\n return this.StartsWith(prefix[1:])\n}", "func (a *Assertions) HasPrefix(corpus, prefix string, userMessageComponents ...interface{}) bool {\n\ta.assertion()\n\tif didFail, message := shouldHasPrefix(corpus, prefix); didFail {\n\t\treturn a.fail(message, userMessageComponents...)\n\t}\n\treturn true\n}", "func MatchPrefix(prefixes ...string) MatcherFunc { return MatchPrefixes(prefixes) }", "func (this *Trie) StartsWith(prefix string) bool {\n\tn := this.root\n\n\tfor i := 0; i < len(prefix); i++ {\n\t\twid := prefix[i] - 'a'\n\t\tif n.children[wid] == nil {\n\t\t\treturn false\n\t\t}\n\t\tn = n.children[wid]\n\t}\n\n\treturn true\n}", "func (q nodeQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count node rows\")\n\t}\n\n\treturn count, nil\n}", "func (pars *Parser) parsePrefixExpression() tree.Expression {\n\texpression := &tree.PrefixExpression{\n\t\tToken: pars.thisToken,\n\t\tOperator: pars.thisToken.Val,\n\t}\n\n\tpars.nextToken()\n\n\texpression.Right = pars.parseExpression(PREFIX)\n\treturn expression\n}", "func (t *Trie) Search(word string) bool {\n\tnode := t.searchPrefix(word)\n\treturn node != nil && node.isEnd\n}", "func (this *Trie) StartsWith(prefix string) bool {\r\n\tstrbyte := []byte(prefix)\r\n\tcurroot := this\r\n\tfor _, char := range strbyte {\r\n\t\tcurroot = curroot.childs[char-'a']\r\n\t\tif curroot == nil {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func (n Nodes) Len() int", "func (this *Trie) StartsWith(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn true\n\t}\n\tif this == nil {\n\t\treturn false\n\t}\n\tindex := ([]byte(prefix[0:1]))[0] - byte('a')\n\tif this.child[index] == nil {\n\t\treturn false\n\t}\n\tif prefix[1:] == \"\" {\n\t\treturn true\n\t}\n\treturn this.child[index].StartsWith(prefix[1:])\n\n}", "func (s *searchServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"SearchService\")\n}", "func (b *BTree) Len() int {\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\treturn int(b.rootNod.GetLength())\n}", "func (t *Tree) Len() int {\n\treturn t.Count\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\ttrie := this\n\tfor _, char := range prefix {\n\t\tif trie.childs[char-97] == nil {\n\t\t\treturn false\n\t\t}\n\t\ttrie = trie.childs[char-97]\n\t}\n\treturn true\n}", "func (pu *PrefixUpdate) Save(ctx context.Context) (int, error) {\n\tif v, ok := pu.mutation.Prefix(); ok {\n\t\tif err := prefix.PrefixValidator(v); err != nil {\n\t\t\treturn 0, &ValidationError{Name: \"prefix\", err: fmt.Errorf(\"ent: validator failed for field \\\"prefix\\\": %w\", err)}\n\t\t}\n\t}\n\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(pu.hooks) == 0 {\n\t\taffected, err = pu.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*PrefixMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tpu.mutation = mutation\n\t\t\taffected, err = pu.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(pu.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = pu.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, pu.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tnode := this\n\tn := len(prefix)\n\tfor i := 0; i < n; i++ {\n\t\tidx := prefix[i] - 'a'\n\t\tif node.sons[idx] == nil {\n\t\t\treturn false\n\t\t}\n\t\tnode = node.sons[idx]\n\t}\n\treturn true\n}", "func (t *Tree) Len() int { return t.Count }", "func countListParents(opt *Options, selec *goquery.Selection) (int, int) {\n\tvar values []int\n\tfor n := selec.Parent(); n != nil; n = n.Parent() {\n\t\tif n.Is(\"li\") {\n\t\t\tcontinue\n\t\t}\n\t\tif !n.Is(\"ul\") && !n.Is(\"ol\") {\n\t\t\tbreak\n\t\t}\n\n\t\tprefix := n.Children().First().AttrOr(attrListPrefix, \"\")\n\n\t\tvalues = append(values, len(prefix))\n\t}\n\n\t// how many spaces are reserved for the prefixes of my siblings\n\tvar prefixCount int\n\n\t// how many spaces are reserved in total for all of the other\n\t// list parents up the tree\n\tvar previousPrefixCounts int\n\n\tfor i, val := range values {\n\t\tif i == 0 {\n\t\t\tprefixCount = val\n\t\t\tcontinue\n\t\t}\n\n\t\tpreviousPrefixCounts += val\n\t}\n\n\treturn prefixCount, previousPrefixCounts\n}", "func (this *Trie) Search(s string, allowPrefix bool) bool {\n\tvar t *TrieNode = this.root\n\tfor _, a := range s {\n\t\tt = t.HasChild(a)\n\t\tif t == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn allowPrefix || t.GetEnd()\n}", "func PrefixLen(f EncryptFunc, bs int) int {\n\tstart := FirstModBlock(f, bs) * bs\n\tend := start + bs\n\n\t// Figure out what the modifiable block looks like when its remaining bytes\n\t// are filled with our own characters.\n\ta := f(A(bs))[start:end]\n\tb := f(B(bs))[start:end]\n\n\t// Add bytes until we see the expected blocks.\n\tfor i := 0; i < bs; i++ {\n\t\tif bytes.Equal(f(A(i + 1))[start:end], a) &&\n\t\t\tbytes.Equal(f(B(i + 1))[start:end], b) {\n\t\t\treturn end - i - 1\n\t\t}\n\t}\n\tpanic(\"couldn't find prefix length\")\n}", "func (p *Parser) parsePrefixExpression() ast.Expression {\n\texpression := &ast.PrefixExpression{\n\t\tToken: p.curToken,\n\t\tOperator: p.curToken.Literal}\n\tp.nextToken()\n\texpression.Right = p.parseExpression(PREFIX)\n\treturn expression\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\troot := this\n\tfor _, chartV := range prefix {\n\t\tnext, ok := root.next[string(chartV)]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\troot = next\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif len(prefix) == 0 {\n\t\treturn true\n\t}\n\tfor _, e := range this.edges {\n\t\tif e.char == prefix[0] {\n\t\t\treturn e.next.StartsWith(prefix[1:])\n\t\t}\n\t}\n\treturn false\n}", "func (p *Parser) parsePrefixExpression() asti.ExpressionI {\n\texpression := &ast.PrefixExpression{\n\t\tToken: p.curToken,\n\t\tOperator: p.curToken.Type,\n\t}\n\tp.nextToken()\n\texpression.Right = p.parseExpression(precedence.PREFIX)\n\treturn expression\n}" ]
[ "0.676077", "0.6484417", "0.63465744", "0.6022248", "0.6011498", "0.5960126", "0.5949926", "0.57407993", "0.5624859", "0.5569003", "0.5540688", "0.54302657", "0.54262424", "0.5414123", "0.5365138", "0.5362125", "0.53595495", "0.5323589", "0.53140223", "0.53023636", "0.5278311", "0.5278311", "0.52627194", "0.52550304", "0.5246604", "0.52394", "0.52348846", "0.5229449", "0.5223332", "0.5221897", "0.5213063", "0.5201663", "0.5196343", "0.5193746", "0.5193686", "0.5184753", "0.51841897", "0.5182623", "0.5181127", "0.51810455", "0.5178577", "0.5178004", "0.5177767", "0.51765907", "0.5150194", "0.5137543", "0.5125225", "0.5122387", "0.51215273", "0.51166666", "0.5115429", "0.5113338", "0.51124185", "0.5088814", "0.508275", "0.50816625", "0.50659484", "0.50633276", "0.50496143", "0.50392985", "0.50331295", "0.50175375", "0.50142956", "0.5010535", "0.5009873", "0.4988309", "0.49821255", "0.49814966", "0.49802244", "0.49633896", "0.4956749", "0.49554884", "0.49550077", "0.49411118", "0.49349904", "0.49169853", "0.48813793", "0.4871062", "0.48574397", "0.4848166", "0.48465896", "0.4831551", "0.4829912", "0.48292503", "0.4826334", "0.48194522", "0.4818557", "0.48181185", "0.48000684", "0.47963518", "0.4793899", "0.47827333", "0.47820684", "0.47754598", "0.47742593", "0.47710064", "0.47676992", "0.47652376", "0.47602051", "0.47569117" ]
0.77689135
0
LookupCalled looks up ssa.Instruction that call the `fn` func in the given instr
LookupCalled ищет ssa.Instruction, вызывающую функцию `fn` в заданном instr
func LookupCalled(instr ssa.Instruction, fn *types.Func) ([]ssa.Instruction, bool) { instrs := []ssa.Instruction{} call, ok := instr.(ssa.CallInstruction) if !ok { return instrs, false } ssaCall := call.Value() if ssaCall == nil { return instrs, false } common := ssaCall.Common() if common == nil { return instrs, false } val := common.Value called := false switch fnval := val.(type) { case *ssa.Function: for _, block := range fnval.Blocks { for _, instr := range block.Instrs { if analysisutil.Called(instr, nil, fn) { called = true instrs = append(instrs, instr) } } } } return instrs, called }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Module) instCall(old *ast.InstCall, resolved, unresolved map[ast.NamedValue]value.Named) bool {\n\tif isUnresolved(unresolved, old.Callee) || isUnresolved(unresolved, old.Args...) {\n\t\treturn false\n\t}\n\tv := m.getLocal(old.Name)\n\tinst, ok := v.(*ir.InstCall)\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"invalid instruction type for instruction %s; expected *ir.InstCall, got %T\", enc.Local(old.Name), v))\n\t}\n\tvar (\n\t\ttyp *types.PointerType\n\t\tsig *types.FuncType\n\t)\n\tvar args []value.Value\n\tfor _, oldArg := range old.Args {\n\t\targ := m.irValue(oldArg)\n\t\targs = append(args, arg)\n\t}\n\tcallee := m.irValue(old.Callee)\n\tif c, ok := callee.(*ir.InlineAsm); ok {\n\t\tswitch t := c.Typ.(type) {\n\t\tcase *types.FuncType:\n\t\t\tsig = t\n\t\tdefault:\n\t\t\t// Result type stored in t, get parameters for function signature from\n\t\t\t// arguments. Not perfect, but the best we can do. In particular, this\n\t\t\t// approach is known to fail for variadic parameters.\n\t\t\tvar params []*types.Param\n\t\t\tfor _, arg := range args {\n\t\t\t\tparam := types.NewParam(\"\", arg.Type())\n\t\t\t\tparams = append(params, param)\n\t\t\t}\n\t\t\tsig = types.NewFunc(t, params...)\n\t\t}\n\t\ttyp = types.NewPointer(sig)\n\t} else {\n\t\tvar ok bool\n\t\ttyp, ok = callee.Type().(*types.PointerType)\n\t\tif !ok {\n\t\t\tpanic(fmt.Errorf(\"invalid callee type, expected *types.PointerType, got %T\", callee.Type()))\n\t\t}\n\t\tsig, ok = typ.Elem.(*types.FuncType)\n\t\tif !ok {\n\t\t\tpanic(fmt.Errorf(\"invalid callee signature type, expected *types.FuncType, got %T\", typ.Elem))\n\t\t}\n\t}\n\tinst.Callee = callee\n\tinst.Sig = sig\n\t// TODO: Validate old.Type against inst.Sig.\n\tinst.Args = args\n\tinst.CallConv = ir.CallConv(old.CallConv)\n\tinst.Metadata = m.irMetadata(old.Metadata)\n\treturn true\n}", "func FnCall() bool {\n\treturn fnCall\n}", "func (th *Thread) CallLookup(this Value, method string, args ...Value) Value {\n\treturn th.CallThis(th.Lookup(this, method), this, args...)\n}", "func (l *Loader) SetLookupFn(fn func(string) (string, bool)) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tl.lookUp = fn\n}", "func (l *InfosT) ByRuntimeFunc(argFunc *runtime.Func) Info {\n\n\tfor i := 0; i < len(*l); i++ {\n\t\tlpFunc := (*l)[i].Handler\n\t\tlpFuncType := reflect.ValueOf(lpFunc)\n\t\tif lpFuncType.Pointer() == argFunc.Entry() {\n\t\t\treturn (*l)[i]\n\t\t}\n\t}\n\tlog.Panicf(\"unknown runtime func %+v\", argFunc)\n\treturn Info{}\n}", "func (_f6 *FakeResolver) ResolveCalledWith(name string) (found bool) {\n\tfor _, call := range _f6.ResolveCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Name, name) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func callFn(name string, unit reflect.Value, args []reflect.Value) error {\n\tif fn := unit.MethodByName(name); fn.IsValid() == false {\n\t\treturn nil\n\t} else if ret := fn.Call(args); len(ret) != 1 {\n\t\treturn nil\n\t} else if err, ok := ret[0].Interface().(error); ok {\n\t\treturn err\n\t} else if err == nil {\n\t\treturn nil\n\t} else {\n\t\treturn gopi.ErrBadParameter.WithPrefix(name)\n\t}\n}", "func Lookup(key string) RunnerFunc {\n\tv, ok := runners.Load(key)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn v.(RunnerFunc)\n}", "func (_f2 *FakeInterfacer) InterfaceCalledWith(ident1 interface{}) (found bool) {\n\tfor _, call := range _f2.InterfaceCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (bi *BinaryInfo) LookupGenericFunc() map[string][]*Function {\n\tif bi.lookupGenericFunc == nil {\n\t\tbi.lookupGenericFunc = make(map[string][]*Function)\n\t\tfor i := range bi.Functions {\n\t\t\tdn := bi.Functions[i].NameWithoutTypeParams()\n\t\t\tif dn != bi.Functions[i].Name {\n\t\t\t\tbi.lookupGenericFunc[dn] = append(bi.lookupGenericFunc[dn], &bi.Functions[i])\n\t\t\t}\n\t\t}\n\t}\n\treturn bi.lookupGenericFunc\n}", "func (m *Mock) Called(arguments ...interface{}) Arguments {\n\t// get the calling function's name\n\tpc, _, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\tpanic(\"Couldn't get the caller information\")\n\t}\n\tfunctionPath := runtime.FuncForPC(pc).Name()\n\t// Next four lines are required to use GCCGO function naming conventions.\n\t// For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock\n\t// uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree\n\t// With GCCGO we need to remove interface information starting from pN<dd>.\n\tif gccgoRE.MatchString(functionPath) {\n\t\tfunctionPath = gccgoRE.Split(functionPath, -1)[0]\n\t}\n\tparts := strings.Split(functionPath, \".\")\n\tfunctionName := parts[len(parts)-1]\n\treturn m.MethodCalled(functionName, arguments...)\n}", "func (a *ActorInfo) LookupMethod(num uint64) (MethodInfo, bool) {\n\tif idx, ok := a.methodMap[num]; ok {\n\t\treturn a.Methods[idx], true\n\t}\n\n\treturn MethodInfo{}, false\n}", "func (bi *BinaryInfo) symLookup(addr uint64) (string, uint64) {\n\tfn := bi.PCToFunc(addr)\n\tif fn != nil {\n\t\tif fn.Entry == addr {\n\t\t\t// only report the function name if it's the exact address because it's\n\t\t\t// easier to read the absolute address than function_name+offset.\n\t\t\treturn fn.Name, fn.Entry\n\t\t}\n\t\treturn \"\", 0\n\t}\n\tif sym, ok := bi.SymNames[addr]; ok {\n\t\treturn sym.Name, addr\n\t}\n\ti := sort.Search(len(bi.packageVars), func(i int) bool {\n\t\treturn bi.packageVars[i].addr >= addr\n\t})\n\tif i >= len(bi.packageVars) {\n\t\treturn \"\", 0\n\t}\n\tif bi.packageVars[i].addr > addr {\n\t\t// report previous variable + offset if i-th variable starts after addr\n\t\ti--\n\t}\n\tif i >= 0 && bi.packageVars[i].addr != 0 {\n\t\treturn bi.packageVars[i].name, bi.packageVars[i].addr\n\t}\n\treturn \"\", 0\n}", "func (mr *MockResolverMockRecorder) Lookup(service, key interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockResolver)(nil).Lookup), service, key)\n}", "func (s *fnSignature) Execute(ctx context.Context) ([]reflect.Value, error) {\n\tglobalBackendStatsClient().TaskExecutionCount().Inc(1)\n\ttargetArgs := make([]reflect.Value, 0, len(s.Args)+1)\n\ttargetArgs = append(targetArgs, reflect.ValueOf(ctx))\n\tfor _, arg := range s.Args {\n\t\ttargetArgs = append(targetArgs, reflect.ValueOf(arg))\n\t}\n\tif fn, ok := fnLookup.getFn(s.FnName); ok {\n\t\tfnValue := reflect.ValueOf(fn)\n\t\treturn fnValue.Call(targetArgs), nil\n\t}\n\treturn nil, fmt.Errorf(\"function: %q not found. Did you forget to register?\", s.FnName)\n}", "func TakeCallableAddr(fn interface{}) unsafe.Pointer {\n\n\t// There is no need nil checks,\n\t// because TakeRealAddr and AddrConvert2Callable already has it\n\treturn AddrConvert2Callable(TakeRealAddr(fn))\n}", "func (b *BananaPhone) GetFuncPtr(funcname string) (uint64, error) {\n\texports, err := b.banana.Exports()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor _, ex := range exports {\n\t\tif strings.ToLower(funcname) == strings.ToLower(ex.Name) {\n\t\t\treturn uint64(b.memloc) + uint64(ex.VirtualAddress), nil\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"could not find function: %s\", funcname)\n}", "func LookupInstruction(ctx *pulumi.Context, args *LookupInstructionArgs, opts ...pulumi.InvokeOption) (*LookupInstructionResult, error) {\n\tvar rv LookupInstructionResult\n\terr := ctx.Invoke(\"google-native:datalabeling/v1beta1:getInstruction\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (t *LineTable) findFunc(pc uint64) funcData {\n\tft := t.funcTab()\n\tif pc < ft.pc(0) || pc >= ft.pc(ft.Count()) {\n\t\treturn funcData{}\n\t}\n\tidx := sort.Search(int(t.nfunctab), func(i int) bool {\n\t\treturn ft.pc(i) > pc\n\t})\n\tidx--\n\treturn t.funcData(uint32(idx))\n}", "func (mr *MockDirStoreMockRecorder) Lookup(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockDirStore)(nil).Lookup), arg0, arg1, arg2)\n}", "func (p *Process) FindFunc(pc core.Address) *Func {\n\treturn p.funcTab.find(pc)\n}", "func (info *Info) FindFunc(path string) (*ssa.Function, error) {\n\tpkgPath, fnName := parseFuncPath(path)\n\tgraph, err := info.BuildCallGraph(\"rta\", false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfuncs, err := graph.UsedFunctions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, f := range funcs {\n\t\tif f.Pkg.Pkg.Path() == pkgPath && f.Name() == fnName {\n\t\t\treturn f, nil\n\t\t}\n\t}\n\treturn nil, nil\n}", "func reflectFuncCall(fn reflect.Value, args []reflect.Value) error {\n\terrValue := fn.Call(args)\n\tvar errResult error\n\terrInter := errValue[0].Interface()\n\tif errInter != nil {\n\t\terrResult = errInter.(error)\n\t}\n\treturn errResult\n}", "func (s *BasejossListener) EnterFuncSin(ctx *FuncSinContext) {}", "func LookupFunction(ctx *pulumi.Context, args *GetFunctionArgs) (*GetFunctionResult, error) {\n\tinputs := make(map[string]interface{})\n\tif args != nil {\n\t\tinputs[\"functionName\"] = args.FunctionName\n\t\tinputs[\"qualifier\"] = args.Qualifier\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\toutputs, err := ctx.Invoke(\"aws:lambda/getFunction:getFunction\", inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GetFunctionResult{\n\t\tArn: outputs[\"arn\"],\n\t\tDeadLetterConfig: outputs[\"deadLetterConfig\"],\n\t\tDescription: outputs[\"description\"],\n\t\tEnvironment: outputs[\"environment\"],\n\t\tFunctionName: outputs[\"functionName\"],\n\t\tHandler: outputs[\"handler\"],\n\t\tInvokeArn: outputs[\"invokeArn\"],\n\t\tKmsKeyArn: outputs[\"kmsKeyArn\"],\n\t\tLastModified: outputs[\"lastModified\"],\n\t\tLayers: outputs[\"layers\"],\n\t\tMemorySize: outputs[\"memorySize\"],\n\t\tQualifiedArn: outputs[\"qualifiedArn\"],\n\t\tQualifier: outputs[\"qualifier\"],\n\t\tReservedConcurrentExecutions: outputs[\"reservedConcurrentExecutions\"],\n\t\tRole: outputs[\"role\"],\n\t\tRuntime: outputs[\"runtime\"],\n\t\tSourceCodeHash: outputs[\"sourceCodeHash\"],\n\t\tSourceCodeSize: outputs[\"sourceCodeSize\"],\n\t\tTags: outputs[\"tags\"],\n\t\tTimeout: outputs[\"timeout\"],\n\t\tTracingConfig: outputs[\"tracingConfig\"],\n\t\tVersion: outputs[\"version\"],\n\t\tVpcConfig: outputs[\"vpcConfig\"],\n\t\tId: outputs[\"id\"],\n\t}, nil\n}", "func (t *ManagePatient) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n fmt.Println(\"invoke is running \" + function)\n\n // Handle different functions\n if function == \"init\" { //initialize the chaincode state, used as reset\n return t.Init(stub, \"init\", args)\n } else if function == \"create_patient\" { //create a new Patient\n return t.create_patient(stub, args)\n }\n fmt.Println(\"invoke did not find func: \" + function) //error\n return nil, errors.New(\"Received unknown function invocation\")\n}", "func (_mr *MockDraOpMockRecorder) LookupFileByMd5(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"LookupFileByMd5\", reflect.TypeOf((*MockDraOp)(nil).LookupFileByMd5), arg0, arg1)\n}", "func (mr *MockRemotesMockRecorder) Lookup(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockRemotes)(nil).Lookup), arg0)\n}", "func (ui *UI) DynamicCommandLookup(impl interface{}) func(string) (func(), bool) {\n\tt := reflect.TypeOf(impl)\n\treturn func(name string) (func(), bool) {\n\t\tcmd := ui.GetCommand(name)\n\t\tif cmd == nil {\n\t\t\treturn nil, false\n\t\t}\n\t\tfn, found := t.MethodByName(cmd.Original)\n\t\tif !found {\n\t\t\treturn nil, found\n\t\t}\n\t\treturn fn.Func.Interface().(func()), true\n\t}\n}", "func (mr *MockUserFinderMockRecorder) Lookup(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockUserFinder)(nil).Lookup), arg0)\n}", "func (bi *BinaryInfo) FindFunction(funcName string) ([]*Function, error) {\n\tif fns := bi.LookupFunc()[funcName]; fns != nil {\n\t\treturn fns, nil\n\t}\n\tfns := bi.LookupGenericFunc()[funcName]\n\tif len(fns) == 0 {\n\t\treturn nil, &ErrFunctionNotFound{funcName}\n\t}\n\treturn fns, nil\n}", "func isFunction(c *Context, callee string) {\r\n possibleFunc := c.lookup(callee)\r\n _, isFuncDec := possibleFunc.(*FuncDeclaration)\r\n performCheck(isFuncDec, fmt.Sprintf(\"ERROR: %d: Semantic: ID: %s is not a function.\", callee, possibleFunc))\r\n}", "func WrapFunc(fn interface{}) Func {\n\treturn func(hit *Hit) error {\n\t\t// TODO: hit as first arg?\n\t\treturn CallFunc(fn, hit.Args)\n\t}\n}", "func (*InstFPExt) isInst() {}", "func _getFuncPtrVal() uintptr {\n // frame 0 : assertXXX\n // frame 1 : TestXXX <- the one we want\n // frame 2 : testing.tRunner\n var frameCnt = 3\n\n // Extract the top few frames\n var pc = make([]uintptr, frameCnt)\n runtime.Callers(frameCnt, pc)\n\n return pc[1]\n}", "func (*InstFPToSI) isInst() {}", "func (cb callBacker) maybeCall(fn_name string) error {\n\tif cb.Scripter.HasEraValue(fn_name) {\n\t\treturn cb.Scripter.EraCall(fn_name)\n\t}\n\treturn nil\n}", "func (c *Container) funcOf(typ reflect.Type, method string) reflect.Value {\n\tc.lock.RLock()\n\tins, ok := c.instances[typ]\n\tc.lock.RUnlock()\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"no instance for type %s\", typ))\n\t}\n\treturn reflect.ValueOf(ins).MethodByName(method)\n}", "func invokeHook(fn func() error) error {\n\tif fn != nil {\n\t\treturn fn()\n\t}\n\n\treturn nil\n}", "func GetFunc(fn func(string) string) LookupFunc {\n\treturn func(key string) (string, bool) {\n\t\tv := fn(key)\n\t\treturn v, v != \"\"\n\t}\n}", "func (fs *fsMutable) lookup(p fuseops.InodeID, c string) (le lookupEntry, found bool, lk []byte) {\n\treturn lookup(p, c, fs.lookupTree)\n}", "func (fs *fsMutable) lookup(p fuseops.InodeID, c string) (le lookupEntry, found bool, lk []byte) {\n\treturn lookup(p, c, fs.lookupTree)\n}", "func (r FunctionRegistry) Function(name string) (Function, error) {\n\tif len(r) == 0 {\n\t\treturn nil, ErrFunctionNotFound.New(name)\n\t}\n\n\tif fn, ok := r[name]; ok {\n\t\treturn fn, nil\n\t}\n\tsimilar := similartext.FindFromMap(r, name)\n\treturn nil, ErrFunctionNotFound.New(name + similar)\n}", "func (me *messageEvents) Called(ctx context.Context, check CheckFunc, msgHnd MsgHandler, rev RevertHandler, confidence int, timeout abi.ChainEpoch, mf MsgMatchFunc) error {\n\thnd := func(ctx context.Context, data eventData, prevTs, ts *types.TipSet, height abi.ChainEpoch) (bool, error) {\n\t\tmsg, ok := data.(*types.Message)\n\t\tif data != nil && !ok {\n\t\t\tpanic(\"expected msg\")\n\t\t}\n\n\t\tml, err := me.cs.StateSearchMsg(ctx, ts.Key(), msg.Cid(), stmgr.LookbackNoLimit, true)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif ml == nil {\n\t\t\treturn msgHnd(msg, nil, ts, height)\n\t\t}\n\n\t\treturn msgHnd(msg, &ml.Receipt, ts, height)\n\t}\n\n\tid, err := me.hcAPI.onHeadChanged(ctx, check, hnd, rev, confidence, timeout)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"on head changed error: %w\", err)\n\t}\n\n\tme.lk.Lock()\n\tdefer me.lk.Unlock()\n\tme.matchers[id] = mf\n\n\treturn nil\n}", "func (_f28 *FakeContext) StartSpanCalledWith(ident1 string, ident2 ...opentracing.StartSpanOption) (found bool) {\n\tfor _, call := range _f28.StartSpanCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) && reflect.DeepEqual(call.Parameters.Ident2, ident2) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (fi *FsCache) lookup(key *fs.FsFile) (*fs.FsData, bool) {\n\tfdata, ok := fi.dict[key.String()]\n\treturn fdata, ok\n}", "func FuncOf(fn func(this Value, args []Value) interface{}) Func {\n\tpanic(message)\n}", "func (hook *CallInfoHook) Fire(entry *logrus.Entry) error {\n\tfile, line, fn := GetStackInfo()\n\n\tif rel, err := filepath.Rel(filepath.Join(build.Default.GOPATH, \"/src\"), file); err == nil {\n\t\tfile = rel\n\t}\n\n\tentry.WithField(\"file\", file)\n\tentry.WithField(\"line\", line)\n\tentry.WithField(\"func\", fn)\n\n\treturn nil\n}", "func (s *BaseConcertoListener) EnterFuncCallArg(ctx *FuncCallArgContext) {}", "func (*InstSExt) isInst() {}", "func FireFunc(data FunctionData) bool {\n\tif fun, found := funcHandler.Load(data.FuncName); found {\n\t\tgo func() {\n\t\t\tfun.(func(data FunctionData))(data)\n\t\t}()\n\t\treturn true\n\t}\n\treturn false\n}", "func (vm *VM) opCall(instr []uint16, nextI int) int {\n\ta := vm.get(instr[0])\n\tvm.stack = append(vm.stack, uint16(nextI)+2)\n\t//fmt.Printf(\"stack after call: %v\\n\", vm.stack)\n\n\treturn int(a)\n}", "func (s Struct) Fn(fn string) Function {\n\treturn Function{s, make(map[string]interface{}), fn}\n}", "func (_f8 *FakeInterfacer) NamedInterfaceCalledWith(a interface{}) (found bool) {\n\tfor _, call := range _f8.NamedInterfaceCalls {\n\t\tif reflect.DeepEqual(call.Parameters.A, a) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (mock *Serf) IDCalled() bool {\n\tlockSerfID.RLock()\n\tdefer lockSerfID.RUnlock()\n\treturn len(mock.calls.ID) > 0\n}", "func (r *Resolver) ResolveFunc(module, field string) FunctionImport {\n\t//fmt.Printf(\"Resolve func: %s %s\\n\", module, field) // Log resolve\n\n\tswitch module { // Handle module types\n\tcase \"env\": // Env module\n\t\tswitch field { // Handle fields\n\t\tcase \"__ursa_ping\":\n\t\t\treturn func(vm *VirtualMachine) int64 {\n\t\t\t\treturn vm.GetCurrentFrame().Locals[0] + 1\n\t\t\t}\n\t\tcase \"__ursa_log\":\n\t\t\treturn func(vm *VirtualMachine) int64 {\n\t\t\t\tptr := int(uint32(vm.GetCurrentFrame().Locals[0]))\n\t\t\t\tmsgLen := int(uint32(vm.GetCurrentFrame().Locals[1]))\n\t\t\t\tmsg := vm.Memory[ptr : ptr+msgLen]\n\t\t\t\tfmt.Printf(\"[app] %s\\n\", string(msg))\n\t\t\t\treturn 0\n\t\t\t}\n\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"unknown field: %s\", field)) // Panic\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown module: %s\", module)) // Panic\n\t}\n}", "func (_mr *MockDraOpMockRecorder) LookupFileById(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"LookupFileById\", reflect.TypeOf((*MockDraOp)(nil).LookupFileById), arg0)\n}", "func (s *BaseConcertoListener) EnterFuncCallSpec(ctx *FuncCallSpecContext) {}", "func IsCalled(v *govulncheck.Vuln) bool {\n\tfor _, m := range v.Modules {\n\t\tfor _, p := range m.Packages {\n\t\t\tif len(p.CallStacks) > 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func FuncIn() {\n\tsimlog.FuncIn()\n}", "func FuncOf(fn func(this Value, args []Value) interface{}) Func {\n\tfuncsMu.Lock()\n\tid := nextFuncID\n\tnextFuncID++\n\tfuncs[id] = fn\n\tfuncsMu.Unlock()\n\treturn Func{\n\t\tid: id,\n\t\tValue: jsGo.Call(\"_makeFuncWrapper\", id),\n\t}\n}", "func walkCall(n *ir.CallExpr, init *ir.Nodes) ir.Node {\n\tif n.Op() == ir.OCALLMETH {\n\t\tbase.FatalfAt(n.Pos(), \"OCALLMETH missed by typecheck\")\n\t}\n\tif n.Op() == ir.OCALLINTER || n.X.Op() == ir.OMETHEXPR {\n\t\t// We expect both interface call reflect.Type.Method and concrete\n\t\t// call reflect.(*rtype).Method.\n\t\tusemethod(n)\n\t}\n\tif n.Op() == ir.OCALLINTER {\n\t\treflectdata.MarkUsedIfaceMethod(n)\n\t}\n\n\tif n.Op() == ir.OCALLFUNC && n.X.Op() == ir.OCLOSURE {\n\t\tdirectClosureCall(n)\n\t}\n\n\tif isFuncPCIntrinsic(n) {\n\t\t// For internal/abi.FuncPCABIxxx(fn), if fn is a defined function, rewrite\n\t\t// it to the address of the function of the ABI fn is defined.\n\t\tname := n.X.(*ir.Name).Sym().Name\n\t\targ := n.Args[0]\n\t\tvar wantABI obj.ABI\n\t\tswitch name {\n\t\tcase \"FuncPCABI0\":\n\t\t\twantABI = obj.ABI0\n\t\tcase \"FuncPCABIInternal\":\n\t\t\twantABI = obj.ABIInternal\n\t\t}\n\t\tif isIfaceOfFunc(arg) {\n\t\t\tfn := arg.(*ir.ConvExpr).X.(*ir.Name)\n\t\t\tabi := fn.Func.ABI\n\t\t\tif abi != wantABI {\n\t\t\t\tbase.ErrorfAt(n.Pos(), \"internal/abi.%s expects an %v function, %s is defined as %v\", name, wantABI, fn.Sym().Name, abi)\n\t\t\t}\n\t\t\tvar e ir.Node = ir.NewLinksymExpr(n.Pos(), fn.Sym().LinksymABI(abi), types.Types[types.TUINTPTR])\n\t\t\te = ir.NewAddrExpr(n.Pos(), e)\n\t\t\te.SetType(types.Types[types.TUINTPTR].PtrTo())\n\t\t\te = ir.NewConvExpr(n.Pos(), ir.OCONVNOP, n.Type(), e)\n\t\t\treturn e\n\t\t}\n\t\t// fn is not a defined function. It must be ABIInternal.\n\t\t// Read the address from func value, i.e. *(*uintptr)(idata(fn)).\n\t\tif wantABI != obj.ABIInternal {\n\t\t\tbase.ErrorfAt(n.Pos(), \"internal/abi.%s does not accept func expression, which is ABIInternal\", name)\n\t\t}\n\t\targ = walkExpr(arg, init)\n\t\tvar e ir.Node = ir.NewUnaryExpr(n.Pos(), ir.OIDATA, arg)\n\t\te.SetType(n.Type().PtrTo())\n\t\te = ir.NewStarExpr(n.Pos(), e)\n\t\te.SetType(n.Type())\n\t\treturn e\n\t}\n\n\twalkCall1(n, init)\n\treturn n\n}", "func (r *Resolver) lookupFunc(key string) func() (interface{}, error) {\n\tif len(key) == 0 {\n\t\tpanic(\"lookupFunc with empty key\")\n\t}\n\tresolver := net.DefaultResolver\n\tif r.Resolver != nil {\n\t\tresolver = r.Resolver\n\t}\n\tswitch key[0] {\n\tcase 'h':\n\t\treturn func() (interface{}, error) {\n\t\t\tctx, cancel := r.getCtx()\n\t\t\tdefer cancel()\n\t\t\treturn resolver.LookupHost(ctx, key[1:])\n\t\t}\n\tcase 'r':\n\t\treturn func() (interface{}, error) {\n\t\t\tctx, cancel := r.getCtx()\n\t\t\tdefer cancel()\n\t\t\treturn resolver.LookupAddr(ctx, key[1:])\n\t\t}\n\tcase 'm':\n\t\treturn func() (interface{}, error) {\n\t\t\tctx, cancel := r.getCtx()\n\t\t\tdefer cancel()\n\t\t\treturn resolver.LookupMX(ctx, key[1:])\n\t\t}\n\tdefault:\n\t\tpanic(\"lookupFunc invalid key type: \" + key)\n\t}\n}", "func (*InstZExt) isInst() {}", "func FindFunctionLocation(p Process, funcName string, lineOffset int) ([]uint64, error) {\n\tbi := p.BinInfo()\n\torigfns, err := bi.FindFunction(funcName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif lineOffset > 0 {\n\t\tfn := origfns[0]\n\t\tfilename, lineno := bi.EntryLineForFunc(fn)\n\t\treturn FindFileLocation(p, filename, lineno+lineOffset)\n\t}\n\n\tr := make([]uint64, 0, len(origfns[0].InlinedCalls)+len(origfns))\n\n\tfor _, origfn := range origfns {\n\t\tif origfn.Entry > 0 {\n\t\t\t// add concrete implementation of the function\n\t\t\tpc, err := FirstPCAfterPrologue(p, origfn, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr = append(r, pc)\n\t\t}\n\t\t// add inlined calls to the function\n\t\tfor _, call := range origfn.InlinedCalls {\n\t\t\tr = append(r, call.LowPC)\n\t\t}\n\t\tif len(r) == 0 {\n\t\t\treturn nil, &ErrFunctionNotFound{funcName}\n\t\t}\n\t}\n\tsort.Slice(r, func(i, j int) bool { return r[i] < r[j] })\n\treturn r, nil\n}", "func (_f68 *FakeContext) WithSpanCalledWith(ident1 opentracing.Span) (found bool) {\n\tfor _, call := range _f68.WithSpanCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func Trace(info string) {\n\tpc := make([]uintptr, 1)\n\n\t// get call stack, ommitting 2 elements on stack, which is runtime.Callers and Trace2, respectively\n\truntime.Callers(2 , pc)\n\tf := runtime.FuncForPC(pc[0])\n\t// get the file and line number of the instruction immediately following the call\n\tfile, line := f.FileLine(pc[0])\n\n\tif len(info) == 0 {\n\t\tlogrus.Debugf(\"Lele: %s:%d; funcName: '%s'\", file, line, f.Name())\n\t}else{\n\t\tlogrus.Debugf(\"Lele: %s, %s:%d; funcName: '%s'\", info, file, line, f.Name())\n\t}\n\n}", "func GetCaller(offset int) (file string, line int) {\n\tfpcs := make([]uintptr, 1)\n\n\tn := runtime.Callers(offset, fpcs)\n\tif n == 0 {\n\t\treturn \"n/a\", -1\n\t}\n\n\tfun := runtime.FuncForPC(fpcs[0] - 1)\n\tif fun == nil {\n\t\treturn \"n/a\", -1\n\t}\n\n\treturn fun.FileLine(fpcs[0] - 1)\n}", "func (state *State) IsFunc(index int) bool { return state.TypeAt(index) == FuncType }", "func (e *Event) Lookup(name string) (arg uint64, found bool) {\n\tfor idx, v := range schemas[e.Type%EvCount].Args {\n\t\tif idx > len(e.Args) {\n\t\t\treturn\n\t\t}\n\t\tif v == name {\n\t\t\treturn e.Args[idx], true\n\t\t}\n\t}\n\treturn\n}", "func fn(labels ...string) string {\n\tfunction, _, _, _ := runtime.Caller(1)\n\n\tlongname := runtime.FuncForPC(function).Name()\n\n\tnameparts := strings.Split(longname, \".\")\n\tshortname := nameparts[len(nameparts)-1]\n\n\tif labels == nil {\n\t\treturn fmt.Sprintf(\"[%s()]\", shortname)\n\t}\n\n\treturn fmt.Sprintf(\"[%s():%s]\", shortname, strings.Join(labels, \":\"))\n}", "func (f *FakeResolver) ResolveCalledN(n int) bool {\n\treturn len(f.ResolveCalls) >= n\n}", "func (m Matcher) Fn() MatchFn {\n\tswitch m.matchType {\n\tcase PathEqual:\n\t\treturn m.matchPathFn(func(s, t string) bool { return s == t })\n\tcase PathContains:\n\t\treturn m.matchPathFn(strings.Contains)\n\tcase PathPrefix:\n\t\treturn m.matchPathFn(strings.HasPrefix)\n\tcase ExecutableEqual:\n\t\treturn m.matchExecutableFn(func(s, t string) bool { return s == t })\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (cb callBacker) mustCall(fn_name string) error {\n\treturn cb.Scripter.EraCall(fn_name)\n}", "func lookupFail(c *C, dnsNames []string) (DNSIPs map[string]*DNSIPRecords, errorDNSNames map[string]error) {\n\tc.Error(\"Lookup function called when it should not\")\n\treturn nil, nil\n}", "func seen(p *profile.Profile, fname string) bool {\n\tlocIDs := map[*profile.Location]bool{}\n\tfor _, loc := range p.Location {\n\t\tfor _, l := range loc.Line {\n\t\t\tif strings.Contains(l.Function.Name, fname) {\n\t\t\t\tlocIDs[loc] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tfor _, sample := range p.Sample {\n\t\tfor _, loc := range sample.Location {\n\t\t\tif locIDs[loc] {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (*InstPtrToInt) isInst() {}", "func (s *service) lookupExecutable(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\texists, err := s.store.ExecutableExists(p.ByName(\"hash\"))\n\tif err != nil {\n\t\ts.logger.Warn(\"looking up executable\", \"hash\", p.ByName(\"hash\"), \"err\", err)\n\t\twriteError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif !exists {\n\t\twriteError(w, http.StatusNotFound, errors.New(`not found`))\n\t\treturn\n\t}\n\n\twrite(w, http.StatusOK, map[string]interface{}{\"found\": true})\n}", "func execLookupFieldOrMethod(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret, ret1, ret2 := types.LookupFieldOrMethod(args[0].(types.Type), args[1].(bool), args[2].(*types.Package), args[3].(string))\n\tp.Ret(4, ret, ret1, ret2)\n}", "func (*InstSIToFP) isInst() {}", "func (f funcTab) funcOff(i int) uint64 {\n\treturn f.uint(f.functab[(2*i+1)*f.sz:])\n}", "func (*InstIntToPtr) isInst() {}", "func fn1() {}", "func InjectDebugCall(gp *g, fn any, regArgs *abi.RegArgs, stackArgs any, tkill func(tid int) error, returnOnUnsafePoint bool) (any, error) {\n\tif gp.lockedm == 0 {\n\t\treturn nil, plainError(\"goroutine not locked to thread\")\n\t}\n\n\ttid := int(gp.lockedm.ptr().procid)\n\tif tid == 0 {\n\t\treturn nil, plainError(\"missing tid\")\n\t}\n\n\tf := efaceOf(&fn)\n\tif f._type == nil || f._type.kind&kindMask != kindFunc {\n\t\treturn nil, plainError(\"fn must be a function\")\n\t}\n\tfv := (*funcval)(f.data)\n\n\ta := efaceOf(&stackArgs)\n\tif a._type != nil && a._type.kind&kindMask != kindPtr {\n\t\treturn nil, plainError(\"args must be a pointer or nil\")\n\t}\n\targp := a.data\n\tvar argSize uintptr\n\tif argp != nil {\n\t\targSize = (*ptrtype)(unsafe.Pointer(a._type)).elem.size\n\t}\n\n\th := new(debugCallHandler)\n\th.gp = gp\n\t// gp may not be running right now, but we can still get the M\n\t// it will run on since it's locked.\n\th.mp = gp.lockedm.ptr()\n\th.fv, h.regArgs, h.argp, h.argSize = fv, regArgs, argp, argSize\n\th.handleF = h.handle // Avoid allocating closure during signal\n\n\tdefer func() { testSigtrap = nil }()\n\tfor i := 0; ; i++ {\n\t\ttestSigtrap = h.inject\n\t\tnoteclear(&h.done)\n\t\th.err = \"\"\n\n\t\tif err := tkill(tid); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Wait for completion.\n\t\tnotetsleepg(&h.done, -1)\n\t\tif h.err != \"\" {\n\t\t\tswitch h.err {\n\t\t\tcase \"call not at safe point\":\n\t\t\t\tif returnOnUnsafePoint {\n\t\t\t\t\t// This is for TestDebugCallUnsafePoint.\n\t\t\t\t\treturn nil, h.err\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase \"retry _Grunnable\", \"executing on Go runtime stack\", \"call from within the Go runtime\":\n\t\t\t\t// These are transient states. Try to get out of them.\n\t\t\t\tif i < 100 {\n\t\t\t\t\tusleep(100)\n\t\t\t\t\tGosched()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, h.err\n\t\t}\n\t\treturn h.panic, nil\n\t}\n}", "func (h CallerHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {\n var file, line, function string\n if pc, filePath, lineNum, ok := runtime.Caller(CallerSkipFrameCount); ok {\n if f := runtime.FuncForPC(pc); f != nil {\n function = f.Name()\n }\n line = fmt.Sprintf(\"%d\", lineNum)\n parts := strings.Split(filePath, \"/\")\n file = parts[len(parts)-1]\n }\n e.Dict(\"logging.googleapis.com/sourceLocation\",\n zerolog.Dict().Str(\"file\", file).Str(\"line\", line).Str(\"function\", function))\n}", "func FuncOf(ctx context.Context, e Expr, vs Values) (Func, error) {\r\n\tfc, ok := ctxutil.Value(ctx, (*funcCache)(nil)).(*funcCache)\r\n\tvar fk funcKey\r\n\tif ok {\r\n\t\tfk = makeFuncKey(ctx, e, vs)\r\n\t\tif fn, ok := fc.load(fk); ok {\r\n\t\t\treturn fn, nil\r\n\t\t}\r\n\t}\r\n\tfn, err := funcFromExpr(ctx, e, vs)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tif ok {\r\n\t\tfn, _ = fc.loadOrStore(fk, fn)\r\n\t}\r\n\treturn fn, nil\r\n}", "func (_mr *MockDraOpMockRecorder) LookupRefById(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"LookupRefById\", reflect.TypeOf((*MockDraOp)(nil).LookupRefById), arg0)\n}", "func (_f6 *FakelogicalReader) ReadCalledWith(path string) (found bool) {\n\tfor _, call := range _f6.ReadCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Path, path) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (_f2 *FakeQualifier) QualifyCalledWith(ident1 fmt.Scanner) (found bool) {\n\tfor _, call := range _f2.QualifyCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func EvalCall(a, b Attrib) (*AddrCode, error) {\n\tentry_ := a.(*AddrCode).Symbol\n\tentry, ok := entry_.(*codegen.TargetEntry)\n\tvar varEntry *codegen.VariableEntry\n\tif !ok {\n\t\tif variable, ok1 := entry_.(*codegen.VariableEntry); ok1 {\n\t\t\tif t, ok2 := variable.Type().(codegen.FuncType); ok2 {\n\t\t\t\tentry = t.Target\n\t\t\t\tvarEntry = variable\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid function call statement\")\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"invalid function call statement\")\n\t\t}\n\t}\n\texprList, ok := b.([]*AddrCode)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unable to type cast %v to []*AddrCode\", b)\n\t}\n\n\tvar isSystem bool\n\n\tif entry.Target == \"printf\" || entry.Target == \"scanf\" {\n\t\tisSystem = true\n\t}\n\n\tif !isSystem && len(exprList) != len(entry.InType) {\n\t\treturn nil, fmt.Errorf(\"wrong number of arguments in function call. expected %d, got %d\", len(entry.InType), len(exprList))\n\t}\n\tcode := a.(*AddrCode).Code\n\tfor i := len(exprList) - 1; i >= 0; i-- {\n\t\tif !isSystem && !SameType(exprList[i].Symbol.Type(), entry.InType[i]) {\n\t\t\treturn nil, fmt.Errorf(\"wrong type of argument %d in function call. expected %v, got %v\", i, entry.InType[i], exprList[i].Symbol.Type())\n\t\t}\n\t\tif isSystem && i == 0 {\n\t\t\tif !SameType(exprList[i].Symbol.Type(), stringType) {\n\t\t\t\treturn nil, fmt.Errorf(\"wrong type of 1st argument in function call. expected %v, got %v\", stringType, exprList[i].Symbol.Type())\n\t\t\t}\n\t\t}\n\t\tevaluatedExpr := EvalWrapped(exprList[i])\n\t\tcode = append(code, evaluatedExpr.Code...)\n\t\tcode = append(code, codegen.IRIns{\n\t\t\tTyp: codegen.KEY,\n\t\t\tOp: codegen.PARAM,\n\t\t\tArg1: evaluatedExpr.Symbol,\n\t\t})\n\t}\n\tif varEntry == nil {\n\t\tcode = append(code, codegen.IRIns{\n\t\t\tTyp: codegen.KEY,\n\t\t\tOp: codegen.CALL,\n\t\t\tArg1: entry,\n\t\t})\n\t} else {\n\t\tcode = append(code, codegen.IRIns{\n\t\t\tTyp: codegen.KEY,\n\t\t\tOp: codegen.CALL,\n\t\t\tArg1: varEntry,\n\t\t})\n\t}\n\t// code = append(code, codegen.IRIns{\n\t// \tTyp: codegen.KEY,\n\t// \tOp: codegen.UNALLOC,\n\t// \tArg1: &codegen.LiteralEntry{\n\t// \t\tValue: len(exprList) * 4,\n\t// \t\tLType: intType,\n\t// \t},\n\t// })\n\tentry1 := CreateTemporary(entry.RetType)\n\tcode = append(code, entry1.Code...)\n\tcode = append(code, codegen.IRIns{\n\t\tTyp: codegen.KEY,\n\t\tOp: codegen.SETRET,\n\t\tArg1: entry1.Symbol,\n\t})\n\treturn &AddrCode{\n\t\tCode: code,\n\t\tSymbol: entry1.Symbol,\n\t}, nil\n}", "func (ast *Call) Eval(env *Env, ctx *Codegen, gen *ssa.Generator) (\n\tssa.Value, bool, error) {\n\n\t// Resolve called.\n\tvar pkgName string\n\tif len(ast.Ref.Name.Package) > 0 {\n\t\tpkgName = ast.Ref.Name.Package\n\t} else {\n\t\tpkgName = ast.Ref.Name.Defined\n\t}\n\tpkg, ok := ctx.Packages[pkgName]\n\tif !ok {\n\t\treturn ssa.Undefined, false,\n\t\t\tctx.Errorf(ast, \"package '%s' not found\", pkgName)\n\t}\n\t_, ok = pkg.Functions[ast.Ref.Name.Name]\n\tif ok {\n\t\treturn ssa.Undefined, false, nil\n\t}\n\t// Check builtin functions.\n\tfor _, bi := range builtins {\n\t\tif bi.Name != ast.Ref.Name.Name {\n\t\t\tcontinue\n\t\t}\n\t\tif bi.Type != BuiltinFunc {\n\t\t\treturn ssa.Undefined, false,\n\t\t\t\tfmt.Errorf(\"builtin %s used as function\", bi.Name)\n\t\t}\n\t\tif bi.Eval == nil {\n\t\t\treturn ssa.Undefined, false, nil\n\t\t}\n\t\treturn bi.Eval(ast.Exprs, env, ctx, gen, ast.Location())\n\t}\n\n\treturn ssa.Undefined, false, nil\n}", "func _caller(n int) string {\n\tif pc, _, _, ok := runtime.Caller(n); ok {\n\t\tfns := strings.Split(runtime.FuncForPC(pc).Name(), \"/\")\n\t\treturn fns[len(fns)-1]\n\t}\n\n\treturn \"unknown\"\n}", "func (*FuncExpr) iCallable() {}", "func (f EventHandlerFunc) Call(ctx context.Context, jobId string) error {\n\treturn f(ctx, jobId)\n}", "func this() *runtime.Func {\n pc := make([]uintptr, 10) // at least 1 entry needed\n runtime.Callers(2, pc)\n f:= runtime.FuncForPC(pc[1])\n return f\n}", "func (_f58 *FakeContext) WithRequestIDCalledWith(ident1 string) (found bool) {\n\tfor _, call := range _f58.WithRequestIDCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (_ArbSys *ArbSysCaller) AddressTableLookup(opts *bind.CallOpts, addr common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ArbSys.contract.Call(opts, &out, \"addressTable_lookup\", addr)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (mr *MockFullNodeMockRecorder) StateLookupID(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"StateLookupID\", reflect.TypeOf((*MockFullNode)(nil).StateLookupID), arg0, arg1, arg2)\n}", "func Lookup(code cid.Cid) (ActorInfo, bool) {\n\tact, ok := actorInfos[code]\n\treturn act, ok\n}", "func funcHasIP(ctx context.Context, out io.Writer, args []string) error {\n\tif len(args) != 1 {\n\t\treturn errors.New(\"usage: act has-ip [IP1] [IP2]... \")\n\t}\n\treturn executor.RunExecutorConfigReadOnly(ctx, func(executor executor.Executor) error {\n\t\tif err := executor.Runner.HasIP(out, args); err != nil {\n\t\t\tlogrus.Errorf(err.Error())\n\t\t}\n\t\treturn nil\n\t})\n}" ]
[ "0.55088776", "0.51450753", "0.5084626", "0.49590853", "0.49253467", "0.49151275", "0.49031597", "0.48806983", "0.48682708", "0.4830155", "0.48227826", "0.47652534", "0.47241217", "0.46917644", "0.4687812", "0.46794826", "0.46600193", "0.46538463", "0.4650809", "0.46494117", "0.46383056", "0.4636756", "0.46328318", "0.46300247", "0.46284673", "0.46276116", "0.4615816", "0.46115842", "0.46102592", "0.460791", "0.46028826", "0.45844704", "0.4571431", "0.4570194", "0.4517809", "0.45079294", "0.4503673", "0.4482793", "0.44807994", "0.44749445", "0.44696933", "0.44696933", "0.44656765", "0.4459201", "0.44465247", "0.44461298", "0.44372997", "0.4432157", "0.44203812", "0.44153333", "0.44046074", "0.44032925", "0.43953833", "0.4380883", "0.43755051", "0.4374393", "0.437411", "0.4363866", "0.43601498", "0.43555757", "0.4350508", "0.4336466", "0.43353626", "0.43329236", "0.43047968", "0.42990345", "0.42983863", "0.42951363", "0.42946437", "0.42926756", "0.4291027", "0.42868116", "0.42855924", "0.4285253", "0.42844692", "0.4277797", "0.4271881", "0.42712307", "0.42664817", "0.4253215", "0.42495072", "0.4245601", "0.42433628", "0.42422584", "0.42356083", "0.42322177", "0.42321402", "0.42276013", "0.4225643", "0.4225523", "0.42242858", "0.42200407", "0.42143106", "0.42129484", "0.42105737", "0.42098084", "0.42041355", "0.42040923", "0.42015338", "0.4200038" ]
0.8261184
0
HasArgs returns whether the given ssa.Instruction has `typ` type args
HasArgs возвращает значение, указывающее, имеет ли заданная ssa.Instruction аргументы типа `typ`
func HasArgs(instr ssa.Instruction, typ types.Type) bool { call, ok := instr.(ssa.CallInstruction) if !ok { return false } ssaCall := call.Value() if ssaCall == nil { return false } for _, arg := range ssaCall.Call.Args { if types.Identical(arg.Type(), typ) { return true } } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i Instruction) IsVariadic() bool {\n\treturn len(i.Arities()) > 1\n}", "func (TypesObject) IsVariadicParam() bool { return boolResult }", "func (f flagString) HasArg() bool {\n\treturn true\n}", "func (a *Args) Has(arg rune) bool {\n\t_, ok := a.marhalers[arg]\n\treturn ok\n}", "func (f flagBool) HasArg() bool {\n\treturn false\n}", "func isTypeParam(_ *ast.Field, _ []*ast.FuncDecl, _ []*ast.FuncLit) bool {\n\treturn false\n}", "func (p *FuncInfo) IsVariadic() bool {\n\tif p.nVariadic == 0 {\n\t\tlog.Panicln(\"FuncInfo is unintialized.\")\n\t}\n\treturn p.nVariadic == nVariadicVariadicArgs\n}", "func (t *Type) IsFuncArgStruct() bool", "func (*InstTrunc) isInst() {}", "func hasContextParam(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 context, true\n\tif p1.Elem() == contextType {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (*InstFPTrunc) isInst() {}", "func (t Type) HasAttr(name string) bool {\n\treturn t.AttrType(name) != NilType\n}", "func (m *Method) HasParameters() bool {\n\treturn len(m.Parameters) != 0\n}", "func (*InstZExt) isInst() {}", "func HasFlag(args []string, flag string) bool {\n\tfor _, item := range args {\n\t\tif item == flag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsHasMethod(st interface{}, methodName string) bool {\n\treturn HasMethod(st, methodName)\n}", "func isOperandOfLen(i interface{}, length int) bool {\n\toperand, ok := i.(Operand)\n\treturn ok && len(operand) == length\n}", "func (n Name) HasType() bool {\n\t_, s := n.GetLookupAndType()\n\treturn s != \"\"\n}", "func isVariadicArgument(value string) (bool, string) {\n\tif !isFlag(value) && strings.HasSuffix(value, \"...\") {\n\t\treturn true, strings.TrimRight(value, \"...\") // trim `...` suffix\n\t}\n\n\treturn false, \"\"\n}", "func typeIs(target string, src interface{}) bool {\n\treturn target == typeOf(src)\n}", "func Argsize(t *Type) int", "func analysisArgs() bool {\n\t//没有选项的情况显示帮助信息\n\tif len(os.Args) <= 1 {\n\t\tfor _, v := range gCommandItems {\n\t\t\tlog(v.mBuilder.getCommandDesc())\n\t\t}\n\t\treturn false\n\t}\n\n\t//解析指令\n\targs := os.Args[1:]\n\tvar pItem *sCommandItem = nil\n\tfor i := 0; i < len(args); i++ {\n\t\tparm := args[i]\n\t\tif parm[0] == '-' {\n\t\t\tpItem = findCommandItem(parm)\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mCanExecute = true\n\t\t} else {\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mParm = append(pItem.mParm, parm)\n\t\t}\n\t}\n\n\treturn true\n}", "func hasName(t Type) bool {\n\tswitch t.(type) {\n\tcase *Basic, *Named, *TypeParam:\n\t\treturn true\n\t}\n\treturn false\n}", "func (a *Args) IsOn(s string) bool {\n\tfor _, u := range a.uniOpts {\n\t\tif u == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (*InstFPExt) isInst() {}", "func attrsContain(attrs []netlink.Attribute, typ uint16) bool {\n\tfor _, a := range attrs {\n\t\tif a.Type == typ {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func CountArgs(args MyType) int {\n\treturn len(args)\n}", "func check_args(parsed_query []string, num_expected int) bool {\n\treturn (len(parsed_query) >= num_expected)\n}", "func (t Type) IsUnary() bool {\n\treturn unop_start < t && t < unop_end\n}", "func hasUpdateArg(args []string) bool {\n\tfor _, arg := range args {\n\t\tif ArgWorkflowUpdate == arg {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *WorkflowCliCommandAllOf) HasType() bool {\n\tif o != nil && o.Type != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p RProc) IsNoArg() bool { return (C._mrb_rproc_flags(p.p) & C.MRB_PROC_NOARG) != 0 }", "func IsCommandLineArguments(id PackageID) bool {\n\treturn strings.Contains(string(id), \"command-line-arguments\")\n}", "func (*InstSExt) isInst() {}", "func (t Type) Is(ty Type) bool {\n\treturn t&ty != 0\n}", "func (l Lambda) IsThunk() bool {\n\treturn len(l.arguments) == 0\n}", "func (s *Instruction) IsInstType(instructionType InstType) bool {\n\treturn instructionType == s.Type\n}", "func (p Typed) IsCommand() bool {\n\treturn p.Kind() == TypeIDKindCommand\n}", "func IsHasMethod(v interface{}, methodName string) bool {\n\treturn String(methodName).IsInArrayIgnoreCase(GetMethods(v))\n}", "func IsType(v interface{}, params ...string) bool {\n\tif len(params) == 1 {\n\t\ttyp := params[0]\n\t\treturn strings.Replace(reflect.TypeOf(v).String(), \" \", \"\", -1) == strings.Replace(typ, \" \", \"\", -1)\n\t}\n\treturn false\n}", "func (runner *suiteRunner) checkFixtureArgs() bool {\n succeeded := true\n argType := reflect.Typeof(&C{})\n for _, fv := range []*reflect.FuncValue{runner.setUpSuite,\n runner.tearDownSuite,\n runner.setUpTest,\n runner.tearDownTest} {\n if fv != nil {\n fvType := fv.Type().(*reflect.FuncType)\n if fvType.In(1) != argType || fvType.NumIn() != 2 {\n succeeded = false\n runner.runFunc(fv, fixtureKd, func(c *C) {\n c.logArgPanic(fv, \"*gocheck.C\")\n c.status = panickedSt\n })\n }\n }\n }\n return succeeded\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 (typ Type) HasAny(t Type) bool { return typ&t != 0 }", "func HasMethod(st interface{}, methodName string) bool {\n\tvalueIface := reflect.ValueOf(st)\n\n\t// Check if the passed interface is a pointer\n\tif valueIface.Type().Kind() != reflect.Ptr {\n\t\t// Create a new type of Iface, so we have a pointer to work with\n\t\tvalueIface = reflect.New(reflect.TypeOf(st))\n\t}\n\n\t// Get the method by name\n\tmethod := valueIface.MethodByName(methodName)\n\treturn method.IsValid()\n}", "func doAnyParametersExist(args ...string) bool {\n\tif args == nil {\n\t\treturn false\n\t}\n\tfor _, arg := range args {\n\t\tif arg != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func isTypeParam(t Type) bool {\n\t_, ok := t.(*TypeParam)\n\treturn ok\n}", "func (*InstAddrSpaceCast) isInst() {}", "func (args MyType) CountArgs() int {\n\treturn len(args)\n}", "func IsComplete(t Type) bool {\n\tswitch v := t.Root().(type) {\n\tcase *Variable:\n\t\treturn false\n\tcase *Operator:\n\t\tfor _, a := range v.Args {\n\t\t\tif !IsComplete(a) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func suitable(m reflect.Method) bool {\n\treturn m.Type.NumIn() <= 2\n}", "func (*InstBitCast) isInst() {}", "func (x *fastReflection_PositionalArgDescriptor) Has(fd protoreflect.FieldDescriptor) bool {\n\tswitch fd.FullName() {\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.proto_field\":\n\t\treturn x.ProtoField != \"\"\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.varargs\":\n\t\treturn x.Varargs != false\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.optional\":\n\t\treturn x.Optional != false\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.autocli.v1.PositionalArgDescriptor\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.autocli.v1.PositionalArgDescriptor does not contain field %s\", fd.FullName()))\n\t}\n}", "func (a *Args) HasOpt(key string) bool {\n\tfor _, b := range a.binOpts {\n\t\tif b.key == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *DeviceParameterValue) HasType() bool {\n\tif o != nil && o.Type != nil {\n\t\treturn true\n\t}\n\n\treturn false\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 (v *Argument) IsSetType() bool {\n\treturn v != nil && v.Type != nil\n}", "func isTyped(t Type) bool {\n\t// isTyped is called with types that are not fully\n\t// set up. Must not call under()!\n\tb, _ := t.(*Basic)\n\treturn b == nil || b.info&IsUntyped == 0\n}", "func isNoCopyType(typ types.Type) bool {\n\tst, ok := typ.Underlying().(*types.Struct)\n\tif !ok {\n\t\treturn false\n\t}\n\tif st.NumFields() != 0 {\n\t\treturn false\n\t}\n\n\tnamed, ok := typ.(*types.Named)\n\tif !ok {\n\t\treturn false\n\t}\n\tif named.NumMethods() != 1 {\n\t\treturn false\n\t}\n\tmeth := named.Method(0)\n\tif meth.Name() != \"Lock\" {\n\t\treturn false\n\t}\n\tsig := meth.Type().(*types.Signature)\n\tif sig.Params().Len() != 0 || sig.Results().Len() != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (t *Transaction) HasAttribute(typ AttrType) bool {\n\tfor i := range t.Attributes {\n\t\tif t.Attributes[i].Type == typ {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (calls Calls) Has(method string, args ...interface{}) bool {\n\twant := call{method, args}\n\tfor _, have := range calls {\n\t\tif reflect.DeepEqual(want, have) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func CanConvertArgs(args []DataType, params []FunctionParameter) bool {\n\n\tif len(args) != len(params) {\n\t\treturn false\n\t}\n\n\tfor i, param := range params {\n\t\targ := args[i]\n\n\t\tif param.AutoConvert {\n\t\t\tif !CanConvert(arg, param.DType) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif !TypeMatches(arg, param.DType) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func CommandArgExists(mapArr map[string]string, key string) bool {\n\tif _, ok := mapArr[key]; ok {\n\t\treturn true\n\t}\n\treturn false\n}", "func (typ Type) HasAll(t Type) bool { return typ&t == t }", "func HasVectorExpansions(t BareType) bool { return vectorTypes[t] != nil }", "func execIsInterface(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := types.IsInterface(args[0].(types.Type))\n\tp.Ret(1, ret)\n}", "func (*InstFPToUI) isInst() {}", "func (args *Args) isEmpty() bool {\n\treturn len(args.items) == 0\n}", "func IsUint(data interface{}) bool {\n\treturn typeIs(data,\n\t\treflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32,\n\t\treflect.Uint64,\n\t\treflect.Uintptr,\n\t)\n}", "func (o Op) Variadic() bool {\n\treturn o == In || o == NotIn\n}", "func (SinkType) Is(typ string) bool { return boolResult }", "func (ExprType) HasMethod(fn string) bool { return boolResult }", "func (d Definition) IsValid(args ...interface{}) bool {\n\tif d.Inputs == nil {\n\t\treturn true\n\t}\n\tif len(args) != len(d.Inputs) {\n\t\treturn false\n\t}\n\tfor i, a := range args {\n\t\tswitch x := d.Inputs[i].(type) {\n\t\tcase reflect.Type:\n\t\t\txv := reflect.ValueOf(x)\n\t\t\tav := reflect.ValueOf(a)\n\t\t\tif !xv.IsNil() {\n\t\t\t\tif !av.IsValid() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif ak := reflect.TypeOf(a).Kind(); (ak == reflect.Chan || ak == reflect.Func || ak == reflect.Map || ak == reflect.Ptr || ak == reflect.Slice) && av.IsNil() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif !av.Type().AssignableTo(x) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Kind:\n\t\t\txv := reflect.ValueOf(x)\n\t\t\tav := reflect.ValueOf(a)\n\t\t\tif xv.IsValid() || !xv.IsNil() {\n\t\t\t\tif !av.IsValid() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif xv.IsValid() && av.Type().Kind() != x {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (x *fastReflection_PositionalArgDescriptor) IsValid() bool {\n\treturn x != nil\n}", "func IsBuiltin(t Type) bool {\n\tname, ok := t.(TName)\n\treturn ok && IsBuiltinTypeString(name.TypeName)\n}", "func (i KeyInfo) IsType(typeName string) bool {\n\tfor _, t := range i.Types {\n\t\tif t == typeName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t Token) IsLength() bool {\n\tif t.TokenType == css.DimensionToken {\n\t\treturn true\n\t} else if t.TokenType == css.NumberToken && t.Data[0] == '0' {\n\t\treturn true\n\t} else if t.TokenType == css.FunctionToken {\n\t\tfun := ToHash(t.Data[:len(t.Data)-1])\n\t\tif fun == Calc || fun == Min || fun == Max || fun == Clamp || fun == Attr || fun == Var || fun == Env {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (args Arguments) Is(objects ...interface{}) bool {\n\tfor i, obj := range args {\n\t\tif obj != objects[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func checkIns(m reflect.Method) (in0, in1, in2, in3 reflect.Type, err error) {\n\tmtype := m.Type\n\tif mtype.NumIn() != 4 {\n\t\terr = fmt.Errorf(\"method %s has wrong number of ins: %d\", m.Name, mtype.NumIn())\n\t\treturn\n\t}\n\tin0 = mtype.In(0)\n\tin1 = mtype.In(1)\n\tif !in1.Implements(typeOfContext) {\n\t\terr = fmt.Errorf(\"method %s context type not implements context.Context: %s\", m.Name, in1)\n\t\treturn\n\t}\n\tin2 = mtype.In(2)\n\tif !isExportedOrBuiltinType(in2) {\n\t\terr = fmt.Errorf(\"method %s args type not exported: %s\", m.Name, in2)\n\t\treturn\n\t}\n\tin3 = mtype.In(3)\n\tif in3.Kind() != reflect.Ptr && in3 != typeOfNilInterface {\n\t\terr = fmt.Errorf(\"method %s reply type not a pointer or interface{}: %s\", m.Name, in3)\n\t\treturn\n\t}\n\tif !isExportedOrBuiltinType(in3) {\n\t\terr = fmt.Errorf(\"method %s reply type not exported: %s\", m.Name, in3)\n\t\treturn\n\t}\n\treturn\n}", "func (p *Packet) HasAttr(key AttributeType) bool {\n\tfor _, a := range p.Attrs {\n\t\tif a.Type() == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func ServerArgsPresent(neededArgs []string) bool {\n\tcurrentArgs := K3sServerArgs()\n\tfor _, arg := range neededArgs {\n\t\tif !contains(currentArgs, arg) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p ParameterFile) IsArray() bool {\n\treturn strings.HasSuffix(p.Type, \"[]\")\n}", "func hasType(node ast.Node) bool {\n\tswitch n := node.(type) {\n\tcase *ast.BinaryNode:\n\t\tif hasType(n.Left) || hasType(n.Right) {\n\t\t\treturn true\n\t\t}\n\tcase *ast.IdentifierNode:\n\t\tif n.Value == \"type\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (obj *testInstruction) IsInstruction() bool {\n\treturn obj.ins != nil\n}", "func occursInType(v Type, t2 Type) bool {\n\troot := t2.Root()\n\tif Equals(root, v) {\n\t\treturn true\n\t}\n\tif to, ok := root.(*Operator); ok {\n\t\treturn OccursIn(v, to.Args)\n\t}\n\treturn false\n}", "func (ob *PyObject) HasAttr(name string) bool {\n\tattr := C.CString(name)\n\tdefer C.free(unsafe.Pointer(attr))\n\treturn C.PyObject_HasAttrString(ob.rawptr, attr) > 0\n}", "func (fn *Function) TypeArgs() []types.Type { return fn.typeargs }", "func validateArgs(linkIndex int, fn reflect.Type, args []Argument) error {\n\tif !fn.IsVariadic() && (fn.NumIn() != len(args)) {\n\t\treturn argumentMismatchError(linkIndex, len(args), fn.NumIn())\n\t}\n\n\treturn nil\n}", "func HasEntry(entries interface{}, entry interface{}) bool {\n\tcontainerValue := reflect.ValueOf(entries)\n\n\tswitch reflect.TypeOf(entries).Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\tfor i := 0; i < containerValue.Len(); i++ {\n\t\t\tif containerValue.Index(i).Interface() == entry {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\tcase reflect.Map:\n\t\tif containerValue.MapIndex(reflect.ValueOf(entry)).IsValid() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (w *whisperer) HasParameters(paths ...*string) (bool, error) {\n\tfilters := []*ssm.ParameterStringFilter{\n\t\t{\n\t\t\tKey: aws.String(\"Name\"),\n\t\t\tOption: aws.String(\"Equals\"),\n\t\t\tValues: paths,\n\t\t},\n\t}\n\tparameters := []*ssm.ParameterMetadata{}\n\tinput := &ssm.DescribeParametersInput{ParameterFilters: filters}\n\terr := w.SSMClient.DescribeParametersPages(input, func(out *ssm.DescribeParametersOutput, lastPage bool) bool {\n\t\tparameters = append(parameters, out.Parameters...)\n\t\treturn !lastPage\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfmt.Printf(\"Parameters: %+v\\n\", parameters)\n\treturn len(parameters) == len(paths), nil\n}", "func (o *WorkflowSshCmd) HasCommandType() bool {\n\tif o != nil && o.CommandType != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func DiagnoseInferableTypeArgs(fset *token.FileSet, inspect *inspector.Inspector, start, end token.Pos, pkg *types.Package, info *types.Info) []analysis.Diagnostic {\n\treturn nil\n}", "func validArgs(args *runtimeArgs) bool {\n\tflag.Usage = showHelp\n\n\targs.fg = flag.String(\"fg\", \"black\", \"foreground color\")\n\targs.bg = flag.String(\"bg\", \"green\", \"background color\")\n\n\tflag.Parse()\n\n\tif args.fg == nil || hue.StringToHue[*args.fg] == 0 {\n\t\tbadColor(*args.fg) // prints an error message w/ a list of supported colors\n\t\treturn false\n\t}\n\n\tif args.fg == nil || hue.StringToHue[*args.bg] == 0 {\n\t\tbadColor(*args.bg)\n\t\treturn false\n\t}\n\n\t// Get the remaining flags, which should\n\t// consist of a pattern, and optionally, one or more file names.\n\trem := flag.Args()\n\n\tswitch {\n\tcase len(rem) == 0:\n\t\tfmt.Println(\"Error: No pattern specified.\")\n\t\tshowHelp()\n\t\treturn false\n\tcase len(rem) == 1:\n\t\targs.pattern = &rem[0]\n\tcase len(rem) >= 2:\n\t\targs.pattern = &rem[0]\n\n\t\tfor i := 1; i < len(rem); i++ {\n\t\t\targs.files = append(args.files, &rem[i])\n\t\t}\n\t}\n\n\treturn true\n}", "func argsOK() bool {\n\tif len(os.Args) > 1 {\n\t\tif os.Args[1] == \"--file\" && len(os.Args[2]) > 0 {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}", "func (s ReleaseSpec) IsKindExecute() (bool, error) {\n\tswitch s.Type {\n\tcase ReleaseImageSpecType:\n\t\tif s.ReleaseImageSpec != nil && s.ReleaseImageSpec.Kind == update.ReleaseKindExecute {\n\t\t\treturn true, nil\n\t\t}\n\tcase ReleaseContainersSpecType:\n\t\tif s.ReleaseContainersSpec != nil && s.ReleaseContainersSpec.Kind == update.ReleaseKindExecute {\n\t\t\treturn true, nil\n\t\t}\n\n\tdefault:\n\t\treturn false, errors.Errorf(\"unknown release spec type %s\", s.Type)\n\t}\n\treturn false, nil\n}", "func (m NoSides) HasQuantityType() bool {\n\treturn m.Has(tag.QuantityType)\n}", "func TypeHasCapability(kv *api.KV, deploymentID, typeName, capabilityTypeName string) (bool, error) {\n\tcapabilities, err := GetCapabilitiesOfType(kv, deploymentID, typeName, capabilityTypeName)\n\treturn len(capabilities) > 0, err\n}", "func (t Type) IsKeyword() bool {\n\treturn key_start < t && t < key_end\n}", "func checkArguments(hash string, privateKey string) bool {\n\t// easy check\n\t// if len(hash) != 46 || len(privateKey) != 64 {\n\t// \treturn false\n\t// }\n\n\treturn true\n}", "func (v *Function) IsSetArguments() bool {\n\treturn v != nil && v.Arguments != nil\n}", "func isCompatibleArg(arg, param types.Type) bool {\n\tif isCompatible(arg, param) {\n\t\treturn true\n\t}\n\tif arg, ok := arg.(*types.Array); ok {\n\t\tif param, ok := param.(*types.Array); ok {\n\t\t\t// TODO: Check for other compatible types (e.g. pointers, array names,\n\t\t\t// strings).\n\t\t\tif param.Len != 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn types.Equal(arg.Elem, param.Elem)\n\t\t}\n\t}\n\treturn false\n}" ]
[ "0.6620399", "0.6070014", "0.58602", "0.5559968", "0.551633", "0.5394115", "0.53795916", "0.5353696", "0.5310007", "0.5298867", "0.52459556", "0.52079266", "0.5189788", "0.51717234", "0.51651365", "0.5159262", "0.51278657", "0.5124402", "0.51076514", "0.5105842", "0.50955737", "0.50827265", "0.5068359", "0.5043159", "0.5039188", "0.50265473", "0.49888113", "0.4971622", "0.4945414", "0.4944646", "0.49427438", "0.49421072", "0.49364662", "0.49363536", "0.49237967", "0.49193102", "0.49118662", "0.49045524", "0.48871848", "0.48817638", "0.48798928", "0.48790714", "0.48713198", "0.48702854", "0.48225248", "0.48197818", "0.4816477", "0.48151174", "0.48118684", "0.48115885", "0.48070294", "0.47893637", "0.47764906", "0.47680828", "0.47628078", "0.476057", "0.47513914", "0.4744463", "0.47405696", "0.47395328", "0.47338685", "0.47167948", "0.4710176", "0.47039503", "0.47037658", "0.47032392", "0.46965584", "0.46948636", "0.46811777", "0.46742845", "0.46705315", "0.4666586", "0.46657553", "0.46553543", "0.46509445", "0.46380863", "0.46333498", "0.46117765", "0.4609888", "0.46053088", "0.46036202", "0.4599336", "0.4594286", "0.4590657", "0.458976", "0.45880038", "0.45865765", "0.45831543", "0.45775568", "0.45772898", "0.45764175", "0.45713258", "0.4564464", "0.45631468", "0.45474452", "0.45434615", "0.45377478", "0.45372462", "0.453515", "0.4533453" ]
0.8171181
0
withClerk invokes the specified callback with a clerk that manages the specified queue. If there is no such clerk, withClerk first creates one. The clerk's reference count is incremented for the duration of the callback. withClerk returns whatever the callback returns.
withClerk вызывает указанный обратный вызов с клерком, управляющим указанной очередью. Если такой клерк отсутствует, withClerk сначала создает его. Счетчик ссылок клерка увеличивается на время выполнения обратного вызова. withClerk возвращает то, что возвращает обратный вызов.
func (registry *Registry) withClerk(queue string, callback func(*clerk) error) error { registry.mutex.Lock() entry, found := registry.queues[queue] if !found { entry = &refCountedClerk{ Clerk: clerk{ // TODO: context Enqueue: make(chan messageSend), Dequeue: make(chan messageReceive), Registry: registry, Queue: queue, }, RefCount: 0, } go entry.Clerk.Run() registry.queues[queue] = entry } entry.RefCount++ registry.mutex.Unlock() result := callback(&entry.Clerk) registry.mutex.Lock() entry.RefCount-- registry.mutex.Unlock() return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *ModuleManager) CallWithCallback(topic string, f, cb interface{}, cbParams, params []interface{}) (err error) {\n\tif m := this.GetModule(topic); m != nil {\n\t\terr = m.CallWithCallback(f, cb, cbParams, params)\n\t} else {\n\t\t// fmt.Println(this)\n\t\terr = Post.PutQueueWithCallback(f, cb, cbParams, params...)\n\t}\n\treturn\n}", "func (client *Client) GetClusterQueueInfoWithCallback(request *GetClusterQueueInfoRequest, callback func(response *GetClusterQueueInfoResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetClusterQueueInfoResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetClusterQueueInfo(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func GoCallbackWrapper(ptr_q *unsafe.Pointer, ptr_nfad *unsafe.Pointer) int {\n q := (*Queue)(unsafe.Pointer(ptr_q))\n payload := build_payload(q.c_gh, ptr_nfad)\n return q.cb(payload)\n}", "func (q *Queue) SetCallback(cb Callback) error {\n\tq.cb = cb\n\treturn nil\n}", "func (ac *asyncCallbacksHandler) push(f func()) {\n\tac.cbQueue <- f\n}", "func (r *RabbitMq) registerCallback() {\r\n\tr.RabbitMqChannel.QueueDeclare(\r\n\t\t\"callback-mq-producer\",\r\n\t\ttrue,\r\n\t\tfalse,\r\n\t\tfalse,\r\n\t\tfalse,\r\n\t\tnil,\r\n\t)\r\n\tr.StartConsumeCallback()\r\n\tlog.Println(\"Create Queue callback\")\r\n}", "func (x *MQQueueManager) Ctl(goOperation int32, goctlo *MQCTLO) error {\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\tvar mqOperation C.MQLONG\n\tvar mqctlo C.MQCTLO\n\n\tmqOperation = C.MQLONG(goOperation)\n\tcopyCTLOtoC(&mqctlo, goctlo)\n\n\t// Need to make sure control information is available before the callback\n\t// is enabled. So this gets setup even if the MQCTL fails.\n\tkey := makePartialKey(x.hConn)\n\tmapLock()\n\tfor k, info := range cbMap {\n\t\tif strings.HasPrefix(k, key) {\n\t\t\tinfo.connectionArea = goctlo.ConnectionArea\n\t\t}\n\t}\n\tmapUnlock()\n\n\tC.MQCTL(x.hConn, mqOperation, (C.PMQVOID)(unsafe.Pointer(&mqctlo)), &mqcc, &mqrc)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQCTL\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn &mqreturn\n\t}\n\n\treturn nil\n}", "func (client *Client) RecognizeFlowerWithCallback(request *RecognizeFlowerRequest, callback func(response *RecognizeFlowerResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RecognizeFlowerResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RecognizeFlower(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) GetClusterQueueInfoWithChan(request *GetClusterQueueInfoRequest) (<-chan *GetClusterQueueInfoResponse, <-chan error) {\n\tresponseChan := make(chan *GetClusterQueueInfoResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.GetClusterQueueInfo(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (ac *asyncCallbacksHandler) run() {\n\tfor {\n\t\tf := <-ac.cbQueue\n\t\tif f == nil {\n\t\t\treturn\n\t\t}\n\t\tf()\n\t}\n}", "func (p *asyncPipeline) DoCmdWithCallback(cmder redis.Cmder, callback func(redis.Cmder) error) error {\n\n\tif cmder == nil {\n\t\treturn fmt.Errorf(\"Cmder passing in is nil\")\n\t}\n\n\tcmders := make([]redis.Cmder, 0)\n\tcmders = append(cmders, cmder)\n\tp.chQueue <- &asyncPipelineCmd{\n\t\tcmders: cmders,\n\t\tcallback: func(cmders []redis.Cmder) error {\n\t\t\tfor _, cmder := range cmders {\n\t\t\t\tif callback != nil {\n\t\t\t\t\tif err := callback(cmder); 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\treturn nil\n\t\t},\n\t}\n\treturn nil\n}", "func WithConcurrency(concurrency int) Option {\n\treturn func(c *queue) {\n\t\tc.concurrency = concurrency\n\t}\n}", "func (q *Queue) Queue(action func()) {\n\tif !q.stopped {\n\t\tq.pendingC <- action\n\t} else {\n\t\tq.l.Error(\"queue failed: queue is stopped, cannot queue more elements\")\n\t}\n}", "func (client *Client) GetTotalQueueReportWithCallback(request *GetTotalQueueReportRequest, callback func(response *GetTotalQueueReportResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetTotalQueueReportResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetTotalQueueReport(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) CreateFabricChannelWithCallback(request *CreateFabricChannelRequest, callback func(response *CreateFabricChannelResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFabricChannelResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFabricChannel(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func consumer(queueChannel chan int, doneChannel chan bool) {\n\tdefer reset.Done()\n\n\tvar counter = 0\n\tfor value := range queueChannel {\n\t\tprintln(\"Consuming value from queue: \" + strconv.Itoa(value))\n\t\tcounter++\n\t\tif counter == 23 {\n\t\t\tprintln(\"Consumed 23 values from queue Channel, stop consuming.\")\n\t\t\tclose(doneChannel)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (ec *EstablishingController) QueueCRD(key string, timeout time.Duration) {\r\n\tec.queue.AddAfter(key, timeout)\r\n}", "func (client *Client) QueryInnerJobWithCallback(request *QueryInnerJobRequest, callback func(response *QueryInnerJobResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryInnerJobResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryInnerJob(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (clt *Client) redisListener(buf io.ReadWriter, queue chan *lib.Request) {\n\tlib.Debugf(\"Net listener started\")\n\tdefer clt.close() // Will force to close net connection\n\n\treader := redis.NewRespReader(buf)\n\tfor req := range queue {\n\t\tr := reader.Read()\n\t\tif req == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif r.Err != nil && r.IsType(redis.IOErr) {\n\t\t\tif redis.IsTimeout(r) {\n\t\t\t\tlog.Printf(\"Timeout (%d secs) at %s\", clt.config.Timeout, clt.config.Host())\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error with server %s connection: %s\", clt.config.Host(), r.Err)\n\t\t\t}\n\t\t\tif req.Conn != nil {\n\t\t\t\trespKO.WriteTo(req.Conn)\n\t\t\t}\n\t\t\tclt.disconnect()\n\t\t\treturn\n\t\t}\n\n\t\tif clt.config.Compress || clt.config.Uncompress || clt.config.Gzip != 0 || clt.config.Gunzip {\n\t\t\tr.Uncompress()\n\t\t}\n\n\t\tif req.Conn != nil {\n\t\t\tr.WriteTo(req.Conn)\n\t\t}\n\t\tr.ReleaseBuffers()\n\t}\n\tlib.Debugf(\"Net listener exiting\")\n}", "func (client *Client) AddBsnFabricBizChainWithCallback(request *AddBsnFabricBizChainRequest, callback func(response *AddBsnFabricBizChainResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *AddBsnFabricBizChainResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.AddBsnFabricBizChain(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (c *consulClient) CAS(ctx context.Context, key string, out interface{}, f CASCallback) error {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"Consul CAS\", opentracing.Tag{Key: \"key\", Value: key})\n\tdefer span.Finish()\n\tvar (\n\t\tindex = uint64(0)\n\t\tretries = 10\n\t\tretry = true\n\t\tintermediate interface{}\n\t)\n\tfor i := 0; i < retries; i++ {\n\t\tkvp, _, err := c.kv.Get(key, queryOptions)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error getting %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tif kvp != nil {\n\t\t\tif err := json.NewDecoder(bytes.NewReader(kvp.Value)).Decode(out); err != nil {\n\t\t\t\tlog.Errorf(\"Error deserialising %s: %v\", key, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tindex = kvp.ModifyIndex // if key doesn't exist, index will be 0\n\t\t\tintermediate = out\n\t\t}\n\n\t\tintermediate, retry, err = f(intermediate)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error CASing %s: %v\", key, err)\n\t\t\tif !retry {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif intermediate == nil {\n\t\t\tpanic(\"Callback must instantiate value!\")\n\t\t}\n\n\t\tvalue := bytes.Buffer{}\n\t\tif err := json.NewEncoder(&value).Encode(intermediate); err != nil {\n\t\t\tlog.Errorf(\"Error serialising value for %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tok, _, err := c.kv.CAS(&consul.KVPair{\n\t\t\tKey: key,\n\t\t\tValue: value.Bytes(),\n\t\t\tModifyIndex: index,\n\t\t}, writeOptions)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error CASing %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Error CASing %s, trying again %d\", key, index)\n\t\t\tcontinue\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"Failed to CAS %s\", key)\n}", "func (client *Client) ContextQueryLogWithCallback(request *ContextQueryLogRequest, callback func(response *ContextQueryLogResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ContextQueryLogResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ContextQueryLog(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) AssociateAclsWithListenerWithCallback(request *AssociateAclsWithListenerRequest, callback func(response *AssociateAclsWithListenerResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *AssociateAclsWithListenerResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.AssociateAclsWithListener(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func NewSucker(amqpURI, queueName, ctag string, work func(delivery amqp.Delivery) error) (*Spaceballz, error) {\n\tc := &Spaceballz{\n\t\tconn: nil,\n\t\tchannel: nil,\n\t\ttag: ctag,\n\t\tdone: make(chan error),\n\t\tWork: work,\n\t}\n\n\tvar err error\n\n\tlog.Printf(\"dialing %q\", amqpURI)\n\tc.conn, err = amqp.Dial(amqpURI)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Dial: %s\", err)\n\t}\n\n\tgo func() {\n\t\tfmt.Printf(\"closing: %s\", <-c.conn.NotifyClose(make(chan *amqp.Error)))\n\t}()\n\n\tlog.Printf(\"got Connection, getting Channel\")\n\tc.channel, err = c.conn.Channel()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Channel: %s\", err)\n\t}\n\n\tdeliveries, err := c.channel.Consume(\n\t\tqueueName, // name\n\t\tc.tag, // consumerTag,\n\t\tfalse, // noAck\n\t\tfalse, // exclusive\n\t\tfalse, // noLocal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Queue Consume: %s\", err)\n\t}\n\n\tgo c.handle(deliveries, c.done)\n\n\treturn c, nil\n}", "func Call(f func()) {\n\tcheckRun()\n\tdone := make(chan struct{})\n\tcallQueue <- func() {\n\t\tf()\n\t\tdone <- struct{}{}\n\t}\n\t<-done\n}", "func (client *Client) GetClusterMetricsWithCallback(request *GetClusterMetricsRequest, callback func(response *GetClusterMetricsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetClusterMetricsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetClusterMetrics(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (p *asyncPipeline) DoCmdsWithCallback(cmders []redis.Cmder, callback func([]redis.Cmder) error) error {\n\n\tfor _, cmder := range cmders {\n\t\tif cmder == nil {\n\t\t\treturn fmt.Errorf(\"Cmder passing in is nil\")\n\t\t}\n\t}\n\tp.chQueue <- &asyncPipelineCmd{\n\t\tcmders: cmders,\n\t\tcallback: callback,\n\t}\n\n\treturn nil\n}", "func (c *QueuedChan) run() {\n\t// Notify close channel coroutine.\n\tdefer close(c.done)\n\n\tfor {\n\t\tvar elem *list.Element\n\t\tvar item interface{}\n\t\tvar popc chan<- interface{}\n\n\t\t// Get front element of the queue.\n\t\tif elem = c.Front(); nil != elem {\n\t\t\tpopc, item = c.popc, elem.Value\n\t\t}\n\n\t\tselect {\n\t\t// Put the new object into the end of queue.\n\t\tcase i := <-c.pushc:\n\t\t\tc.PushBack(i)\n\t\t// Remove the front element from queue if send out success\n\t\tcase popc <- item:\n\t\t\tc.List.Remove(elem)\n\t\t// Control command\n\t\tcase cmd := <-c.ctrlc:\n\t\t\tc.control(cmd)\n\t\t// Channel is closed\n\t\tcase <-c.close:\n\t\t\treturn\n\t\t}\n\t\t// Update channel length\n\t\tatomic.StoreInt32(&c.len, int32(c.List.Len()))\n\t}\n}", "func WithQueue(queue workqueue.RateLimitingInterface) Option {\n\treturn func(config *queueInformerConfig) {\n\t\tconfig.queue = queue\n\t}\n}", "func (b *testBroker) queue(pipe *Pipeline) *testQueue {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tq, ok := b.queues[pipe]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn q\n}", "func worker(queue workqueue.RateLimitingInterface, resourceType string, maxRetries int, forgetAfterSuccess bool, reconciler func(key string) error) func() {\n\treturn func() {\n\t\texit := false\n\t\tfor !exit {\n\t\t\texit = func() bool {\n\t\t\t\tkey, quit := queue.Get()\n\t\t\t\tif quit {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tdefer queue.Done(key)\n\n\t\t\t\terr := reconciler(key.(string))\n\t\t\t\tif err == nil {\n\t\t\t\t\tif forgetAfterSuccess {\n\t\t\t\t\t\tqueue.Forget(key)\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\tif queue.NumRequeues(key) < maxRetries {\n\t\t\t\t\tglog.V(4).Infof(\"Error syncing %s %v: %v\", resourceType, key, err)\n\t\t\t\t\tqueue.AddRateLimited(key)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\tglog.V(4).Infof(\"Dropping %s %q out of the queue: %v\", resourceType, key, err)\n\t\t\t\tqueue.Forget(key)\n\t\t\t\treturn false\n\t\t\t}()\n\t\t}\n\t}\n}", "func (c *Consumer) consume(ctx context.Context) {\n\t// We need to run startConsuming to make sure that we are okay and ready to start consuming. This is mainly to\n\t// avoid a race condition where Listen() will attempt to read the messages channel prior to consume()\n\t// initializing it. We can then launch a goroutine to handle the actual consume operation.\n\tif !c.startConsuming() {\n\t\treturn\n\t}\n\tgo func() {\n\t\tdefer c.stopConsuming()\n\n\t\tchildCtx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\t// The consume loop can be cancelled by a calling the cancellation function on the context or by\n\t\t\t// closing the pipe of death. Note that in the case of context cancellation, the getRecords\n\t\t\t// call below will be allowed to complete (as getRecords does not regard context cancellation).\n\t\t\t// In the case of cancellation by pipe of death, however, the getRecords will immediately abort\n\t\t\t// and allow the consume function to immediately abort as well.\n\t\t\tif ok, _ := c.shouldConsume(ctx); !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.enqueueBatch(childCtx)\n\t\t}\n\t}()\n}", "func (c *QueueClient) Use(hooks ...Hook) {\n\tc.hooks.Queue = append(c.hooks.Queue, hooks...)\n}", "func (lp *loop) HandleCb(cb handleCb) {\n\tlp.handleCb = cb\n}", "func (a *answer) queueCall(result *answer, transform []capnp.PipelineOp, call *capnp.Call) error {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\tif a.done {\n\t\tpanic(\"answer.queueCall called on resolved answer\")\n\t}\n\tif len(a.queue) == cap(a.queue) {\n\t\treturn errQueueFull\n\t}\n\tcc, err := call.Copy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.queue = append(a.queue, pcall{\n\t\ttransform: transform,\n\t\tqcall: qcall{\n\t\t\ta: result,\n\t\t\tcall: cc,\n\t\t},\n\t})\n\treturn nil\n}", "func NewRedisQueueWithFunc(\n\tr *redis.Client,\n\tpush func(interface{}) (interface{}, error),\n\tpop func(interface{}) (interface{}, error)) *RedisQueue {\n\treturn &RedisQueue{\n\t\tkey: fmt.Sprintf(\"queue:%v\", time.Now().Nanosecond()),\n\t\tr: r,\n\t\tpush: push,\n\t\tpop: pop,\n\t}\n}", "func (client *Client) RecognizeFlowerWithChan(request *RecognizeFlowerRequest) (<-chan *RecognizeFlowerResponse, <-chan error) {\n\tresponseChan := make(chan *RecognizeFlowerResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.RecognizeFlower(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (f *Fixer) QueueChain(cert *x509.Certificate, chain []*x509.Certificate, roots *x509.CertPool) {\n\tf.toFix <- &toFix{\n\t\tcert: cert,\n\t\tchain: newDedupedChain(chain),\n\t\troots: roots,\n\t\tcache: f.cache,\n\t}\n}", "func WithTracer(tracer trace.Tracer) OptionFunc {\n\treturn func(c *callbacks) {\n\t\tc.tracer = tracer\n\t}\n}", "func CallErr(f func() error) error {\n\tcheckRun()\n\terrChan := make(chan error)\n\tcallQueue <- func() {\n\t\terrChan <- f()\n\t}\n\treturn <-errChan\n}", "func (client *Client) KillSparkJobWithCallback(request *KillSparkJobRequest, callback func(response *KillSparkJobResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *KillSparkJobResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.KillSparkJob(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func queueRedo(queue, cgroup string) (exWrap, error) {\n\tk, err := queueKeyMarshal(core.Key{Base: queue, Subs: []string{cgroup, \"redo\"}})\n\tif err != nil {\n\t\treturn exWrap{}, err\n\t}\n\treturn newExWrap(k), nil\n}", "func (q *GCPPubSubQueue) receive(ctx context.Context, f func(interface{})) {\n\terr := q.subscription.Receive(ctx, func(ctx xContext.Context, msg *pubsub.Message) {\n\t\tlogger := q.logger.With(\"messageID\", msg.ID)\n\n\t\tlogger.With(\"publishTime\", msg.PublishTime).Info(\"processing job published\")\n\n\t\t// Acknowledge the job now, anything else that could fail by this instance\n\t\t// will probably fail for others.\n\t\tmsg.Ack()\n\t\tlogger.Info(\"acknowledged job\")\n\n\t\treader := bytes.NewReader(msg.Data)\n\t\tdec := gob.NewDecoder(reader)\n\n\t\tvar job container\n\t\tif err := dec.Decode(&job); err != nil {\n\t\t\tlogger.With(\"error\", err).Errorf(\"could not decode job\")\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"processing\")\n\n\t\tf(job.Job)\n\t})\n\tif err != nil && err != context.Canceled {\n\t\tq.logger.With(\"error\", err).Error(\"could not receive on subscription\")\n\t}\n}", "func (client *Client) DescribeAcceleratorWithCallback(request *DescribeAcceleratorRequest, callback func(response *DescribeAcceleratorResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DescribeAcceleratorResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DescribeAccelerator(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func NewChannelQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {\n\tconfigInterface, err := toConfig(ChannelQueueConfiguration{}, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := configInterface.(ChannelQueueConfiguration)\n\tif config.BatchLength == 0 {\n\t\tconfig.BatchLength = 1\n\t}\n\n\tterminateCtx, terminateCtxCancel := context.WithCancel(context.Background())\n\tshutdownCtx, shutdownCtxCancel := context.WithCancel(terminateCtx)\n\n\tqueue := &ChannelQueue{\n\t\tshutdownCtx: shutdownCtx,\n\t\tshutdownCtxCancel: shutdownCtxCancel,\n\t\tterminateCtx: terminateCtx,\n\t\tterminateCtxCancel: terminateCtxCancel,\n\t\texemplar: exemplar,\n\t\tworkers: config.Workers,\n\t\tname: config.Name,\n\t}\n\tqueue.WorkerPool = NewWorkerPool(func(data ...Data) []Data {\n\t\tunhandled := handle(data...)\n\t\tif len(unhandled) > 0 {\n\t\t\t// We can only pushback to the channel if we're paused.\n\t\t\tif queue.IsPaused() {\n\t\t\t\tatomic.AddInt64(&queue.numInQueue, int64(len(unhandled)))\n\t\t\t\tgo func() {\n\t\t\t\t\tfor _, datum := range data {\n\t\t\t\t\t\tqueue.dataChan <- datum\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn unhandled\n\t}, config.WorkerPoolConfiguration)\n\n\tqueue.qid = GetManager().Add(queue, ChannelQueueType, config, exemplar)\n\treturn queue, nil\n}", "func (client *Client) GetTaobaoOrderWithCallback(request *GetTaobaoOrderRequest, callback func(response *GetTaobaoOrderResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetTaobaoOrderResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetTaobaoOrder(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func WithGomockController(t *testing.T, f func(ctrl *gomock.Controller)) {\n\tctrl := gomock.NewController(t)\n\n\tf(ctrl)\n}", "func (runner *TestRunner) handleQueue (queueControl <-chan batchExecQueueControl) {\n\texecEndSignal := make(chan string)\n\n\texecute := func (enq batchExecQueueControlEnqueue, stopRequest <-chan struct{}, executionLogQuery <-chan chan<- string) {\n\t\t// Handle the execution log in a separate goroutine rather than in\n\t\t// the main loop of runner.executeBatch, so that any stalls in\n\t\t// executeBatch don't delay execution log queries.\n\t\t// The handler is controlled via the following channels.\n\t\texecutionLogAppend\t:= make(chan string)\t// Append a string to the log; don't commit to DB yet.\n\t\texecutionLogCommit\t:= make(chan struct{})\t// Commit uncommitted changes to DB.\n\t\texecutionLogStop\t:= make(chan struct{})\t// Stop the goroutine.\n\t\tgo func() {\n\t\t\texecutionLog := bytes.Buffer{}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\t\tcase dst := <-executionLogQuery:\n\t\t\t\t\t\tdst <- runner.getBatchResultPastExecutionLog(enq.batchResultId) + executionLog.String()\n\t\t\t\t\tcase str := <-executionLogAppend:\n\t\t\t\t\t\texecutionLog.WriteString(str)\n\t\t\t\t\tcase <-executionLogCommit:\n\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\topSet.Call(typeBatchResultExecutionLog, enq.batchResultId, \"Append\", executionLog.String())\n\t\t\t\t\t\terr := runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\texecutionLog.Reset()\n\t\t\t\t\tcase <-executionLogStop:\n\t\t\t\t\t\tif executionLog.Len() > 0 { panic(\"Execution log handler stopped, but non-committed data remains\") }\n\t\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\texecutionLogAppend <- fmt.Sprintf(\"Batch reached front of its queue at %v\\n\", time.Now().Format(defaultHumanReadableTimeFormat))\n\n\t\tvar batchResult BatchResult\n\t\terr := runner.rtdbServer.GetObject(enq.batchResultId, &batchResult)\n\t\tif err != nil { panic(err) }\n\n\t\tvar testCaseList TestCaseList\n\t\terr = runner.rtdbServer.GetObject(enq.batchResultId, &testCaseList)\n\t\tif err != nil { panic(err) }\n\n\t\tcasePaths := testCaseList.Paths\n\t\tif runner.isPartiallyExecutedBatch(enq.batchResultId) {\n\t\t\texecutionLogAppend <- fmt.Sprintf(\"Batch is partially executed, filtering pending cases\\n\")\n\t\t\tcasePaths = runner.filterPendingCasePaths(enq.batchResultId, casePaths)\n\t\t}\n\n\t\trunner.executeBatch(enq.batchResultId, batchResult.ExecParams, casePaths, stopRequest, executionLogAppend)\n\n\t\texecutionLogCommit <- struct{}{}\n\t\texecEndSignal <- enq.queueId\n\t\texecutionLogStop <- struct{}{}\n\t}\n\n\tqueueStopRequest\t\t:= make(map[string]chan<- struct{})\n\tqueueExecutionLogQuery\t:= make(map[string]chan<- chan<- string)\n\n\tlaunch := func (enq batchExecQueueControlEnqueue) {\n\t\tstopRequest\t\t\t:= make(chan struct{}, 1)\n\t\texecutionLogQuery\t:= make(chan chan<- string, 1)\n\t\tqueueStopRequest[enq.queueId]\t\t\t= stopRequest\n\t\tqueueExecutionLogQuery[enq.queueId]\t\t= executionLogQuery\n\t\tgo execute(enq, stopRequest, executionLogQuery)\n\t}\n\n\tfor {\n\t\tselect {\n\t\t\tcase command := <-queueControl:\n\t\t\t\tswitch cmd := command.(type) {\n\t\t\t\t\tcase batchExecQueueControlEnqueue:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t// Queue does not exist; create it.\n\n\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueueList, \"deviceBatchQueueList\", \"Append\", cmd.queueId)\n\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Init\")\n\t\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\t\t\t\tlog.Printf(\"[runner] created queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Append\", cmd.batchResultId)\n\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\t\t\tif len(queue.BatchResultIds) == 0 { // \\note queue is the queue before appending.\n\t\t\t\t\t\t\tlaunch(cmd);\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlStopBatch:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: stop request for non-existent queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfound := false\n\t\t\t\t\t\tfor ndx, enqueuedId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueuedId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tif ndx == 0 {\n\t\t\t\t\t\t\t\t\tselect {\n\t\t\t\t\t\t\t\t\t\tcase queueStopRequest[cmd.queueId] <- struct{}{}:\n\t\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] stop request sent for batch '%s'\\n\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] stop request already sent for batch '%s'\\n\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] cancelled pending batch '%s'\\n\", cmd.batchResultId)\n\n\t\t\t\t\t\t\t\t\t// Set batch status, and remove it from the queue and active batch list.\n\t\t\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\t\t\topSet.Call(typeBatchResult, cmd.batchResultId, \"SetStatus\", BATCH_STATUS_CODE_CANCELED)\n\t\t\t\t\t\t\t\t\topSet.Call(typeActiveBatchResultList, \"activeBatchResultList\", \"Remove\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Remove\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !found {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: stop request for batch '%s', does not exist in queue '%s'\\n\", cmd.batchResultId, cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlMove:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: move command for non-existent queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfound := false\n\t\t\t\t\t\tfor srcNdx, enqueuedId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueuedId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tdstNdx := srcNdx + cmd.offset\n\t\t\t\t\t\t\t\tif srcNdx == 0 || dstNdx == 0 {\n\t\t\t\t\t\t\t\t\t// \\todo [nuutti] Support moving running batch? We'd have to automatically\n\t\t\t\t\t\t\t\t\t//\t\t\t\t stop it first, which can be slow, so it could get confusing?\n\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: trying to move currently to/from running batch in queue\\n\")\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif dstNdx < 0 || dstNdx >= len(queue.BatchResultIds) {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: trying to move batch to position %d\\n\", dstNdx)\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Move\", srcNdx, dstNdx)\n\t\t\t\t\t\t\t\t\t\terr := runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !found {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: move command for batch '%s', does not exist in queue '%s'\\n\", cmd.batchResultId, cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlExecutionLogQuery:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil { cmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId); continue }\n\n\t\t\t\t\t\tquerySent := false\n\t\t\t\t\t\tfor ndx, enqueueId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueueId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tif ndx == 0 {\n\t\t\t\t\t\t\t\t\tqueueExecutionLogQuery[cmd.queueId] <- cmd.dst\n\t\t\t\t\t\t\t\t\tquerySent = true\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !querySent {\n\t\t\t\t\t\t\tcmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId)\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase queueId := <-execEndSignal:\n\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\terr := runner.rtdbServer.GetObject(queueId, &queue)\n\t\t\t\tif err != nil { panic(err) } // \\note This shouldn't happen (a batch run ends while it's not even in the queue).\n\n\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\topSet.Call(typeDeviceBatchQueue, queueId, \"Remove\", queue.BatchResultIds[0])\n\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\tif len(queue.BatchResultIds) > 1 { // \\note queue is the queue before removal.\n\t\t\t\t\tlaunch(batchExecQueueControlEnqueue{\n\t\t\t\t\t\tbatchResultId:\tqueue.BatchResultIds[1],\n\t\t\t\t\t\tqueueId:\t\tqueueId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t}\n\t}\n}", "func (c *Connection) ConsumerWithConfig(done chan bool, config *Config, callback func(msgs <-chan amqp.Delivery)) error {\n\tmsgs, err := c.Channel.Consume(\n\t\tconfig.Queue,\n\t\tconfig.ConsumerTag,\n\t\tconfig.Options.Consume.AutoAck,\n\t\tconfig.Options.Consume.Exclusive,\n\t\tconfig.Options.Consume.NoLocal,\n\t\tconfig.Options.Consume.NoWait,\n\t\tconfig.Options.Consume.Args,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo callback(msgs)\n\n\tlog.Println(\"Waiting for messages...\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tc.Channel.Close()\n\t\t\tc.Conn.Close()\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *Controller) enqueueTagger(obj interface{}) {\n\tvar key string\n\tvar err error\n\tif key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {\n\t\truntime.HandleError(err)\n\t\treturn\n\t}\n\tglog.Infof(\"Enqueueing tagger %s\", key)\n\tc.workqueue.AddRateLimited(key)\n}", "func (client *Client) RunMedQAWithCallback(request *RunMedQARequest, callback func(response *RunMedQAResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RunMedQAResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RunMedQA(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (q *ChannelQueue) Run(atShutdown, atTerminate func(func())) {\n\tpprof.SetGoroutineLabels(q.baseCtx)\n\tatShutdown(q.Shutdown)\n\tatTerminate(q.Terminate)\n\tlog.Debug(\"ChannelQueue: %s Starting\", q.name)\n\t_ = q.AddWorkers(q.workers, 0)\n}", "func New(c *Config) (Poller, error) {\n\tcfg := c.withDefaults()\n\n\tkq, err := KqueueCreate(&KqueueConfig{\n\t\tOnWaitError: cfg.OnWaitError,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn poller{kq}, nil\n}", "func (q *execQueue) queue(f func()) bool {\n\tq.mu.Lock()\n\tok := !q.isClosed() && len(q.funcs) < cap(q.funcs)\n\tif ok {\n\t\tq.funcs = append(q.funcs, f)\n\t\tq.cond.Signal()\n\t}\n\tq.mu.Unlock()\n\treturn ok\n}", "func TestConsumerControlLoop(t *testing.T) {\n\texpect := ttesting.NewExpect(t)\n\tmockC := getMockConsumer()\n\n\tstop := new(int32)\n\troll := new(int32)\n\tmockC.SetStopCallback(func() {\n\t\tatomic.StoreInt32(stop, 1)\n\t})\n\n\tmockC.SetRollCallback(func() {\n\t\tatomic.StoreInt32(roll, 1)\n\t})\n\n\tgo mockC.ControlLoop()\n\t// let the go routine start\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlStopConsumer\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(stop), int32(1))\n\n\tgo mockC.ControlLoop()\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlRoll\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(roll), int32(1))\n}", "func (cb *ZVControllerBuilder) withWorkqueueRateLimiting() *ZVControllerBuilder {\n\tcb.ZVController.workqueue = workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"ZV\")\n\treturn cb\n}", "func (client *Client) RunContactReviewWithCallback(request *RunContactReviewRequest, callback func(response *RunContactReviewResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RunContactReviewResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RunContactReview(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (lp *loop) RedrawCb(cb redrawCb) {\n\tlp.redrawCb = cb\n}", "func (q *Queue) RunWithTimer(c *config.Config) error {\n\tstart := time.Now()\n\tif err := q.run(c); err != nil {\n\t\treturn fmt.Errorf(\"run queue failed: %s\", err)\n\t}\n\tlog.Printf(\"%sFinished in %.3f seconds%s\", colors.Green,\n\t\ttime.Since(start).Seconds(), colors.Reset)\n\treturn nil\n}", "func (client *Client) QueryWorksWithCallback(request *QueryWorksRequest, callback func(response *QueryWorksResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryWorksResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryWorks(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func TestConsumerControlLoop(t *testing.T) {\n\texpect := shared.NewExpect(t)\n\tmockC := getMockConsumer()\n\n\tstop := new(int32)\n\troll := new(int32)\n\tmockC.SetStopCallback(func() {\n\t\tatomic.StoreInt32(stop, 1)\n\t})\n\n\tmockC.SetRollCallback(func() {\n\t\tatomic.StoreInt32(roll, 1)\n\t})\n\n\tgo mockC.ControlLoop()\n\t// let the go routine start\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlStopConsumer\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(stop), int32(1))\n\n\tgo mockC.ControlLoop()\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlRoll\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(roll), int32(1))\n}", "func HandleQuee(c chan<- string) {\n\tc <- \"one\" //queue(\"one\")\n\tc <- \"two\" //queue(\"one\",\"two\")\n\tfmt.Println(\"isEnough\")\n\tclose(c)\n}", "func RunConsumer(ctx context.Context, qUser, qPassword, qUri, qName string, prefetchCount, prefetchSize,\n\tmaxRetries, workers int, handler MessageHandler) {\n\tconn := NewConnection(ctx, qUser, qPassword, qUri)\n\tfor id := 0; id < workers; id++ {\n\t\tc := newRetryableConsumer(id, qName, prefetchCount, prefetchSize, handler, maxRetries)\n\t\tc.run(conn)\n\t}\n\tconn.start()\n}", "func (q *queueDriverDefault) Run(ctx context.Context) error {\n\tvar (\n\t\tmsg etl.Message\n\t\tsize int\n\t\terr error\n\t\tok bool\n\t)\n\tfor {\n\t\tfor true {\n\t\t\t// dequeue message\n\t\t\tmsg, size, ok = q.dequeue()\n\t\t\t// if no message was dequeued, break and wait for new message in a queue\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// send dequeued message to output channel\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tcase q.outputCh <- msg:\n\t\t\t}\n\n\t\t\t// call dequeue hooks\n\t\t\terr = q.callDequeueHooks(ctx, size)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// wait until new item is enqueued\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-q.enqueuedCh:\n\t\t}\n\t}\n\n\treturn nil\n}", "func WithBlockingCallback() Option {\n\treturn func(i interface{}) error {\n\t\tif c, ok := i.(*ceClient); ok {\n\t\t\tc.blockingCallback = true\n\t\t}\n\t\treturn nil\n\t}\n}", "func TestChainWithClosure(t *testing.T) {\n\twriter := os.Stdout\n\tvar chainC ChainCClosure\n\tchainC = ChainCClosure{\n\t\tWriter: writer,\n\t\tClosure: func(msg *string) {\n\t\t\tfmt.Println(\"chain c\")\n\t\t\tchainC.Msg = msg // side effect on outside of block\n\t\t},\n\t}\n\tchainB := ChainBClosure{\n\t\tNextChain: &chainC,\n\t\tClosure: func(msg *string) {\n\t\t\tfmt.Println(\"chain B\")\n\t\t},\n\t}\n\n\tchainA := ChainAClosure{\n\t\tNextChain: &chainB,\n\t\tClosure: func(msg *string) {\n\t\t\tfmt.Println(\"chain A\")\n\t\t},\n\t}\n\n\tmsg := \"hello\"\n\tchainA.Next(&msg)\n\n\tif *chainC.Msg != \"hello\" {\n\t\tt.Errorf(\"chainC msg should be 'hello' but got: %s\\n\", *chainC.Msg)\n\t}\n}", "func (client *Client) SetCasterConfigWithCallback(request *SetCasterConfigRequest, callback func(response *SetCasterConfigResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *SetCasterConfigResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.SetCasterConfig(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func demo_queue() {\n fmt.Print(\"\\n---QUEUE Logic---\\n\\n\")\n q := queue.Queue{}\n\n for i := 0; i <= 5; i++ {\n q.Enqueue(i)\n }\n fmt.Print(\"---Queue Before Dequeue---\\n\")\n q.PrintAll()\n dequeued := q.Dequeue()\n fmt.Printf(\"Dequeued Value: %v\\n\", dequeued)\n fmt.Print(\"---Queue After Dequeue---\\n\")\n q.PrintAll()\n}", "func (client *Client) VerifyCenWithCallback(request *VerifyCenRequest, callback func(response *VerifyCenResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *VerifyCenResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.VerifyCen(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func causalityWrap(inCh chan *job, syncer *Syncer) chan *job {\n\tcausality := &causality{\n\t\trelations: make(map[string]string),\n\t\ttask: syncer.cfg.Name,\n\t\tsource: syncer.cfg.SourceID,\n\t\tlogger: syncer.tctx.Logger.WithFields(zap.String(\"component\", \"causality\")),\n\t\tinCh: inCh,\n\t\toutCh: make(chan *job, syncer.cfg.QueueSize),\n\t}\n\n\tgo func() {\n\t\tcausality.run()\n\t\tcausality.close()\n\t}()\n\n\treturn causality.outCh\n}", "func (client *Client) ModifyPlanWithCallback(request *ModifyPlanRequest, callback func(response *ModifyPlanResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ModifyPlanResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ModifyPlan(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (f *ccFixture) popQueue() {\n\tf.T().Helper()\n\n\tdone := make(chan error)\n\tgo func() {\n\t\titem, _ := f.q.Get()\n\t\t_, err := f.tfr.Reconcile(f.ctx, item.(reconcile.Request))\n\t\tf.q.Done(item)\n\t\tdone <- err\n\t}()\n\n\tselect {\n\tcase <-time.After(time.Second):\n\t\tf.T().Fatal(\"timeout waiting for workqueue\")\n\tcase err := <-done:\n\t\tassert.NoError(f.T(), err)\n\t}\n}", "func (r *Request) getCallback() mq.Response {\n\tif r.cb == nil {\n\t\tpanic(\"test: request already responded to\")\n\t}\n\n\tcb := r.cb\n\tr.cb = nil\n\treturn cb\n}", "func (gq *Dispatch) Enqueue(t queues.Task) int64 {\n // Wrap the function so it works with the goroutine limiting code.\n var f = t.Func()\n var dtFunc = func(id int64) {\n // Run the given function.\n f(id)\n\n // Decrement the process counter.\n gq.pLock.Lock()\n //log.Printf(\"processing: %d, waiting: %v\", gq.processing, gq.waitingToRun)\n gq.processing--\n if gq.waitingToRun {\n gq.waitingToRun = false\n gq.nextWait.Done()\n }\n gq.pLock.Unlock()\n }\n t.SetFunc(dtFunc)\n\n // Lock the queue and enqueue a new task.\n gq.qLock.Lock()\n gq.idcount++\n var id = gq.idcount\n gq.queue.Enqueue(dispatchTaskWrapper{id, t})\n if gq.waitingOnQ {\n gq.waitingOnQ = false\n gq.restart.Done()\n }\n if gq.queue.Len() > gq.maxlength {\n gq.maxlength = gq.queue.Len()\n }\n gq.qLock.Unlock()\n\n return id\n}", "func (client *Client) StartK8sApplicationWithCallback(request *StartK8sApplicationRequest, callback func(response *StartK8sApplicationResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *StartK8sApplicationResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.StartK8sApplication(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (e Enumerable) Queue(f func(item interface{})) (q Queue) {\n\tq.AddJob = func(jobs *chan interface{}) {\n\t\tfor _, item := range e {\n\t\t\t*jobs <- item\n\t\t}\n\t}\n\tq.DoJob = func(job *interface{}) {\n\t\tf(*job)\n\t\treturn\n\t}\n\treturn\n}", "func (client *Client) AssociateRouteTableWithGatewayWithCallback(request *AssociateRouteTableWithGatewayRequest, callback func(response *AssociateRouteTableWithGatewayResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *AssociateRouteTableWithGatewayResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.AssociateRouteTableWithGateway(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (object *MQObject) CB(goOperation int32, gocbd *MQCBD, gomd *MQMD, gogmo *MQGMO) error {\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\tvar mqOperation C.MQLONG\n\tvar mqcbd C.MQCBD\n\tvar mqmd C.MQMD\n\tvar mqgmo C.MQGMO\n\n\terr := checkMD(gomd, \"MQCB\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = checkGMO(gogmo, \"MQCB\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmqOperation = C.MQLONG(goOperation)\n\tcopyCBDtoC(&mqcbd, gocbd)\n\tcopyMDtoC(&mqmd, gomd)\n\tcopyGMOtoC(&mqgmo, gogmo)\n\n\tkey := makeKey(object.qMgr.hConn, object.hObj)\n\n\t// The callback function is a C function that is a proxy for the MQCALLBACK_Go function\n\t// defined here. And that in turn will call the user's callback function\n\tmqcbd.CallbackFunction = (C.MQPTR)(unsafe.Pointer(C.MQCALLBACK_C))\n\n\tC.MQCB(object.qMgr.hConn, mqOperation, (C.PMQVOID)(unsafe.Pointer(&mqcbd)),\n\t\tobject.hObj,\n\t\t(C.PMQVOID)(unsafe.Pointer(&mqmd)), (C.PMQVOID)(unsafe.Pointer(&mqgmo)),\n\t\t&mqcc, &mqrc)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQCB\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn &mqreturn\n\t}\n\n\t// Add or remove the control information in the map used by the callback routines\n\tswitch mqOperation {\n\tcase C.MQOP_DEREGISTER:\n\t\tmapLock()\n\t\tdelete(cbMap, key)\n\t\tmapUnlock()\n\tcase C.MQOP_REGISTER:\n\t\t// Stash the hObj and real function to be called\n\t\tinfo := &cbInfo{hObj: object,\n\t\t\tcallbackFunction: gocbd.CallbackFunction,\n\t\t\tconnectionArea: nil,\n\t\t\tcallbackArea: gocbd.CallbackArea}\n\t\tmapLock()\n\t\tcbMap[key] = info\n\t\tmapUnlock()\n\tdefault: // Other values leave the map alone\n\t}\n\n\treturn nil\n}", "func (f *FakeWatchEventQ) Dequeue(ctx context.Context,\n\tfromver uint64, ignoreBulk bool, cb apiintf.EventHandlerFn, cleanupfn func(), opts *api.ListWatchOptions) {\n\tdefer f.Unlock()\n\tf.Lock()\n\tclose(f.DqCh)\n\tf.Dequeues++\n\tif f.DQFn != nil {\n\t\tf.DQFn(ctx, fromver, cb, cleanupfn)\n\t}\n}", "func (client *Client) QueryBlockWithCallback(request *QueryBlockRequest, callback func(response *QueryBlockResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryBlockResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryBlock(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) MetastoreCreateKafkaTopicWithCallback(request *MetastoreCreateKafkaTopicRequest, callback func(response *MetastoreCreateKafkaTopicResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *MetastoreCreateKafkaTopicResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.MetastoreCreateKafkaTopic(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (c *ConsumerManager) Handle(topic, channel string, handler HandlerFunc) {\n\tfor i := range c.middlewares {\n\t\thandler = c.middlewares[len(c.middlewares)-i-1](handler)\n\t}\n\n\tc.mu.RLock()\n\tgHandler, ok := c.handlers[mergeTopicAndChannel(topic, channel)]\n\tc.mu.RUnlock()\n\n\tif !ok {\n\t\tc.err = fmt.Errorf(\"gonsq: consumer with topic %s and channel %s does not exist\", topic, channel)\n\t\treturn\n\t}\n\n\tif gHandler.handler != nil {\n\t\tc.err = fmt.Errorf(\"gonsq: handler for topic %s and channel %s registered twice\", topic, channel)\n\t\treturn\n\t}\n\n\t// Set the gonsq handler.\n\tgHandler.handler = handler\n\t// Set the nsq handler for HandleMessage.\n\t// Use AddHandler instead of AddConcurrentHandler,\n\t// consuming message from nsqd is very fast and\n\t// most of the timewe don't need to use concurrent handler.\n\tgHandler.client.AddHandler(gHandler)\n\t// Change the MaxInFlight to buffLength as the number\n\t// of message won't exceed the buffLength.\n\tgHandler.client.ChangeMaxInFlight(gHandler.stats.BufferLength())\n\n\tc.mu.Lock()\n\tc.handlers[mergeTopicAndChannel(topic, channel)] = gHandler\n\tc.mu.Unlock()\n}", "func WithCounter(counter Counter) Option {\n\treturn func(c *Consumer) error {\n\t\tc.counter = counter\n\t\treturn nil\n\t}\n}", "func WithThrottler(ctx context.Context, thr Throttler, freq time.Duration) context.Context {\n\treturn ctxthr{Context: ctx, thr: thr, freq: freq}\n}", "func runConsumer() {\n\tlog.Info(\"consumer starting ...\")\n\tdone := make(chan bool, 1)\n\tfor _, consumer := range cc.consumers {\n\t\tgo func(c *ConsumerWrapper) {\n\t\t\tlog.Info(\"consumer runing\", c.name)\n\t\t\tfor {\n\t\t\t\tif c.pause {\n\t\t\t\t\tlog.Info(\"consumer pause\", c.name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.consumer.Pop(c.queue, c.name)\n\t\t\t}\n\t\t}(consumer)\n\t}\n\t<-done\n}", "func (client *Client) QueryContactInfoWithCallback(request *QueryContactInfoRequest, callback func(response *QueryContactInfoResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryContactInfoResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryContactInfo(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (cb *ControllerBuilder) WithWorkqueueRateLimiting() *ControllerBuilder {\n\tcb.Controller.workqueue = workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"CSPC\")\n\treturn cb\n}", "func TestConsumerTickerLoop(t *testing.T) {\n\texpect := shared.NewExpect(t)\n\tmockC := getMockConsumer()\n\tmockC.setState(PluginStateActive)\n\t// accept timeroff by abs( 8 ms)\n\tdelta := float64(8 * time.Millisecond)\n\tcounter := new(int32)\n\ttickerLoopTimeout := 20 * time.Millisecond\n\tvar timeRecorded time.Time\n\tonTimeOut := func() {\n\t\tif atomic.LoadInt32(counter) > 3 {\n\t\t\tmockC.setState(PluginStateDead)\n\t\t\treturn\n\t\t}\n\t\t//this was fired as soon as the ticker started. So ignore but save the time\n\t\tif atomic.LoadInt32(counter) == 0 {\n\t\t\ttimeRecorded = time.Now()\n\t\t\tatomic.AddInt32(counter, 1)\n\t\t\treturn\n\t\t}\n\t\tdiff := time.Now().Sub(timeRecorded)\n\t\tdeltaDiff := math.Abs(float64(tickerLoopTimeout - diff))\n\t\texpect.True(deltaDiff < delta)\n\t\ttimeRecorded = time.Now()\n\t\tatomic.AddInt32(counter, 1)\n\t\treturn\n\t}\n\n\tmockC.tickerLoop(tickerLoopTimeout, onTimeOut)\n\ttime.Sleep(2 * time.Second)\n\t// in anycase, the callback has to be called atleast once\n\texpect.Greater(atomic.LoadInt32(counter), int32(1))\n}", "func (f *FPC) enqueue() {\n\tf.queueMu.Lock()\n\tdefer f.queueMu.Unlock()\n\tf.ctxsMu.Lock()\n\tdefer f.ctxsMu.Unlock()\n\tfor ele := f.queue.Front(); ele != nil; ele = f.queue.Front() {\n\t\tvoteCtx := ele.Value.(*vote.Context)\n\t\tf.ctxs[voteCtx.ID] = voteCtx\n\t\tf.queue.Remove(ele)\n\t\tdelete(f.queueSet, voteCtx.ID)\n\t}\n}", "func main() {\n\tctx := cliContext()\n\tflag.Parse()\n\tpool := &red.Pool{\n\t\tDial: func() (red.Conn, error) {\n\t\t\treturn red.Dial(\"tcp\", *redisServer)\n\t\t},\n\t\tTestOnBorrow: func(c red.Conn, _ time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t\tMaxIdle: 1,\n\t}\n\t// Create the driver for queue\n\tdriver, err := redis.NewDriver(\n\t\tctx,\n\t\tredis.WithQueuePrefix(*prefix),\n\t\tredis.WithRedisPool(pool),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Create the manager\n\tm := workers.NewManager(driver, driver)\n\t// Register a global middleware\n\tm.RegisterMiddleware(\n\t\tmiddleware(\"Global\"),\n\t\tstorage.NewStorageMiddleware(&redisStorage{red: pool}),\n\t)\n\t// Register workers\n\terr = m.RegisterWorker(\"dummy\", dummyWorker{}, workers.WithMiddleware(middleware(\"DummyMiddle\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Process queues\n\t// this hangs until the context is done\n\tm.Process(ctx, workers.WithParallelLimit(10), workers.WithRetryCount(1))\n}", "func Call(f func()) {\n\tdone := dPool.Get().(chan struct{})\n\tdefer dPool.Put(done)\n\tfq <- fun{fn: f, done: done}\n\t<-done\n}", "func (client *Client) PutMetricAlarmWithCallback(request *PutMetricAlarmRequest, callback func(response *PutMetricAlarmResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *PutMetricAlarmResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.PutMetricAlarm(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func WithQueueSubscriber(queue string) ConsumerOption {\n\treturn func(c *Consumer) error {\n\t\tif queue == \"\" {\n\t\t\treturn ErrInvalidQueueName\n\t\t}\n\t\tc.Subscriber = &QueueSubscriber{Queue: queue}\n\t\treturn nil\n\t}\n}", "func (client *Client) GetContactWithCallback(request *GetContactRequest, callback func(response *GetContactResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetContactResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetContact(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (p *unlimitedPool) Queue(fn WorkFunc) WorkUnit {\n\n\tw := &workUnit{\n\t\tdone: make(chan struct{}),\n\t\tfn: fn,\n\t}\n\n\tp.m.Lock()\n\n\tif p.closed {\n\t\tw.err = &ErrPoolClosed{s: errClosed}\n\t\t// if w.cancelled.Load() == nil {\n\t\tclose(w.done)\n\t\t// }\n\t\tp.m.Unlock()\n\t\treturn w\n\t}\n\n\tp.units = append(p.units, w)\n\tgo func(w *workUnit) {\n\n\t\tdefer func(w *workUnit) {\n\t\t\tif err := recover(); err != nil {\n\n\t\t\t\ttrace := make([]byte, 1<<16)\n\t\t\t\tn := runtime.Stack(trace, true)\n\n\t\t\t\ts := fmt.Sprintf(errRecovery, err, string(trace[:int(math.Min(float64(n), float64(7000)))]))\n\n\t\t\t\tw.cancelled.Store(struct{}{})\n\t\t\t\tw.err = &ErrRecovery{s: s}\n\t\t\t\tclose(w.done)\n\t\t\t}\n\t\t}(w)\n\n\t\t// support for individual WorkUnit cancellation\n\t\t// and batch job cancellation\n\t\tif w.cancelled.Load() == nil {\n\t\t\tval, err := w.fn(w)\n\n\t\t\tw.writing.Store(struct{}{})\n\n\t\t\t// need to check again in case the WorkFunc cancelled this unit of work\n\t\t\t// otherwise we'll have a race condition\n\t\t\tif w.cancelled.Load() == nil && w.cancelling.Load() == nil {\n\n\t\t\t\tw.value, w.err = val, err\n\n\t\t\t\t// who knows where the Done channel is being listened to on the other end\n\t\t\t\t// don't want this to block just because caller is waiting on another unit\n\t\t\t\t// of work to be done first so we use close\n\t\t\t\tclose(w.done)\n\t\t\t}\n\t\t}\n\t}(w)\n\n\tp.m.Unlock()\n\n\treturn w\n}", "func (o *GetLolCareerStatsV1ChampionAveragesByChampionIDByPositionByTierByQueueParams) WithQueue(queue string) *GetLolCareerStatsV1ChampionAveragesByChampionIDByPositionByTierByQueueParams {\n\to.SetQueue(queue)\n\treturn o\n}", "func (h *HTTPClient) Enqueue(ctx context.Context, token, projID, qName string, msgs []NewMessage) (*Enqueued, error) {\n\treqBody := &bytes.Buffer{}\n\tif err := json.NewEncoder(reqBody).Encode(enqueueReq{Messages: msgs}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := h.newReq(\"POST\", token, projID, fmt.Sprintf(\"queues/%s/messages\", qName), reqBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := new(Enqueued)\n\tdoFunc := func(resp *http.Response, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tif err := json.NewDecoder(resp.Body).Decode(ret); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif err := gorion.HTTPDo(ctx, h.client, h.transport, req, doFunc); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}", "func (cl *DelayCaller) runner() {\n\tfor {\n\t\t// Run all the functions in the queue, whose timeout has expired. After\n\t\t// the loop, the variable |delay| contains the time until the next timeout.\n\t\tdelay := time.Duration(0)\n\t\tfor cl.queue.Len() > 0 {\n\t\t\tc := cl.queue.topCall()\n\t\t\tnow := time.Now()\n\t\t\tif now.Before(c.Tm) {\n\t\t\t\tdelay = c.Tm.Sub(now)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcl.queue.popCall()\n\t\t\tcl.p.send(c.Fn)\n\t\t}\n\t\t// Wait for a new timeout request, but block at most until the next\n\t\t// already scheduled timeout.\n\t\tvar timeout <-chan time.Time\n\t\tif delay == 0 {\n\t\t\ttimeout = nil\n\t\t} else {\n\t\t\ttimeout = time.After(delay)\n\t\t}\n\t\tselect {\n\t\tcase c, ok := <-cl.queueIn:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tcl.queue.pushCall(c)\n\t\t\t}\n\t\tcase <-timeout:\n\t\t}\n\t}\n}", "func runCallback(receivedMessage *Message, consumerMessage *sarama.ConsumerMessage) {\n\tcallback := subscribeMap[consumerMessage.Topic][receivedMessage.MessageType]\n\n\tif callback == nil {\n\t\tlogrus.Error(fmt.Sprintf(\"callback not found for topic : %s, message type : %s\", consumerMessage.Topic,\n\t\t\treceivedMessage.MessageType))\n\t\treturn\n\t}\n\n\tgo callback(&Message{\n\t\tTopic: consumerMessage.Topic,\n\t\tMessage: receivedMessage.Message,\n\t\tMessageType: receivedMessage.MessageType,\n\t\tService: receivedMessage.Service,\n\t\tTraceId: receivedMessage.TraceId,\n\t\tMessageId: receivedMessage.MessageId,\n\t}, nil)\n}", "func TestConsumerTickerLoop(t *testing.T) {\n\texpect := ttesting.NewExpect(t)\n\tmockC := getMockConsumer()\n\tmockC.setState(PluginStateActive)\n\n\t// accept timeroff by abs( 15 ms)\n\ttickThreshold := float64(15 * time.Millisecond)\n\ttickerLoopTimeout := 20 * time.Millisecond\n\tlastTick := time.Now()\n\tcounter := new(int32)\n\n\tonTimeOut := func() {\n\t\tdefer func() {\n\t\t\tatomic.AddInt32(counter, 1)\n\t\t\tlastTick = time.Now()\n\t\t}()\n\n\t\tif atomic.LoadInt32(counter) > 3 {\n\t\t\tmockC.setState(PluginStateDead)\n\t\t\treturn\n\t\t}\n\n\t\tif atomic.LoadInt32(counter) > 0 {\n\t\t\tdeltaDiff := math.Abs(float64(tickerLoopTimeout - time.Since(lastTick)))\n\t\t\texpect.Less(deltaDiff, tickThreshold)\n\t\t}\n\t}\n\n\tmockC.tickerLoop(tickerLoopTimeout, onTimeOut)\n\ttime.Sleep(2 * time.Second)\n\t// in anycase, the callback has to be called atleast once\n\texpect.Greater(atomic.LoadInt32(counter), int32(1))\n}" ]
[ "0.5876569", "0.56525135", "0.53222644", "0.47999582", "0.47828177", "0.47699308", "0.47098765", "0.46049252", "0.45920306", "0.4560763", "0.45019993", "0.44990736", "0.4407609", "0.4383445", "0.42866144", "0.42831054", "0.42361563", "0.42217386", "0.4204431", "0.42024133", "0.4200147", "0.41932052", "0.41853583", "0.41822237", "0.41760316", "0.41300935", "0.4128459", "0.41247618", "0.4104638", "0.41005486", "0.4092167", "0.40907085", "0.40825716", "0.40749297", "0.40726155", "0.40721485", "0.40674758", "0.40590805", "0.40569532", "0.40265998", "0.40256128", "0.40189782", "0.4015255", "0.40138492", "0.40068057", "0.39973462", "0.39962187", "0.3995733", "0.39949635", "0.39938197", "0.39934778", "0.39875737", "0.3982926", "0.39752552", "0.3973805", "0.39707705", "0.39697373", "0.3966761", "0.39665523", "0.39584213", "0.39572668", "0.39572343", "0.39548144", "0.3953937", "0.39509052", "0.394783", "0.3940888", "0.39378253", "0.39356485", "0.3913344", "0.39131007", "0.3912053", "0.39030346", "0.3902831", "0.39027768", "0.39008138", "0.38971153", "0.389136", "0.3887498", "0.3885404", "0.38834408", "0.38824725", "0.38824302", "0.38758948", "0.3871928", "0.3870089", "0.38658443", "0.38521808", "0.38511652", "0.38501006", "0.3849449", "0.38464737", "0.38450384", "0.38405353", "0.3838324", "0.38364825", "0.3827314", "0.3817864", "0.38171208", "0.38148075" ]
0.79700077
0
optionalTimeout returns a channel on which the current time will be sent when the specified deadline arrives. Or, if deadline is nil, optionalTimeout returns a nil channel (receives will block forever, i.e. no timeout).
optionalTimeout возвращает канал, на котором будет отправлено текущее время, когда наступит указанный срок. Или, если срок истечения не указан, optionalTimeout возвращает nil-канал (прием будет блокироваться бесконечно, то есть нет таймаута).
func optionalTimeout(deadline *time.Time) <-chan time.Time { var timeout <-chan time.Time if deadline != nil { timeout = time.NewTimer(time.Until(*deadline)).C } return timeout }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *Sink) TimeoutChan() <-chan time.Time {\n\treturn f.timeoutTimer.C\n}", "func With_timeout_nowait(ctx context.Context, timeout time.Duration) option {\n\treturn func(o *Group) {\n\t\tif o.Context != nil {\n\t\t\tpanic(\"context already set\")\n\t\t}\n\t\tif ctx == nil {\n\t\t\to.Context, o.CancelFunc = context.WithTimeout(context.Background(), timeout)\n\t\t\treturn\n\t\t}\n\t\to.Context, o.CancelFunc = context.WithTimeout(ctx, timeout)\n\t}\n}", "func (w *ChannelWriter) SetDeadline(t time.Time) {\n\tw.deadline = t\n}", "func WithDeadline(d time.Duration) RingOption {\n\treturn func(r *Ring) error {\n\t\tr.deadline = d\n\t\ts := newRingSubmitter(r, d)\n\t\t// This is an ugly hack....\n\t\tgo s.run()\n\t\tr.submitter = s\n\t\treturn nil\n\t}\n}", "func Timeout() <-chan time.Time {\n\treturn Timeouts(GetNonSubscribeTimeout())\n}", "func NewTimeoutChan(ctx context.Context, resolution time.Duration, limit int) *TimeoutChan {\n\tsize := limit\n\tif limit == 0 {\n\t\tsize = 1024\n\t}\n\tin := make(chan Deadliner)\n\tout := make(chan Deadliner)\n\ttc := &TimeoutChan{\n\t\tIn: in,\n\t\tOut: out,\n\n\t\tctx: ctx,\n\t\tpushCtrl: NewController(ctx, \"TimeoutChan Push\"),\n\t\tpopCtrl: NewController(ctx, \"TimeoutChan Pop\"),\n\t\tresolution: resolution,\n\t\tlimit: limit,\n\t\tin: in,\n\t\tout: out,\n\t\tresumePush: make(chan interface{}),\n\t\tresumePop: make(chan interface{}),\n\t\treschedule: make(chan interface{}),\n\t\tclosePush: make(chan interface{}),\n\n\t\tmu: &sync.RWMutex{},\n\t\tpq: NewPriorityQueue(false, size),\n\t\tpushed: 0,\n\t\tpopped: 0,\n\t\tcleared: 0,\n\t}\n\ttc.popCtrl.Go(tc.popProcess)\n\ttc.pushCtrl.Go(tc.pushProcess)\n\treturn tc\n}", "func TestDeadline(t *testing.T) {\n\tmsgChan, _, wg := initTest()\n\teb := eventbus.New()\n\tsupervisor, err := monitor.Launch(eb, unixSoc)\n\tassert.NoError(t, err)\n\n\tlog.AddHook(supervisor)\n\n\t// Send an error entry, to trigger Send\n\tlog.Errorln(\"pippo\")\n\n\tmsg := <-msgChan\n\tassert.Equal(t, \"error\", msg[\"level\"])\n\tassert.Equal(t, \"pippo\", msg[\"msg\"])\n\n\t// The write deadline is 3 seconds, so let's wait for that to expire\n\ttime.Sleep(3 * time.Second)\n\n\tblk := helper.RandomBlock(t, 23, 4)\n\tmsgBlk := message.New(topics.AcceptedBlock, *blk)\n\teb.Publish(topics.AcceptedBlock, msgBlk)\n\n\t// Should get the accepted block message on the msgchan\n\tfor {\n\t\tmsg = <-msgChan\n\t\t// We should discard any other messages\n\t\tif msg[\"code\"] == \"round\" {\n\t\t\t// Success\n\t\t\tbreak\n\t\t}\n\t}\n\n\t_ = supervisor.Stop()\n\twg.Wait()\n}", "func timeoutDialer(secs int) func(net, addr string) (c net.Conn, err error) {\n\treturn func(netw, addr string) (net.Conn, error) {\n\t\tc, err := net.Dial(netw, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.SetDeadline(time.Now().Add(time.Duration(secs) * time.Second))\n\t\treturn c, nil\n\t}\n}", "func NewOptionalTicker(d time.Duration) *OptionalTicker {\n\tvar ticker OptionalTicker\n\tif d != 0 {\n\t\tticker.t = time.NewTicker(d)\n\t\tticker.C = ticker.t.C\n\t}\n\n\treturn &ticker\n}", "func ReceiveWait(t time.Duration) ReceiveOpt {\n\treturn func(m ReceiveMatcher) ReceiveMatcher {\n\t\tm.timeout = t\n\t\treturn m\n\t}\n}", "func ContextWithOptionalTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {\n\tif timeout < 0 {\n\t\t// This should be handled in validation\n\t\tklog.Errorf(\"Timeout for context shall not be negative!\")\n\t\ttimeout = 0\n\t}\n\n\tif timeout == 0 {\n\t\treturn context.WithCancel(parent)\n\t}\n\n\treturn context.WithTimeout(parent, timeout)\n}", "func TestMock_WithDeadlineCancel(t *testing.T) {\n\tm := NewMock()\n\tctx, cancel := m.WithDeadline(context.Background(), m.Now().Add(time.Second))\n\tcancel()\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.Canceled) {\n\t\t\tt.Error(\"invalid type of error returned after cancellation\")\n\t\t}\n\tcase <-time.After(time.Second):\n\t\tt.Error(\"context is not cancelled after cancel was called\")\n\t}\n}", "func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) Dialer {\n\treturn func(ctx context.Context, network, addr string) (net.Conn, error) {\n\t\tconn, err := net.DialTimeout(network, addr, cTimeout)\n\t\tif err != nil {\n\t\t\treturn conn, err\n\t\t}\n\n\t\tif rwTimeout > 0 {\n\t\t\terr = conn.SetDeadline(time.Now().Add(rwTimeout))\n\t\t}\n\n\t\treturn conn, err\n\t}\n}", "func (c *ChannelConn) SetDeadline(_ time.Time) error {\n\treturn nil\n}", "func TestMock_WithDeadlineImmediate(t *testing.T) {\n\tm := NewMock()\n\tctx, _ := m.WithDeadline(context.Background(), m.Now().Add(-time.Second))\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tt.Error(\"invalid type of error returned when deadline has already passed\")\n\t\t}\n\tdefault:\n\t\tt.Error(\"context is not cancelled when deadline has already passed\")\n\t}\n}", "func newNullableTicker(d time.Duration) (<-chan time.Time, func()) {\n\tif d > 0 {\n\t\tt := time.NewTicker(d)\n\t\treturn t.C, t.Stop\n\t}\n\treturn nil, func() {}\n}", "func (r *ChannelReader) SetDeadline(deadline time.Time) {\n\tr.deadline = deadline\n}", "func getDrainTimeout(ctx thrift.Context) time.Duration {\n\tif ctx != nil {\n\t\tif deadline, ok := ctx.Deadline(); ok {\n\t\t\treturn deadline.Sub(time.Now())\n\t\t}\n\t}\n\treturn defaultDrainTimeout\n}", "func (client *AmqpConsumer) ReceiveWithoutTimeout(exchange string, routingKeys []string, queue string, queueOptions QueueOptions) chan AmqpMessage {\n\treturn client.Receive(exchange, routingKeys, queue, queueOptions, 0*time.Second)\n}", "func TestMock_WithDeadline(t *testing.T) {\n\tm := NewMock()\n\tctx, _ := m.WithDeadline(context.Background(), m.Now().Add(time.Second))\n\tm.Add(time.Second)\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tt.Error(\"invalid type of error returned when deadline exceeded\")\n\t\t}\n\tdefault:\n\t\tt.Error(\"context is not cancelled when deadline exceeded\")\n\t}\n}", "func Timeout(timeout time.Duration) OptionFunc {\n\treturn func(tc *TracedClient) error {\n\t\tif timeout <= 0 {\n\t\t\treturn errors.New(\"timeout must be positive\")\n\t\t}\n\t\ttc.cl.Timeout = timeout\n\t\treturn nil\n\t}\n}", "func Timeout(d time.Duration) func(*Attacker) {\n\treturn func(a *Attacker) {\n\t\ta.client.Timeout = d\n\t}\n}", "func RedisOptIdleTimeout(idleTimeout time.Duration) RedisOpt {\n\treturn func(p *redis.Pool) {\n\t\tp.IdleTimeout = idleTimeout\n\t}\n}", "func (c *Conn) SetDeadline(t time.Time) error {\n // return c.conn.SetDeadline(t)\n fmt.Println(\"set deadline\", t)\n return nil\n}", "func (cfg *Config) Timeout(msg hotstuff.TimeoutMsg) {\n\tif cfg.cfg == nil {\n\t\treturn\n\t}\n\tvar ctx context.Context\n\tcfg.timeoutCancel()\n\tctx, cfg.timeoutCancel = context.WithCancel(context.Background())\n\tcfg.cfg.Timeout(ctx, proto.TimeoutMsgToProto(msg), gorums.WithNoSendWaiting())\n}", "func timeoutDialer(timeout time.Duration) func(string, string) (net.Conn, error) {\n\treturn func(network, addr string) (c net.Conn, err error) {\n\t\tc, err = net.DialTimeout(network, addr, timeout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn\n\t}\n}", "func (o BuildSpecPtrOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Timeout\n\t}).(pulumi.StringPtrOutput)\n}", "func Timeout(d time.Duration) func(*Server) {\n\treturn func(s *Server) {\n\t\ts.timeout = d\n\t}\n}", "func TestTimeout(t *testing.T) {\n\tgo func() {\n\t\ttime.Sleep(10 * time.Second)\n\t\tt.Fatal()\n\t}()\n\n\tpub, sub := testClients(t, 500*time.Millisecond)\n\trequire.Nil(t, sub.Subscribe(\"timeoutTestChannel\").Err)\n\n\tr := sub.Receive() // should timeout after a second\n\tassert.Equal(t, Error, r.Type)\n\tassert.NotNil(t, r.Err)\n\tassert.True(t, r.Timeout())\n\n\twaitCh := make(chan struct{})\n\tgo func() {\n\t\tr = sub.Receive()\n\t\tclose(waitCh)\n\t}()\n\trequire.Nil(t, pub.Cmd(\"PUBLISH\", \"timeoutTestChannel\", \"foo\").Err)\n\t<-waitCh\n\n\tassert.Equal(t, Message, r.Type)\n\tassert.Equal(t, \"timeoutTestChannel\", r.Channel)\n\tassert.Equal(t, \"foo\", r.Message)\n\tassert.Nil(t, r.Err, \"%s\", r.Err)\n\tassert.False(t, r.Timeout())\n}", "func (b *ASCIIOverTCP) Timeout(timeout time.Duration) time.Duration {\n\tt := b.Handler.Timeout\n\tb.Handler.Timeout = timeout\n\treturn t\n}", "func (async *async) waitOrTimeout(duration time.Duration) error {\n\ttimer := time.NewTimer(duration)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-timer.C:\n\t\treturn errors.New(\"operation cancelled\")\n\tcase <-async.done:\n\t\treturn nil\n\t}\n}", "func Timeout(o int) interface {\n\ttimeoutOptionSetter\n} {\n\treturn &timeoutOption{o}\n}", "func Timeout(timeout time.Duration, timeoutFunction OnTimeout) crOption {\n\treturn func(cr *ConsumerRegistration) *ConsumerRegistration {\n\t\tcr.timeout = timeout\n\t\tcr.onTimeout = timeoutFunction\n\t\treturn cr\n\t}\n}", "func WithoutPongDeadline() Option {\n\treturn func(o *options) {\n\t\to.pongWait = 0\n\t}\n}", "func (rw *NopConn) SetDeadline(time.Time) error { return nil }", "func (ch Ch) Receive(timeout int) (interface{}, error){\n\tif timeout<=0{\n\t\treturn nil,errors.New(\"timeout variable cannot be below or equals zero\")\n\t}\n\tselect {\n\tcase b:=<- ch:\n\t\treturn b, nil\n\tcase <-time.After(time.Duration(timeout)*time.Second):\n\t\treturn nil, errors.New(\"timeout data reception from channel\")\n\t}\n}", "func (p *Peer) heartbeatTimeoutFunc(startChannel chan bool) {\n\tstartChannel <- true\n\n\tfor {\n\t\t// Grab the current timer channel.\n\t\tp.mutex.Lock()\n\n\t\tvar c chan time.Time\n\t\tif p.heartbeatTimer != nil {\n\t\t\tc = p.heartbeatTimer.C()\n\t\t}\n\t\tp.mutex.Unlock()\n\n\t\t// If the channel or timer are gone then exit.\n\t\tif c == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Flush the peer when we get a heartbeat timeout. If the channel is\n\t\t// closed then the peer is getting cleaned up and we should exit.\n\t\tif _, ok := <-c; ok {\n\t\t\tp.flush(false)\n\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func TestMock_WithDeadlineLaterThanCurrent(t *testing.T) {\n\tm := NewMock()\n\tctx, _ := m.WithDeadline(context.Background(), m.Now().Add(time.Second))\n\tctx, _ = m.WithDeadline(ctx, m.Now().Add(10*time.Second))\n\tm.Add(time.Second)\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tt.Error(\"invalid type of error returned when deadline exceeded\")\n\t\t}\n\tdefault:\n\t\tt.Error(\"context is not cancelled when deadline exceeded\")\n\t}\n}", "func (r *timeoutReader) SetDeadline(t time.Time) {\n\tr.t = t\n}", "func WithRecvTimeout(timeout time.Duration) SessionOpt {\n\treturn func(so SessionOpts) SessionOpts {\n\t\tso.recvTimeout = timeout\n\t\treturn so\n\t}\n}", "func LeaveTimeoutOpt(timeout time.Duration) NodeDiscoverOpt {\n\treturn func(o *options) error {\n\t\to.leaveTimeout = timeout\n\t\treturn nil\n\t}\n}", "func WithDefaultTimeout(t time.Duration) Option {\n\treturn func(opt *options) {\n\t\topt.timeout = t\n\t}\n}", "func (c *Ctx) WithDeadline(deadline time.Time) (cf context.CancelFunc) {\n\tc.netContext, cf = context.WithDeadline(c.netContext, deadline)\n\treturn\n}", "func contextWithDeadline(t *testing.T) context.Context {\n\tt.Helper()\n\n\tdeadline, ok := t.Deadline()\n\tif !ok {\n\t\treturn context.Background()\n\t}\n\n\tctx, cancel := context.WithDeadline(context.Background(), deadline.Truncate(timeoutGracePeriod))\n\n\tt.Cleanup(cancel)\n\n\treturn ctx\n}", "func TimeoutOption(d time.Duration) Option {\n\treturn func(w *Webman) {\n\t\tw.timeout = d\n\t}\n}", "func (s *Sniffer) Recv(t *testing.T, timeout time.Duration) []byte {\n\tt.Helper()\n\n\tdeadline := time.Now().Add(timeout)\n\tfor {\n\t\ttimeout = time.Until(deadline)\n\t\tif timeout <= 0 {\n\t\t\treturn nil\n\t\t}\n\t\tusec := timeout.Microseconds()\n\t\tif usec == 0 {\n\t\t\t// Timeout is less than a microsecond; set usec to 1 to avoid\n\t\t\t// blocking indefinitely.\n\t\t\tusec = 1\n\t\t}\n\t\tconst microsInOne = 1e6\n\t\ttv := unix.Timeval{\n\t\t\tSec: usec / microsInOne,\n\t\t\tUsec: usec % microsInOne,\n\t\t}\n\t\tif err := unix.SetsockoptTimeval(s.fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &tv); err != nil {\n\t\t\tt.Fatalf(\"can't setsockopt SO_RCVTIMEO: %s\", err)\n\t\t}\n\n\t\tbuf := make([]byte, maxReadSize)\n\t\tnread, _, err := unix.Recvfrom(s.fd, buf, unix.MSG_TRUNC)\n\t\tif err == unix.EINTR || err == unix.EAGAIN {\n\t\t\t// There was a timeout.\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"can't read: %s\", err)\n\t\t}\n\t\tif nread > maxReadSize {\n\t\t\tt.Fatalf(\"received a truncated frame of %d bytes, want at most %d bytes\", nread, maxReadSize)\n\t\t}\n\t\treturn buf[:nread]\n\t}\n}", "func (ch Ch) Send(value interface{}, timeout int) error{\n\tif timeout<=0{\n\t\treturn errors.New(\"timeout variable cannot be below or equals zero\")\n\t}\n\tselect {\n\tcase ch<-value:\n\t\treturn errors.New(\"sending data to channel timeout\")\n\tcase <-time.After(time.Duration(timeout)*time.Second):\n\t\treturn nil\n\t}\n}", "func (c *TestConnection) SetDeadline(t time.Time) error {\n return errors.New(\"Not implemented\")\n}", "func TestClock_AfterElectionTimeout(t *testing.T) {\n\tc := raft.NewClock()\n\tc.ElectionTimeout = 10 * time.Millisecond\n\tt0 := time.Now()\n\t<-c.AfterElectionTimeout()\n\tif d := time.Since(t0); d < c.ElectionTimeout {\n\t\tt.Fatalf(\"channel fired too soon: %v\", d)\n\t}\n}", "func (o TriggerBuildPtrOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerBuild) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Timeout\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *context) Deadline() (deadline time.Time, ok bool) { return c.c.Deadline() }", "func (ls *LState) OptChannel(n int, ch chan LValue) chan LValue {\n\tv := ls.Get(n)\n\tif v == LNil {\n\t\treturn ch\n\t}\n\tif ch, ok := v.(LChannel); ok {\n\t\treturn (chan LValue)(ch)\n\t}\n\tls.TypeError(n, LTChannel)\n\treturn nil\n}", "func (c *Clock) AfterReconnectTimeout() <-chan chan struct{} { return newClockChan(c.ReconnectTimeout) }", "func ConstructTimeoutQueue( workers int ) chan *packet_metadata {\n\n timeoutQueue := make(chan *packet_metadata, 1000000)\n return timeoutQueue\n}", "func (me Broker) TimeoutContext(ctx context.Context) (\n\tcontext.Context, context.CancelFunc,\n) {\n\treturn context.WithTimeout(ctx, me.Timeout)\n}", "func (o BuildSpecOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildSpec) *string { return v.Timeout }).(pulumi.StringPtrOutput)\n}", "func (rp *RaftProcess) GetWithTimeout(serial uint64, timeout int) (etf.Ref, error) {\n\tvar ref etf.Ref\n\tif rp.quorum == nil {\n\t\treturn ref, ErrRaftNoQuorum\n\t}\n\n\tpeers := []etf.Pid{}\n\tfor _, pid := range rp.quorum.Peers {\n\t\tif pid == rp.Self() {\n\t\t\tcontinue\n\t\t}\n\t\tif c := rp.quorumCandidates.GetOnline(pid); c != nil {\n\t\t\tif serial > c.serial {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpeers = append(peers, pid)\n\t\t}\n\t}\n\tif len(peers) == 0 {\n\t\treturn ref, ErrRaftNoSerial\n\t}\n\n\t// get random member of quorum and send the request\n\tn := 0\n\tif len(peers) > 1 {\n\t\trand.Intn(len(peers) - 1)\n\t}\n\tpeer := peers[n]\n\tref = rp.MakeRef()\n\trequestGet := etf.Tuple{\n\t\tetf.Atom(\"$request_get\"),\n\t\trp.Self(),\n\t\tetf.Tuple{\n\t\t\trp.options.ID,\n\t\t\tref,\n\t\t\trp.Self(), // origin\n\t\t\tserial,\n\t\t},\n\t}\n\n\tif err := rp.Cast(peer, requestGet); err != nil {\n\t\treturn ref, err\n\t}\n\tcancel := rp.CastAfter(rp.Self, messageRaftRequestClean{ref: ref}, time.Duration(timeout)*time.Second)\n\trp.requests[ref] = cancel\n\treturn ref, nil\n}", "func (c *Clock) AfterElectionTimeout() <-chan chan struct{} {\n\td := c.ElectionTimeout + time.Duration(rand.Intn(int(c.ElectionTimeout)))\n\treturn newClockChan(d)\n}", "func SubscribeTimeout() <-chan time.Time {\n\treturn Timeouts(GetSubscribeTimeout())\n}", "func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {\n\tctx, f := context.WithDeadline(parent, deadline)\n\treturn ctx, f\n}", "func WithTimeout(duration time.Duration) Option {\n\treturn wrappedOption{oconf.WithTimeout(duration)}\n}", "func CollectiveBcastRecvTimeoutSeconds(value float32) CollectiveBcastRecvAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"timeout_seconds\"] = value\n\t}\n}", "func (p *Peer) heartbeatTimeoutFunc() {\n\tfor {\n\t\t// Grab the current timer channel.\n\t\tp.mutex.Lock()\n\t\tvar c chan time.Time\n\t\tif p.heartbeatTimer != nil {\n\t\t\tc = p.heartbeatTimer.C()\n\t\t}\n\t\tp.mutex.Unlock()\n\n\t\t// If the channel or timer are gone then exit.\n\t\tif c == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Flush the peer when we get a heartbeat timeout. If the channel is\n\t\t// closed then the peer is getting cleaned up and we should exit.\n\t\tif _, ok := <-c; ok {\n\t\t\t// Retrieve the peer data within a lock that is separate from the\n\t\t\t// server lock when creating the request. Otherwise a deadlock can\n\t\t\t// occur.\n\t\t\tp.mutex.Lock()\n\t\t\tserver, prevLogIndex := p.server, p.prevLogIndex\n\t\t\tp.mutex.Unlock()\n\n\t\t\t// Lock the server to create a request.\n\t\t\treq := server.createAppendEntriesRequest(prevLogIndex)\n\n\t\t\tp.mutex.Lock()\n\t\t\tp.sendFlushRequest(req)\n\t\t\tp.mutex.Unlock()\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (p *tubePool) setDeadline(ctx context.Context, tube tube) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\tvar deadline time.Time\n\tif d, ok := ctx.Deadline(); ok {\n\t\tdeadline = d\n\t}\n\treturn tube.SetDeadline(deadline)\n}", "func (w *WebrtcConn) SetDeadline(t time.Time) error {\n\treturn nil\n}", "func AbsoluteTimeout(idle int) Option {\n\treturn func(s *storage) {\n\t\ts.idleTimeout = idle\n\t}\n}", "func Timeout(t time.Duration) DiscoverOption {\n\treturn func(o *dOpts) {\n\t\to.timeout = t\n\t}\n}", "func (p *Peer) maybeAddDeadline(pendingResponses map[string]time.Time, msgCmd string) {\n\t// Setup a deadline for each message being sent that expects a response.\n\t//\n\t// NOTE: Pings are intentionally ignored here since they are typically\n\t// sent asynchronously and as a result of a long backlock of messages,\n\t// such as is typical in the case of initial block download, the\n\t// response won't be received in time.\n\tdeadline := time.Now().Add(stallResponseTimeout)\n\tswitch msgCmd {\n\tcase wire.CmdVersion:\n\t\t// Expects a verack message.\n\t\tpendingResponses[wire.CmdVerAck] = deadline\n\n\tcase wire.CmdMemPool:\n\t\t// Expects an inv message.\n\t\tpendingResponses[wire.CmdInv] = deadline\n\n\tcase wire.CmdGetBlocks:\n\t\t// Expects an inv message.\n\t\tpendingResponses[wire.CmdInv] = deadline\n\n\tcase wire.CmdGetData:\n\t\t// Expects a block, merkleblock, tx, or notfound message.\n\t\tpendingResponses[wire.CmdBlock] = deadline\n\t\tpendingResponses[wire.CmdMerkleBlock] = deadline\n\t\tpendingResponses[wire.CmdTx] = deadline\n\t\tpendingResponses[wire.CmdNotFound] = deadline\n\n\tcase wire.CmdGetHeaders:\n\t\t// Expects a headers message. Use a longer deadline since it\n\t\t// can take a while for the remote peer to load all of the\n\t\t// headers.\n\t\tdeadline = time.Now().Add(stallResponseTimeout * 3)\n\t\tpendingResponses[wire.CmdHeaders] = deadline\n\t}\n}", "func (o TaskOutput) DispatchDeadline() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Task) pulumi.StringOutput { return v.DispatchDeadline }).(pulumi.StringOutput)\n}", "func (d *Dialer) SetDeadline(deadline time.Time) {\n\td.deadline = deadline\n\td.okdeadline = true\n}", "func timeout(c chan int, t int) {\n\tgo func() {\n\t\ttime.Sleep(time.Second * time.Duration(t))\n\t\tc <- 1\n\t}()\n}", "func (filterdev *NetworkTap) Timeout() (*syscall.Timeval, error) {\n\tvar tv syscall.Timeval\n\t_, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(filterdev.device.Fd()), syscall.BIOCGRTIMEOUT, uintptr(unsafe.Pointer(&tv)))\n\tif err != 0 {\n\t\treturn nil, syscall.Errno(err)\n\t}\n\treturn &tv, nil\n}", "func (s stdlib) Timeout(time.Duration) {}", "func After(d Duration) <-chan Time {}", "func newDeadlineTimer(deadline time.Time) *deadlineTimer {\n\treturn &deadlineTimer{\n\t\tt: time.NewTimer(time.Until(deadline)),\n\t}\n}", "func (mq *LinuxMessageQueue) ReceiveTimeout(data []byte, timeout time.Duration) (int, error) {\n\tlen, _, err := mq.ReceiveTimeoutPriority(data, timeout) // ignore proirity\n\treturn len, err\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func (o *Basic) Timeout() int {\n\tif 0 == o.Options.Timeout {\n\t\treturn timeout\n\t}\n\treturn o.Options.Timeout\n}", "func Timeout(timeout time.Duration) ServerOption {\n\treturn func(s *Server) {\n\t\ts.timeout = timeout\n\t}\n}", "func (mq *LinuxMessageQueue) ReceiveTimeoutPriority(input []byte, timeout time.Duration) (int, int, error) {\n\tdataToReceive := input\n\tcurMaxMsgSize := len(mq.inputBuff)\n\tif len(input) < curMaxMsgSize {\n\t\tdataToReceive = mq.inputBuff\n\t}\n\tvar prio, actualMsgSize, maxMsgSize int\n\terr := common.UninterruptedSyscallTimeout(func(curTimeout time.Duration) error {\n\t\tvar err error\n\t\tactualMsgSize, maxMsgSize, err = mq_timedreceive(\n\t\t\tmq.ID(),\n\t\t\tdataToReceive,\n\t\t\t&prio,\n\t\t\tcommon.AbsTimeoutToTimeSpec(curTimeout))\n\t\treturn err\n\t}, timeout)\n\tif maxMsgSize != 0 && actualMsgSize != 0 {\n\t\tif curMaxMsgSize != maxMsgSize {\n\t\t\tmq.inputBuff = make([]byte, maxMsgSize)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn 0, 0, errors.Wrap(err, \"linux mq: receive failed\")\n\t}\n\tif len(input) < curMaxMsgSize {\n\t\tif len(input) < actualMsgSize {\n\t\t\treturn 0, 0, errors.Errorf(\"the buffer of %d bytes is too small for a %d bytes message\", len(input), actualMsgSize)\n\t\t}\n\t\tcopy(input, dataToReceive[:actualMsgSize])\n\t}\n\treturn actualMsgSize, prio, nil\n}", "func (o BuildRunStatusBuildSpecPtrOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunStatusBuildSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Timeout\n\t}).(pulumi.StringPtrOutput)\n}", "func Timeout() time.Duration { return note.Timeout }", "func goTimeout(t *testing.T, d time.Duration, f func()) {\n\tch := make(chan bool, 2)\n\ttimer := time.AfterFunc(d, func() {\n\t\tt.Errorf(\"Timeout expired after %v\", d)\n\t\tch <- true\n\t})\n\tdefer timer.Stop()\n\tgo func() {\n\t\tdefer func() { ch <- true }()\n\t\tf()\n\t}()\n\t<-ch\n}", "func UnaryUniversalDeadline(d time.Duration) grpc.UnaryServerInterceptor {\n\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\n\t\t//Also can get a deadline from the metadata\n\t\tctx, _ = context.WithDeadline(ctx, time.Now().Add(d))\n\n\t\tdone := make(chan bool)\n\n\t\tgo func() {\n\t\t\tresp, err = handler(ctx, req)\n\t\t\tdone <- true\n\t\t}()\n\n\t\t//Will return an error if the deadline passes before the handler is finished... should also figure out how to stop the handler from continuing if possible?\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, errors.New(\"Unable to complete request due to deadline\")\n\t\tcase <-done:\n\t\t\treturn resp, err\n\t\t}\n\t}\n}", "func (s *Conn) Timeout() time.Duration {\n\tif s.state == stateClosed {\n\t\treturn -1\n\t}\n\tnow := s.timeFn()\n\ts.logLossTimer(now)\n\tvar deadline time.Time\n\tif !s.drainingTimer.IsZero() {\n\t\tdeadline = s.drainingTimer\n\t} else if !s.recovery.lossDetectionTimer.IsZero() {\n\t\t// Minimum of loss and idle timer\n\t\tdeadline = s.recovery.lossDetectionTimer\n\t\tif !s.idleTimer.IsZero() && deadline.After(s.idleTimer) {\n\t\t\tdeadline = s.idleTimer\n\t\t}\n\t} else if !s.idleTimer.IsZero() {\n\t\tdeadline = s.idleTimer\n\t} else {\n\t\treturn -1\n\t}\n\ttimeout := deadline.Sub(now)\n\tif timeout < 0 {\n\t\ttimeout = 0\n\t}\n\treturn timeout\n}", "func (c *HostClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error {\n\treq.timeout = time.Until(deadline)\n\tif req.timeout < 0 {\n\t\treturn ErrTimeout\n\t}\n\treturn c.Do(req, resp)\n}", "func TestMock_WithDeadlineCancelledWithParent(t *testing.T) {\n\tm := NewMock()\n\tparent, cancel := context.WithCancel(context.Background())\n\tctx, _ := m.WithDeadline(parent, m.Now().Add(time.Second))\n\tcancel()\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.Canceled) {\n\t\t\tt.Error(\"invalid type of error returned after cancellation\")\n\t\t}\n\tcase <-time.After(time.Second):\n\t\tt.Error(\"context is not cancelled when parent context is cancelled\")\n\t}\n}", "func DefaultChooseTimeout(timeout time.Duration) Option {\n\treturn optionFunc(func(options *options) {\n\t\toptions.defaultChooseTimeout = &timeout\n\t})\n}", "func (w *ChannelWriter) Write(b []byte) (sz int, err error) {\n\tselect {\n\tcase w.c <- b:\n\t\treturn len(b), nil\n\tdefault:\n\t}\n\n\tif w.deadline.IsZero() {\n\t\tw.c <- b\n\t\treturn len(b), nil\n\t}\n\n\ttimer := time.NewTimer(w.deadline.Sub(time.Now()))\n\tdefer timer.Stop()\n\n\tselect {\n\tcase w.c <- b:\n\t\treturn len(b), nil\n\tcase <-timer.C:\n\t\treturn 0, context.DeadlineExceeded\n\t}\n}", "func (c *MockedHTTPContext) Deadline() (deadline time.Time, ok bool) {\n\tif c.MockedDeadline != nil {\n\t\treturn c.MockedDeadline()\n\t}\n\treturn time.Now(), false\n}", "func (c *txnClientCtx) commitTimeout(waitmsync bool) time.Duration {\n\tif waitmsync {\n\t\treturn c.timeout.host + c.timeout.netw\n\t}\n\treturn c.timeout.netw\n}", "func GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error) {\n\treturn defaultClient.GetDeadline(dst, url, deadline)\n}", "func Timeout(timeout int64) Option {\n\treturn func(opts *options) {\n\t\topts.timeout = time.Duration(timeout) * time.Second\n\t}\n}", "func (bw *BlockWriter) SetDeadline(t time.Time) error {\n\tbw.deadline = t\n\tif bw.conn != nil {\n\t\treturn bw.conn.SetDeadline(t)\n\t}\n\n\t// Return the error at connection time.\n\treturn nil\n}", "func TestWait_timeout(t *testing.T) {\n\tdefer check(t)\n\tcontent := \"hello world!\"\n\treq := &showcasepb.WaitRequest{\n\t\tEnd: &showcasepb.WaitRequest_Ttl{\n\t\t\tTtl: &durationpb.Duration{Seconds: 1},\n\t\t},\n\t\tResponse: &showcasepb.WaitRequest_Success{\n\t\t\tSuccess: &showcasepb.WaitResponse{Content: content},\n\t\t},\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\tdefer cancel()\n\n\top, err := echo.Wait(ctx, req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := op.Wait(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"Wait() = %+v, want error\", resp)\n\t}\n}", "func (o *ChatNewParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func TestClock_AfterReconnectTimeout(t *testing.T) {\n\tc := raft.NewClock()\n\tc.ReconnectTimeout = 10 * time.Millisecond\n\tt0 := time.Now()\n\t<-c.AfterReconnectTimeout()\n\tif d := time.Since(t0); d < c.ReconnectTimeout {\n\t\tt.Fatalf(\"channel fired too soon: %v\", d)\n\t}\n}" ]
[ "0.5174397", "0.5156724", "0.5065961", "0.5060068", "0.5043165", "0.50363374", "0.4978916", "0.49680018", "0.4962167", "0.49414706", "0.4929812", "0.48641688", "0.4854244", "0.48350728", "0.48332527", "0.48316026", "0.48256624", "0.48114562", "0.47939524", "0.4789711", "0.47847196", "0.47820517", "0.4776915", "0.47548705", "0.473034", "0.4723146", "0.46795171", "0.46763182", "0.46665353", "0.46609327", "0.46577755", "0.46575493", "0.46482185", "0.46426922", "0.46171218", "0.46170467", "0.4607814", "0.46071237", "0.45909518", "0.45901194", "0.45803556", "0.45725545", "0.45688236", "0.4547528", "0.45288515", "0.4518878", "0.45178142", "0.45161188", "0.45082343", "0.45046124", "0.44831705", "0.44797885", "0.44760364", "0.4474829", "0.4473707", "0.44691256", "0.44633913", "0.44555062", "0.44487435", "0.44480565", "0.44454473", "0.44409165", "0.44384676", "0.4432694", "0.4429949", "0.44201207", "0.44200516", "0.441241", "0.44016257", "0.43789184", "0.4372708", "0.43649206", "0.43616393", "0.43600416", "0.4357924", "0.43565834", "0.4347601", "0.4347601", "0.4347601", "0.4347601", "0.4345919", "0.43438876", "0.4342106", "0.43370944", "0.43344143", "0.43302944", "0.43174005", "0.43167153", "0.43138948", "0.4309054", "0.43069974", "0.43054056", "0.4301684", "0.43007502", "0.43001688", "0.42981714", "0.42959014", "0.42866904", "0.42802998", "0.42761993" ]
0.8052867
0
copyHeader adds the HTTP header whose name is the specified `which` from the specified headers `from` to the specified headers `to`.
copyHeader добавляет HTTP-заголовок, имя которого указано в `which`, из указанных заголовков `from` в указанные заголовки `to`.
func copyHeader(which string, from http.Header, to http.Header) { for _, value := range from.Values(which) { to.Add(which, value) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func copyHeader(target, source http.Header) {\n\tfor k, vs := range source {\n\t\ttarget[k] = vs\n\t}\n}", "func copyHeader(src, dest http.Header) {\n\tfor key, val := range src {\n\t\tfor _, v := range val {\n\t\t\tdest.Add(key, v)\n\t\t}\n\t}\n}", "func copyHeader(dst http.Header, src http.Header) {\n\tfor k, _ := range dst {\n\t\tdst.Del(k)\n\t}\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}", "func copyHeaders(source http.Header, destination http.Header) {\n\tfor h, vs := range source {\n\t\tfor _, v := range vs {\n\t\t\tdestination.Set(h, v)\n\t\t}\n\t}\n}", "func (h *RequestHeader) CopyTo(dst *RequestHeader) {\n\tdst.Reset()\n\n\tdst.disableNormalizing = h.disableNormalizing\n\tdst.noHTTP11 = h.noHTTP11\n\tdst.connectionClose = h.connectionClose\n\tdst.noDefaultContentType = h.noDefaultContentType\n\n\tdst.contentLength = h.contentLength\n\tdst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)\n\tdst.method = append(dst.method, h.method...)\n\tdst.proto = append(dst.proto, h.proto...)\n\tdst.requestURI = append(dst.requestURI, h.requestURI...)\n\tdst.host = append(dst.host, h.host...)\n\tdst.contentType = append(dst.contentType, h.contentType...)\n\tdst.userAgent = append(dst.userAgent, h.userAgent...)\n\tdst.trailer = append(dst.trailer, h.trailer...)\n\tdst.h = copyArgs(dst.h, h.h)\n\tdst.cookies = copyArgs(dst.cookies, h.cookies)\n\tdst.cookiesCollected = h.cookiesCollected\n\tdst.rawHeaders = append(dst.rawHeaders, h.rawHeaders...)\n}", "func CopyHeader(w http.ResponseWriter, r *http.Response) {\n\t// copy headers\n\tdst, src := w.Header(), r.Header\n\tfor k := range dst {\n\t\tdst.Del(k)\n\t}\n\tfor k, vs := range src {\n\t\tfor _, v := range vs {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}", "func CopyRequestHeaders(from, to *http.Request, headers []string) {\n\tfor _, header := range headers {\n\t\tvalue := from.Header.Get(header)\n\t\tif value != \"\" {\n\t\t\tto.Header.Set(header, value)\n\t\t}\n\t}\n}", "func copyHeaders(dst, src http.Header) {\n\tfor key, vals := range src {\n\t\tfor _, val := range vals {\n\t\t\tdst.Add(key, val)\n\t\t}\n\t}\n}", "func copySourceHeaders(sh http.Header) (th http.Header) {\n\tth = make(http.Header)\n\n\tif sh == nil {\n\t\treturn nil\n\t}\n\n\tfor key, values := range sh {\n\t\tif dhHeadersRe.MatchString(key) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, val := range values {\n\t\t\tth.Add(key, val)\n\t\t}\n\t}\n\n\treturn th\n}", "func CopyHeaders(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tdst[k] = append([]string{}, vv...)\n\t}\n}", "func copyHeaders(headerNames []string, srcRequest *http.Request, destRequest *http.Request) {\n for _, headerName := range headerNames {\n // TODO: make sure headerName exists in srcRequest.Header\n if headerValue := srcRequest.Header.Get(headerName); headerValue != \"\" {\n destRequest.Header.Set(headerName, headerValue)\n }\n }\n}", "func (h *ResponseHeader) CopyTo(dst *ResponseHeader) {\n\tdst.Reset()\n\n\tdst.disableNormalizing = h.disableNormalizing\n\tdst.noHTTP11 = h.noHTTP11\n\tdst.connectionClose = h.connectionClose\n\tdst.noDefaultContentType = h.noDefaultContentType\n\tdst.noDefaultDate = h.noDefaultDate\n\n\tdst.statusCode = h.statusCode\n\tdst.statusMessage = append(dst.statusMessage, h.statusMessage...)\n\tdst.protocol = append(dst.protocol, h.protocol...)\n\tdst.contentLength = h.contentLength\n\tdst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)\n\tdst.contentType = append(dst.contentType, h.contentType...)\n\tdst.contentEncoding = append(dst.contentEncoding, h.contentEncoding...)\n\tdst.server = append(dst.server, h.server...)\n\tdst.h = copyArgs(dst.h, h.h)\n\tdst.cookies = copyArgs(dst.cookies, h.cookies)\n\tdst.trailer = copyArgs(dst.trailer, h.trailer)\n}", "func CopyHeader(h *Header) *Header {\n\tcpy := *h\n\tif cpy.Time = new(big.Int); h.Time != nil {\n\t\tcpy.Time.Set(h.Time)\n\t}\n\tif cpy.SnailNumber = new(big.Int); h.SnailNumber != nil {\n\t\tcpy.SnailNumber.Set(h.SnailNumber)\n\t}\n\tif cpy.Number = new(big.Int); h.Number != nil {\n\t\tcpy.Number.Set(h.Number)\n\t}\n\tif len(h.Extra) > 0 {\n\t\tcpy.Extra = make([]byte, len(h.Extra))\n\t\tcopy(cpy.Extra, h.Extra)\n\t}\n\treturn &cpy\n}", "func CopyHeader(dst *LogBuffer, src *LogBuffer) {\n\tsrc.headerMU.Lock()\n\tdup, err := copystructure.Copy(src.header)\n\tdupBanner := src.AddBanner\n\tsrc.headerMU.Unlock()\n\n\tdst.headerMU.Lock()\n\tif err != nil {\n\t\tdst.header = map[string]interface{}{}\n\t} else {\n\t\tdst.header = dup.(map[string]interface{})\n\t}\n\tdst.AddBanner = dupBanner\n\tdst.headerMU.Unlock()\n}", "func copyHeaders(resp *http.Response, w http.ResponseWriter) {\n\tfor key, values := range resp.Header {\n\t\tfor _, value := range values {\n\t\t\tw.Header().Add(key, value)\n\t\t}\n\t}\n}", "func copyHeaders(headers map[string]interface{}) map[string]interface{} {\n\treturn copyHeader(headers).(map[string]interface{})\n}", "func (w *responseWrapper) copy(rw http.ResponseWriter) {\n\trw.WriteHeader(w.status)\n\n\tfor k, v := range w.header {\n\t\tfor _, vv := range v {\n\t\t\trw.Header().Add(k, vv)\n\t\t}\n\t}\n\tio.Copy(rw, w.buffer)\n}", "func copyHeader(v interface{}) interface{} {\n\tswitch x := v.(type) {\n\tcase string:\n\t\treturn x\n\tcase []interface{}:\n\t\tres := make([]interface{}, len(x))\n\t\tfor i, elem := range x {\n\t\t\tres[i] = copyHeader(elem)\n\t\t}\n\t\treturn res\n\tcase map[string]interface{}:\n\t\tres := make(map[string]interface{}, len(x))\n\t\tfor name, value := range x {\n\t\t\tif value == nil {\n\t\t\t\tcontinue // normalize nils out\n\t\t\t}\n\t\t\tres[name] = copyHeader(value)\n\t\t}\n\t\treturn res\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"internal error: encountered unexpected value type copying headers: %v\", v))\n\t}\n}", "func (_m *requestHeaderMapUpdatable) AddCopy(name string, value string) {\n\t_m.Called(name, value)\n}", "func copyHeadersToSend(headersToSend []string, r *ProxyRequest) map[string][]string {\n\tif len(headersToSend) == 0 {\n\t\theadersToSend = defaultHeadersToSend\n\t}\n\n\theaders := make(map[string][]string, len(headersToSend))\n\n\tfor _, k := range headersToSend {\n\t\tif k == requestParamsAsterisk {\n\t\t\tfor name, vs := range r.Headers {\n\t\t\t\ttmp := make([]string, len(vs))\n\t\t\t\tcopy(tmp, vs)\n\t\t\t\theaders[name] = tmp\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tvs, ok := r.Headers[k]\n\t\tif ok {\n\t\t\ttmp := make([]string, len(vs))\n\t\t\tcopy(tmp, vs)\n\t\t\theaders[k] = tmp\n\t\t}\n\t}\n\n\treturn headers\n}", "func newHTTPHeader(header, value string) httpHeader {\n\treturn httpHeader{Header: header, Value: value}\n}", "func CopyZipkinHeaders(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdata := make(map[string]string, 7)\n\t\tfor _, key := range zipkinHeaders {\n\t\t\tv := r.Header.Get(key)\n\t\t\tif v != \"\" {\n\t\t\t\tdata[key] = v\n\t\t\t}\n\t\t}\n\t\tmd := metadata.New(data)\n\t\tctx := metadata.NewOutgoingContext(r.Context(), md)\n\t\tr = r.WithContext(ctx)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (_m *requestHeaderMapUpdatable) AppendCopy(name string, value string) {\n\t_m.Called(name, value)\n}", "func (params *headerParams) Copy() Params {\n\tdup := NewParams()\n\tfor _, key := range params.Keys() {\n\t\tif val, ok := params.Get(key); ok {\n\t\t\tdup.Add(key, val)\n\t\t}\n\t}\n\n\treturn dup\n}", "func writeToHeader(w *http.ResponseWriter, statusCode int, payload interface{}) {\n\t(*w).WriteHeader(statusCode)\n\t(*w).Write(payload.([]byte))\n}", "func (h CommonHeader) Clone() api.HeaderMap {\n\tcopy := make(map[string]string)\n\n\tfor k, v := range h {\n\t\tcopy[k] = v\n\t}\n\n\treturn CommonHeader(copy)\n}", "func (t *Target) AddHeader(key, value string) {\n t.header.Add(key, value)\n}", "func (_m *requestHeaderMapUpdatable) SetCopy(name string, value string) {\n\t_m.Called(name, value)\n}", "func copyRequest(req *http.Request) *http.Request {\n\treq2 := new(http.Request)\n\t*req2 = *req\n\treq2.URL = new(url.URL)\n\t*req2.URL = *req.URL\n\treq2.Header = make(http.Header, len(req.Header))\n\tfor k, s := range req.Header {\n\t\treq2.Header[k] = append([]string(nil), s...)\n\t}\n\treturn req2\n}", "func (i *ICoreWebView2HttpRequestHeaders) SetHeader(name, value string) error {\n\t_name, err := windows.UTF16PtrFromString(name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t_value, err := windows.UTF16PtrFromString(value)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tres, _, err := i.vtbl.SetHeader.Call(\n\t\tuintptr(unsafe.Pointer(i)),\n\t\tuintptr(unsafe.Pointer(_name)),\n\t\tuintptr(unsafe.Pointer(_value)),\n\t)\n\tif err != windows.ERROR_SUCCESS {\n\t\treturn err\n\t}\n\tif windows.Handle(res) != windows.S_OK {\n\t\treturn syscall.Errno(res)\n\t}\n\treturn nil\n}", "func copy(to, from string) error {\n\ttoFd, err := os.Create(to)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer toFd.Close()\n\tfromFd, err := os.Open(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fromFd.Close()\n\t_, err = io.Copy(toFd, fromFd)\n\treturn err\n}", "func copy(to, from string) error {\n\ttoFd, err := os.Create(to)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer toFd.Close()\n\tfromFd, err := os.Open(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fromFd.Close()\n\t_, err = io.Copy(toFd, fromFd)\n\treturn err\n}", "func NewHeader(m map[string]string) Header {\n\tfor k, v := range m {\n\t\tdelete(m, k)\n\t\tm[http.CanonicalHeaderKey(k)] = v\n\t}\n\treturn Header(m)\n}", "func addHeaders(req *http.Request, opt *Options) {\n\tfor i := 0; i < len(opt.Headers); i += 2 {\n\t\tkey := opt.Headers[i]\n\t\tvalue := opt.Headers[i+1]\n\t\treq.Header.Add(key, value)\n\t}\n}", "func (this *SIPMessage) AddHeader(sipHeader header.Header) {\n\t// Content length is never stored. Just computed.\n\tsh := sipHeader.(header.Header)\n\t//try {\n\tif _, ok := sipHeader.(header.ViaHeader); ok {\n\t\tthis.AttachHeader3(sh, false, true)\n\t} else {\n\t\tthis.AttachHeader3(sh, false, false)\n\t}\n\t// } catch (SIPDuplicateHeaderException ex) {\n\t//try {\n\t//if cl, ok := sipHeader.(header.ContentLengthHeader); ok {\n\t//\t\tcontentLengthHeader.SetContentLength(cl.GetContentLength())\n\t//\t}\n\t// } catch (InvalidArgumentException e) {}\n\t//}\n}", "func (h *RequestHeader) WriteTo(w io.Writer) (int64, error) {\n\tn, err := w.Write(h.Header())\n\treturn int64(n), err\n}", "func (framer *HTTPFramer) Copy(dest io.Writer, src io.Reader) error {\n\tresp, err := http.ReadResponse(bufio.NewReader(src), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn resp.Write(dest)\n}", "func CopySnailHeader(h *SnailHeader) *SnailHeader {\n\tcpy := *h\n\tif cpy.Time = new(big.Int); h.Time != nil {\n\t\tcpy.Time.Set(h.Time)\n\t}\n\tif cpy.Difficulty = new(big.Int); h.Difficulty != nil {\n\t\tcpy.Difficulty.Set(h.Difficulty)\n\t}\n\tif cpy.FruitDifficulty = new(big.Int); h.FruitDifficulty != nil {\n\t\tcpy.FruitDifficulty.Set(h.FruitDifficulty)\n\t}\n\tif cpy.Number = new(big.Int); h.Number != nil {\n\t\tcpy.Number.Set(h.Number)\n\t}\n\tif cpy.FastNumber = new(big.Int); h.FastNumber != nil {\n\t\tcpy.FastNumber.Set(h.FastNumber)\n\t}\n\tif cpy.PointerNumber = new(big.Int); h.PointerNumber != nil {\n\t\tcpy.PointerNumber.Set(h.PointerNumber)\n\t}\n\tif len(h.Publickey) > 0 {\n\t\tcpy.Publickey = make([]byte, len(h.Publickey))\n\t\tcopy(cpy.Publickey, h.Publickey)\n\t}\n\tif len(h.Extra) > 0 {\n\t\tcpy.Extra = make([]byte, len(h.Extra))\n\t\tcopy(cpy.Extra, h.Extra)\n\t}\n\treturn &cpy\n}", "func (b binder) setFromHeaders() HTTPError {\n\tfor k, values := range b.req.Header {\n\t\tk = strings.ToLower(k)\n\t\tfor _, v := range values {\n\t\t\tif err := b.setField(k, v, ParamSourceHeader); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func DirtHeader(req *http.Request, header string, oldValue ...string) {\n\tvar dirtyHeaders map[string]string = make(map[string]string)\n\theader = sanitizeHeaderName(header)\n\toldVal := \"\"\n\tif len(oldVal) > 0 {\n\t\toldVal = oldValue[0]\n\t}\n\tdirtyHeadersPtr := DirtyHeaders(req)\n\tif dirtyHeadersPtr == nil {\n\t\tdirtyHeaders[header] = oldVal\n\t\tAddContextValue(req, dirtyHeadersKey, &dirtyHeaders)\n\t\treturn\n\t}\n\tdirtyHeaders = *dirtyHeadersPtr\n\tdirtyHeaders[header] = oldVal\n\t*dirtyHeadersPtr = dirtyHeaders\n}", "func (in *HTTPHeader) DeepCopyInto(out *HTTPHeader) {\n\t*out = *in\n\tif in.HeaderName != nil {\n\t\tin, out := &in.HeaderName, &out.HeaderName\n\t\t*out = new(string)\n\t\t**out = **in\n\t}\n\tif in.HeaderValue != nil {\n\t\tin, out := &in.HeaderValue, &out.HeaderValue\n\t\t*out = new(string)\n\t\t**out = **in\n\t}\n}", "func (hs *headers) PrependHeader(header Header) {\n\tname := strings.ToLower(header.Name())\n\tif hers, ok := hs.headers[name]; ok {\n\t\ths.headers[name] = append([]Header{header}, hers...)\n\t} else {\n\t\ths.headers[name] = []Header{header}\n\t\tnewOrder := make([]string, 1, len(hs.headerOrder)+1)\n\t\tnewOrder[0] = name\n\t\ths.headerOrder = append(newOrder, hs.headerOrder...)\n\t}\n}", "func ApplyHeaders(req *http.Request, h string) error {\n\tvar list = strings.Split(h, \"\\x1e\")\n\tfor _, fv := range list {\n\t\tvar parts = strings.SplitN(fv, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn fmt.Errorf(\"invalid header declaration %q\", fv)\n\t\t}\n\t\treq.Header.Set(parts[0], parts[1])\n\t}\n\n\treturn nil\n}", "func (self *AbtabURL) SetHeader(header []string) {\n\tself.Header = header\n\tself.HeaderMap = make(map[string]int)\n\tfor idx, fname := range header {\n\t\t//fmt.Printf(\"SetHeader: %s=%d\\n\", fname, idx)\n\t\tself.HeaderMap[fname] = idx\n\t}\n}", "func (h HeaderV2) WriteTo(w io.Writer) (int64, error) {\n\tif h.Command > CmdProxy {\n\t\treturn 0, errors.New(\"invalid command\")\n\t}\n\n\tvar rawHdr rawV2\n\tcopy(rawHdr.Sig[:], sigV2)\n\trawHdr.VerCmd = (2 << 4) | (0xf & byte(h.Command))\n\tsendEmpty := func() (int64, error) {\n\t\terr := binary.Write(w, binary.BigEndian, rawHdr)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn 16, nil\n\t}\n\tif h.Command == CmdLocal {\n\t\treturn sendEmpty()\n\t}\n\n\tbuf := newBuffer(16, 232)\n\n\tsetAddr := func(srcIP, dstIP net.IP, srcPort, dstPort int) (fam byte) {\n\t\tsrc := srcIP.To4()\n\t\tdst := dstIP.To4()\n\t\tif src != nil && dst != nil {\n\t\t\tfam = 0x1 // INET\n\t\t} else if src == nil && dst == nil {\n\t\t\tsrc = srcIP.To16()\n\t\t\tdst = dstIP.To16()\n\t\t\tfam = 0x2 // INET6\n\t\t}\n\t\tif src == nil || dst == nil {\n\t\t\treturn 0 // UNSPEC\n\t\t}\n\n\t\tbuf.Write(src)\n\t\tbuf.Write(dst)\n\t\tbinary.Write(buf, binary.BigEndian, uint16(srcPort))\n\t\tbinary.Write(buf, binary.BigEndian, uint16(dstPort))\n\n\t\treturn fam\n\t}\n\n\tswitch src := h.Src.(type) {\n\tcase *net.TCPAddr:\n\t\tdst, ok := h.Dest.(*net.TCPAddr)\n\t\tif !ok {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\taddrFam := setAddr(src.IP, dst.IP, src.Port, dst.Port)\n\t\tif addrFam == 0 {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\trawHdr.FamProto = (addrFam << 4) | 0x1 // 0x1 == STREAM\n\tcase *net.UDPAddr:\n\t\tdst, ok := h.Dest.(*net.UDPAddr)\n\t\tif !ok {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\taddrFam := setAddr(src.IP, dst.IP, src.Port, dst.Port)\n\t\tif addrFam == 0 {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\trawHdr.FamProto = (addrFam << 4) | 0x2 // 0x2 == DGRAM\n\tcase *net.UnixAddr:\n\t\tdst, ok := h.Dest.(*net.UnixAddr)\n\t\tif !ok || src.Net != dst.Net {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\tif len(src.Name) > 108 || len(dst.Name) > 108 {\n\t\t\t// name too long to use\n\t\t\treturn sendEmpty()\n\t\t}\n\t\tswitch src.Net {\n\t\tcase \"unix\":\n\t\t\trawHdr.FamProto = (0x3 << 4) | 0x1 // 0x3 (UNIX) | 0x1 (STREAM)\n\t\tcase \"unixgram\":\n\t\t\trawHdr.FamProto = (0x3 << 4) | 0x2 // 0x3 (UNIX) | 0x2 (DGRAM)\n\t\tdefault:\n\t\t\treturn sendEmpty()\n\t\t}\n\t\tbuf.Write([]byte(src.Name))\n\t\tbuf.Seek(108 + 16)\n\t\tbuf.Write([]byte(dst.Name))\n\t\tbuf.Seek(232)\n\t}\n\n\trawHdr.Len = uint16(buf.Len() - 16)\n\n\tbuf.Seek(0)\n\terr := binary.Write(buf, binary.BigEndian, rawHdr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn buf.WriteTo(w)\n}", "func (this *SIPMessage) AttachHeader3(h header.Header, replaceFlag, top bool) error { //throws SIPDuplicateHeaderException {\n\tif h == nil {\n\t\terrors.New(\"NullPointerException: nil header\")\n\t}\n\n\tif replaceFlag {\n\t\tdelete(this.nameTable, strings.ToLower(h.GetName()))\n\t} else {\n\t\tif _, present := this.nameTable[strings.ToLower(h.GetName())]; present {\n\t\t\tif _, ok := h.(header.SIPHeaderLister); !ok {\n\t\t\t\tif cl, ok := h.(*header.ContentLength); ok {\n\t\t\t\t\tthis.contentLengthHeader.SetContentLength(cl.GetContentLength())\n\t\t\t\t}\n\t\t\t\t// Just ignore duplicate header.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\toriginalHeader := this.GetHeader(h.GetName())\n\n\t// Delete the original sh from our list structure.\n\tif originalHeader != nil {\n\t\tfor li := this.headers.Front(); li != nil; li = li.Next() {\n\t\t\tnext := li.Value.(header.Header)\n\t\t\tif next == originalHeader {\n\t\t\t\tthis.headers.Remove(li)\n\t\t\t}\n\t\t}\n\t}\n\n\tif this.GetHeader(h.GetName()) == nil {\n\t\tthis.nameTable[strings.ToLower(h.GetName())] = h\n\t\tthis.headers.PushBack(h)\n\t} else {\n\t\tif hs, ok := h.(header.SIPHeaderLister); ok {\n\t\t\thdrlist := this.nameTable[strings.ToLower(h.GetName())].(header.SIPHeaderLister)\n\t\t\tif hdrlist != nil {\n\t\t\t\thdrlist.Concatenate(hs, top)\n\t\t\t} else {\n\t\t\t\tthis.nameTable[strings.ToLower(h.GetName())] = h\n\t\t\t}\n\t\t} else {\n\t\t\tthis.nameTable[strings.ToLower(h.GetName())] = h\n\t\t}\n\t}\n\n\t// Direct accessor fields for frequently accessed headers.\n\tif sh, ok := h.(*header.From); ok {\n\t\tthis.fromHeader = sh\n\t} else if sh, ok := h.(*header.ContentLength); ok {\n\t\tthis.contentLengthHeader = sh\n\t} else if sh, ok := h.(*header.To); ok {\n\t\tthis.toHeader = sh\n\t} else if sh, ok := h.(*header.CSeq); ok {\n\t\tthis.cSeqHeader = sh\n\t} else if sh, ok := h.(*header.CallID); ok {\n\t\tthis.callIdHeader = sh\n\t} else if sh, ok := h.(*header.MaxForwards); ok {\n\t\tthis.maxForwardsHeader = sh\n\t}\n\n\treturn nil\n}", "func copyInnerNodeHeader(dst, src *innerNodeHeader) {\n\t// Shallow copy is sufficient because prefix is an embedded array of byte\n\t// not a slice pointing to a shared array, but we can't just use = since\n\t// that would override the id and ref in nodeHeader\n\tdst.leaf = src.leaf\n\tdst.nChildren = src.nChildren\n\tdst.prefixLen = src.prefixLen\n\tdst.prefix = src.prefix\n}", "func (c *Action) AddHeader(key string, value string) {\n\tc.Header().Add(key, value)\n}", "func (f *FileAttributes) HeaderAttributesCopy() map[string]any {\n\treturn mapCopy(f.HeaderAttributes)\n}", "func (proxy *Proxy) copyRequest(originalRequest *http.Request) *http.Request {\n\tproxyRequest := new(http.Request)\n\tproxyURL := new(url.URL)\n\t*proxyRequest = *originalRequest\n\t*proxyURL = *originalRequest.URL\n\tproxyRequest.URL = proxyURL\n\tproxyRequest.Proto = \"HTTP/1.1\"\n\tproxyRequest.ProtoMajor = 1\n\tproxyRequest.ProtoMinor = 1\n\tproxyRequest.Close = false\n\tproxyRequest.Header = make(http.Header)\n\tproxyRequest.URL.Scheme = \"http\"\n\tproxyRequest.URL.Path = originalRequest.URL.Path\n\n\t// Copy all header fields except ignoredHeaderNames'.\n\tnv := 0\n\tfor _, vv := range originalRequest.Header {\n\t\tnv += len(vv)\n\t}\n\tsv := make([]string, nv)\n\tfor k, vv := range originalRequest.Header {\n\t\tif _, ok := ignoredHeaderNames[k]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tn := copy(sv, vv)\n\t\tproxyRequest.Header[k] = sv[:n:n]\n\t\tsv = sv[n:]\n\t}\n\n\treturn proxyRequest\n}", "func (t Header) Clone() Header {\n\tt.Key = append([]KeyField{}, t.Key...)\n\tt.Data = append([]Field{}, t.Data...)\n\treturn t\n}", "func (hs *headers) CloneHeaders() []Header {\n\thers := make([]Header, 0)\n\tfor _, header := range hs.Headers() {\n\t\thers = append(hers, header.Copy())\n\t}\n\n\treturn hers\n}", "func copyTo(dst []byte, src []byte, offset int) {\n\tfor j, k := range src {\n\t\tdst[offset+j] = k\n\t}\n}", "func CopySourceIfMatch(value string) Option {\n\treturn setHeader(\"X-Oss-Copy-Source-If-Match\", value)\n}", "func (h *Header) Clone() *Header {\n\thc := &Header{slice: make([]string, len(h.slice))}\n\tcopy(hc.slice, h.slice)\n\treturn hc\n}", "func (headers Headers) UpdateHeader(reqHeaders http.Header) {\n\tfor _, h := range headers {\n\t\tswitch h.Op {\n\t\tcase \"\", \"set\":\n\t\t\treqHeaders.Set(h.Key, h.Value)\n\t\tcase \"add\":\n\t\t\treqHeaders.Add(h.Key, h.Value)\n\t\tcase \"del\":\n\t\t\treqHeaders.Del(h.Key)\n\t\t}\n\t}\n}", "func Header(k, v string) RequestOpt { return func(r *http.Request) { r.Header.Add(k, v) } }", "func InjectHeader(h http.Header) InterceptorFn {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn RoundTripperFn(func(req *http.Request) (*http.Response, error) {\n\t\t\tfor k, v := range h {\n\t\t\t\tfor _, vv := range v {\n\t\t\t\t\treq.Header.Add(k, vv)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn rt.RoundTrip(req)\n\t\t})\n\t}\n}", "func mergeHeaders(h1, h2 http.Header) http.Header {\n\th := http.Header{}\n\tfor key, values := range h2 {\n\t\tfor _, value := range values {\n\t\t\th.Set(key, value)\n\t\t}\n\t}\n\tfor key, values := range h1 {\n\t\tfor _, value := range values {\n\t\t\th.Set(key, value)\n\t\t}\n\t}\n\treturn h\n}", "func (c *PrivateClient) addHeaders(req *http.Request, h headers) *http.Request {\n\tfor k, v := range c.headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tif h != nil {\n\t\tfor k, v := range h {\n\t\t\treq.Header[k] = v\n\t\t}\n\t}\n\treturn req\n}", "func PassThroughHeaders(headers http.Header) http.Header {\n\th := http.Header{}\n\n\tfor n, v := range headers {\n\t\tlower := strings.ToLower(n)\n\t\tif forwardHeaders.Has(lower) {\n\t\t\th[n] = v\n\t\t\tcontinue\n\t\t}\n\t\tfor _, prefix := range forwardPrefixes {\n\t\t\tif strings.HasPrefix(lower, prefix) {\n\t\t\t\th[n] = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn h\n}", "func ConvertHeader(ctx context.Context, src, dst types.Protocol, srcHeader types.HeaderMap) (types.HeaderMap, error) {\n\tif sub, subOk := protoConvFactory[src]; subOk {\n\t\tif f, ok := sub[dst]; ok {\n\t\t\treturn f.ConvHeader(ctx, srcHeader)\n\t\t}\n\t}\n\treturn nil, ErrNotFound\n}", "func (f *Fs) addHeaders(headers fs.CommaSepList) {\n\tfor i := 0; i < len(headers); i += 2 {\n\t\tkey := f.opt.Headers[i]\n\t\tvalue := f.opt.Headers[i+1]\n\t\tf.srv.SetHeader(key, value)\n\t}\n}", "func Copy(\n\tctx context.Context,\n\tfrom ReadBucket,\n\tto ReadWriteBucket,\n\toptions ...normalpath.TransformerOption,\n) (int, error) {\n\treturn CopyPrefix(ctx, from, to, \"\", options...)\n}", "func InjectHeader(r *http.Request, key, val string) {\n\tr.Header.Add(key, val)\n}", "func addHeaders(req *http.Request, header http.Header) {\n\tfor key, values := range header {\n\t\tfor _, value := range values {\n\t\t\treq.Header.Add(key, value)\n\t\t}\n\t}\n}", "func (pw *pooledWriter) SetHeader(h writer.Header) {\n\tpw.Name = h.Name\n\tpw.Extra = h.Extra\n\tpw.Comment = h.Comment\n\tpw.ModTime = h.ModTime\n\tpw.OS = h.OS\n}", "func (h HandshakeHeaderHTTP) WriteTo(w io.Writer) (int64, error) {\n\twr := writer{w: w}\n\terr := http.Header(h).Write(&wr)\n\treturn wr.n, err\n}", "func (c *Action) SetHeader(key string, value string) {\n\tc.Header().Set(key, value)\n}", "func (c *CommandDescriptor) SetHeader(key string, value interface{}) {\n\tc.headers[key] = value\n}", "func CopySource(sourceBucket, sourceObject string) Option {\n\treturn setHeader(\"X-Oss-Copy-Source\", \"/\"+sourceBucket+\"/\"+sourceObject)\n}", "func (hs *headers) AddHeader(header Header) {\n\tname := strings.ToLower(header.Name())\n\tif headerList, ok := hs.headers[name]; ok {\n\t\ta := headerList[0]\n\t\tlogger.Error(headerList[0])\n\t\tlogger.Error(a)\n\t\tlogger.Error(headerList[0].Equals(Header(nil)))\n\t\tlogger.Error(headerList[0].String())\n\t\tif len(headerList) > 0 && !headerList[0].Equals(nil) {\n\t\t\ths.headers[name] = append(headerList, header)\n\t\t} else {\n\t\t\ths.headers[name] = []Header{header}\n\t\t}\n\t} else {\n\t\ths.headers[name] = []Header{header}\n\t\ths.headerOrder = append(hs.headerOrder, name)\n\t}\n}", "func FilterHeader(header http.Header) http.Header {\n\tnewHeader := make(http.Header)\n\tfor k, v := range header {\n\t\tswitch k {\n\t\tcase \"Authorization\":\n\t\t// ignore these headers\n\t\tdefault:\n\t\t\tnewHeader[k] = v\n\t\t}\n\t}\n\n\treturn newHeader\n}", "func Copy(c *gophercloud.ServiceClient, containerName, objectName string, opts CopyOptsBuilder) CopyResult {\n\tvar res CopyResult\n\th := c.AuthenticatedHeaders()\n\n\theaders, err := opts.ToObjectCopyMap()\n\tif err != nil {\n\t\tres.Err = err\n\t\treturn res\n\t}\n\n\tfor k, v := range headers {\n\t\th[k] = v\n\t}\n\n\turl := copyURL(c, containerName, objectName)\n\tresp, err := c.Request(\"COPY\", url, gophercloud.RequestOpts{\n\t\tMoreHeaders: h,\n\t\tOkCodes: []int{201},\n\t})\n\tif resp != nil {\n\t\tres.Header = resp.Header\n\t}\n\tres.Err = err\n\treturn res\n}", "func ExtractHeader(name string, dest *string) func(http.RoundTripper) http.RoundTripper {\n\treturn func(tr http.RoundTripper) http.RoundTripper {\n\t\treturn &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {\n\t\t\tres, err := tr.RoundTrip(req)\n\t\t\tif err == nil {\n\t\t\t\tif value := res.Header.Get(name); value != \"\" {\n\t\t\t\t\t*dest = value\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn res, err\n\t\t}}\n\t}\n}", "func (c *PublicClient) addHeaders(req *http.Request, h headers) *http.Request {\n\tfor k, v := range c.headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tif h != nil {\n\t\tfor k, v := range h {\n\t\t\treq.Header[k] = v\n\t\t}\n\t}\n\treturn req\n}", "func AddHeader(name, value string) ClientOption {\n\treturn func(tr http.RoundTripper) http.RoundTripper {\n\t\treturn &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {\n\t\t\thost := req.Host\n\t\t\tlog.Logger().Debugf(\"sending request to host '%s'\", host)\n\t\t\tif name == \"Authorization\" {\n\t\t\t\tif host == \"api.github.com\" {\n\t\t\t\t\tlog.Logger().Debugf(\"Adding Authorization Header %s=%s\", name, Mask(value))\n\t\t\t\t\treq.Header.Add(name, value)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Logger().Debugf(\"Adding Header %s=%s\", name, Mask(value))\n\t\t\t\treq.Header.Add(name, value)\n\t\t\t}\n\n\t\t\treturn tr.RoundTrip(req)\n\t\t}}\n\t}\n}", "func (m *Modifier) ChangeHeader(index int, name, value string) error {\n\tvar buffer bytes.Buffer\n\tif err := binary.Write(&buffer, binary.BigEndian, uint32(index)); err != nil {\n\t\treturn err\n\t}\n\tbuffer.WriteString(name + null)\n\tbuffer.Write(crlfToLF([]byte(value)))\n\tbuffer.WriteString(null)\n\treturn m.writePacket(NewResponse('m', buffer.Bytes()).Response())\n}", "func writeRequestHeaders(writer io.Writer, request *http.Request) error {\n\tif _, err := fmt.Fprintf(\n\t\twriter,\n\t\t\"%s %s %s\\r\\n\",\n\t\trequest.Method,\n\t\trequest.URL.RequestURI(),\n\t\trequest.Proto,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tif err := request.Header.Write(writer); err != nil {\n\t\treturn err\n\t}\n\n\t_, err := io.WriteString(writer, \"\\r\\n\")\n\treturn err\n}", "func (in *HTTPHeader) DeepCopy() *HTTPHeader {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HTTPHeader)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (msg *Message) writeHeader(buffer *bytes.Buffer) {\n\tfor key, values := range msg.Headers {\n\t\tfor _, keyval := range values {\n\t\t\tio.WriteString(buffer, key)\n\t\t\tio.WriteString(buffer, \": \")\n\t\t\tswitch {\n\t\t\tcase key == \"Content-Type\" || key == \"Content-Disposition\":\n\t\t\t\tbuffer.Write([]byte(keyval))\n\t\t\tdefault:\n\t\t\t\tbuffer.Write([]byte(mime.QEncoding.Encode(\"UTF-8\", keyval)))\n\t\t\t}\n\t\t\tio.WriteString(buffer, \"\\r\\n\")\n\t\t}\n\t}\n\tio.WriteString(buffer, \"\\r\\n\")\n}", "func (client *graphqlClient)AddHeader(headerName string, headerValue string){\n client.header.Add(headerName,headerValue)\n}", "func (g *Generator) NewHeader(step *pathway.Step) *message.HeaderInfo {\n\treturn g.headerGenerator.NewHeader(step)\n}", "func (h blockHeader) appendTo(b []byte) []byte {\n\treturn append(b, uint8(h), uint8(h>>8), uint8(h>>16))\n}", "func Headers(self *C.PyObject, args, kwargs *C.PyObject) *C.PyObject {\n\th := util.HTTPHeaders()\n\n\tdict := C.PyDict_New()\n\tfor k, v := range h {\n\t\tcKey := C.CString(k)\n\t\tpyKey := C.PyString_FromString(cKey)\n\t\tdefer C.Py_DecRef(pyKey)\n\t\tC.free(unsafe.Pointer(cKey))\n\n\t\tcVal := C.CString(v)\n\t\tpyVal := C.PyString_FromString(cVal)\n\t\tdefer C.Py_DecRef(pyVal)\n\t\tC.free(unsafe.Pointer(cVal))\n\n\t\tC.PyDict_SetItem(dict, pyKey, pyVal)\n\t}\n\n\t// some checks need to add an extra header when they pass `http_host`\n\tif kwargs != nil {\n\t\tcKey := C.CString(\"http_host\")\n\t\t// in case of failure, the following doesn't set an exception\n\t\t// pyHttpHost is borrowed\n\t\tpyHTTPHost := C.PyDict_GetItemString(kwargs, cKey)\n\t\tC.free(unsafe.Pointer(cKey))\n\t\tif pyHTTPHost != nil {\n\t\t\t// set the Host header\n\t\t\tcKey = C.CString(\"Host\")\n\t\t\tC.PyDict_SetItemString(dict, cKey, pyHTTPHost)\n\t\t\tC.free(unsafe.Pointer(cKey))\n\t\t}\n\t}\n\n\treturn dict\n}", "func (h *Header) AddHeader(header *Header) {\n\tif header != nil {\n\t\tfor i := 0; i < header.Len(); i++ {\n\t\t\tkey, value := header.GetAt(i)\n\t\t\th.Add(key, value)\n\t\t}\n\t}\n}", "func SpanTransferFromContextToHeader(ctx context.Context) context.Context {\n\tvar parentCtx opentracing.SpanContext\n\tif parent := opentracing.SpanFromContext(ctx); parent != nil {\n\t\tparentCtx = parent.Context()\n\t}\n\tsp := opentracing.StartSpan(\n\t\t\"GRPCToHTTP\",\n\t\topentracing.FollowsFrom(parentCtx),\n\t\text.SpanKindRPCClient,\n\t)\n\tdefer sp.Finish()\n\treturn opentracing.ContextWithSpan(context.Background(), sp)\n}", "func (h *Histogram) copyHDataFrom(src *Histogram) {\n\tif h.Divider == src.Divider && h.Offset == src.Offset {\n\t\tfor i := 0; i < len(h.Hdata); i++ {\n\t\t\th.Hdata[i] += src.Hdata[i]\n\t\t}\n\t\treturn\n\t}\n\n\thData := src.Export()\n\tfor _, data := range hData.Data {\n\t\th.record((data.Start+data.End)/2, int(data.Count))\n\t}\n}", "func (rp *ReqParams) AddHeader(key, value string) {\n\tif rp.headers == nil {\n\t\trp.headers = make(map[string]string)\n\t}\n\n\trp.headers[key] = value\n}", "func existingOrNewHeader(cfg exportConfig, src StorageDriver, key *CryptoKey, ct CompressionType) (*Header, error) {\n\theader, err := LoadHeader(cfg.SnapshotID, src, key, ct)\n\n\tif errors.Cause(err) == ErrDataDidNotExist {\n\t\t// deduped map did not exist yet,\n\t\t// return a new one based on the given export config\n\t\treturn newExportHeader(cfg), nil\n\t}\n\tif err != nil {\n\t\t// deduped map did exist, but we couldn't load it.\n\t\tif cfg.Force {\n\t\t\t// we forcefully create a new one anyhow if `force == true`\n\t\t\tlog.Debugf(\n\t\t\t\t\"couldn't read header for snapshot '%s' due to an error (%s), forcefully creating a new one\",\n\t\t\t\tcfg.SnapshotID, err)\n\t\t\treturn newExportHeader(cfg), nil\n\t\t}\n\t\t// deduped map did exist,\n\t\t// but an error was triggered while fetching it\n\t\treturn nil, err\n\t}\n\n\tif header.Metadata.BlockSize != cfg.DstBlockSize {\n\t\tif cfg.Force {\n\t\t\t// we forcefully create a new one anyhow if `force == true`\n\t\t\tlog.Debugf(\n\t\t\t\t\"existing header for snapshot '%s' defined incompatible snapshot blocksize, forcefully creating a new one\",\n\t\t\t\tcfg.SnapshotID)\n\t\t\treturn newExportHeader(cfg), nil\n\t\t}\n\n\t\treturn nil, errIncompatibleHeader\n\t}\n\n\t// update information to match new export session\n\theader.Metadata.Created = time.Now().Format(time.RFC3339)\n\theader.Metadata.Source.VdiskID = cfg.VdiskID\n\theader.Metadata.Source.BlockSize = cfg.SrcBlockSize\n\theader.Metadata.Source.Size = int64(cfg.VdiskSize)\n\theader.Metadata.Version = zerodisk.CurrentVersion\n\n\t// return existing header, which was updated\n\tlog.Debugf(\"loaded and updated existing header for snapshot %s\", cfg.SnapshotID)\n\treturn header, nil\n}", "func (w *Writer) WriteHeader(hdr *index.Header) error {\n\t// Flush out preceding file's content before starting new range.\n\tif !w.first {\n\t\tif err := w.tw.Flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tw.first = false\n\t// Setup index header for next file.\n\t// (bryce) might want to deep copy the passed in header.\n\tw.hdr = &index.Header{\n\t\tHdr: hdr.Hdr,\n\t\tIdx: &index.Index{DataOp: &index.DataOp{}},\n\t}\n\tw.cw.StartRange(w.callback(w.hdr))\n\tif err := w.tw.WriteHeader(w.hdr.Hdr); err != nil {\n\t\treturn err\n\t}\n\t// Setup first tag for header.\n\tw.hdr.Idx.DataOp.Tags = []*index.Tag{&index.Tag{Id: headerTag, SizeBytes: w.cw.RangeSize()}}\n\treturn nil\n}", "func (request *ActivityRecordHeartbeatRequest) CopyTo(target IProxyMessage) {\n\trequest.ActivityRequest.CopyTo(target)\n\tif v, ok := target.(*ActivityRecordHeartbeatRequest); ok {\n\t\tv.SetDetails(request.GetDetails())\n\t}\n}", "func addProxyAddToHeader(remoteAddr, realIP string, fwd []string, header http.Header, omitForward bool) {\n\trip, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif realIP != \"\" {\n\t\theader.Set(\"X-Real-IP\", realIP)\n\t} else {\n\t\theader.Set(\"X-Real-IP\", rip)\n\t}\n\n\tif !omitForward {\n\t\theader[\"X-Forwarded-For\"] = fwd[:]\n\t\theader.Add(\"X-Forwarded-For\", rip)\n\t}\n}", "func (ctx *Context) SetHeader(hdr string, val string, unique bool) {\n\tif unique {\n\t\tctx.Header().Set(hdr, val)\n\t} else {\n\t\tctx.Header().Add(hdr, val)\n\t}\n}", "func (b *Builder) AddHeader(headers ...string) *Builder {\n\tfor i := range headers {\n\t\tb.headers = append(b.headers, headers[i]+\"\\r\\n\")\n\t}\n\treturn b\n}", "func (v *DCHttpClient) SetCommonHeader(key string, value string) {\n\tv.CHeader[key] = value\n}", "func mergeHeaders(headers, extraHeaders map[string]string) map[string]string {\n\tfor k, v := range extraHeaders {\n\t\theaders[k] = v\n\t}\n\treturn headers\n}", "func Copy(h *hdrhistogram.Histogram) *hdrhistogram.Histogram {\n\tdup := hdrhistogram.New(h.LowestTrackableValue(), h.HighestTrackableValue(),\n\t\tint(h.SignificantFigures()))\n\tdup.Merge(h)\n\treturn dup\n}", "func (rwp *ResponseWriterProxy) WriteHeader(statusCode int) {\n\trwp.response.Status = statusCode\n\trwp.response.Headers = parseStringArrMap(rwp.under.Header())\n\trwp.under.WriteHeader(statusCode)\n}", "func OptHeader(headers http.Header) Option {\n\treturn RequestOption(webutil.OptHeader(headers))\n}" ]
[ "0.7428583", "0.73180294", "0.6969307", "0.6939664", "0.68874514", "0.68320334", "0.68258685", "0.68127483", "0.6698579", "0.66148335", "0.6614227", "0.65428376", "0.62228173", "0.61663586", "0.6070402", "0.5893018", "0.572726", "0.5709158", "0.5704184", "0.56725305", "0.5646608", "0.5645388", "0.5574246", "0.5555903", "0.54837346", "0.542251", "0.5371328", "0.5345336", "0.53015137", "0.52920705", "0.52531844", "0.52531844", "0.5229696", "0.5226522", "0.5220001", "0.52038217", "0.5201821", "0.5197332", "0.5156163", "0.5150092", "0.5130715", "0.51217115", "0.5114498", "0.5106032", "0.5099308", "0.5089942", "0.50800717", "0.5078758", "0.5067956", "0.5047841", "0.5040618", "0.5032649", "0.5026464", "0.50258803", "0.5010079", "0.5007416", "0.5007155", "0.50043637", "0.499278", "0.4988924", "0.4987665", "0.49784976", "0.4977679", "0.49716467", "0.49663723", "0.49580267", "0.49558127", "0.4941594", "0.49379838", "0.49378836", "0.49272296", "0.49200714", "0.4915111", "0.49147546", "0.49099168", "0.49092948", "0.49052823", "0.49048206", "0.48995703", "0.48898464", "0.48847663", "0.48797214", "0.48782638", "0.4877883", "0.48679817", "0.4863784", "0.48572177", "0.48525876", "0.4851444", "0.48451784", "0.48417372", "0.48406094", "0.48389497", "0.48356885", "0.48334682", "0.48292223", "0.48230276", "0.48180714", "0.48122036", "0.4802366" ]
0.83915895
0
RemoveIfUnused deletes the entry for the specified queue in this registry if its reference count is zero. Return whether the entry has been removed, and any error that occurred.
RemoveIfUnused удаляет запись для указанной очереди в этом реестре, если счетчик ссылок равен нулю. Возвращает, была ли запись удалена, и любую произошедшую ошибку.
func (registry *Registry) RemoveIfUnused(queue string) (bool, error) { registry.mutex.Lock() defer registry.mutex.Unlock() entry, found := registry.queues[queue] if !found { // "Not found" is unexpected, since I expect only the clerk itself // would be trying to remove its queue (so why, then, is it already // missing?). return true, fmt.Errorf("no entry for queue %q", queue) } if entry.RefCount > 0 { // Someone is using the queue. Return `false`, meaning "not removed." return false, nil } // Nobody is using the queue. Remove it. delete(registry.queues, queue) // Return `true`, meaning "removed." return true, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeleteTimerQueue(timerQueue HANDLE) bool {\n\tret1 := syscall3(deleteTimerQueue, 1,\n\t\tuintptr(timerQueue),\n\t\t0,\n\t\t0)\n\treturn ret1 != 0\n}", "func (q *Queue) MaybeRemoveMissing(names []string) int {\n\tq.mu.Lock()\n\tsameSize := len(q.items) == len(names)\n\tq.mu.Unlock()\n\n\t// heuristically skip expensive work\n\tif sameSize {\n\t\treturn -1\n\t}\n\n\tset := make(map[string]struct{}, len(names))\n\tfor _, name := range names {\n\t\tset[name] = struct{}{}\n\t}\n\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tcount := 0\n\tfor name, item := range q.items {\n\t\tif _, ok := set[name]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif item.heapIdx >= 0 {\n\t\t\theap.Remove(&q.pq, item.heapIdx)\n\t\t}\n\t\titem.setIndexState(\"\")\n\t\tdelete(q.items, name)\n\t\tcount++\n\t}\n\n\tmetricQueueLen.Set(float64(len(q.pq)))\n\tmetricQueueCap.Set(float64(len(q.items)))\n\n\treturn count\n}", "func (t *TopicCache) IsQueueEmpty(projectName, serviceName string) bool {\n\tt.RLock()\n\tdefer t.RUnlock()\n\n\t_, ok := t.inQueue[projectName+serviceName]\n\n\treturn !ok\n}", "func (q *LinkQueue) DeQueue() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.IsEmpty() {\n\t\treturn false\n\t}\n\n\tq.head = q.head.Next\n\tq.size--\n\treturn true\n}", "func TestRemoveFromEmptyQueue(t *testing.T) {\n\ttarget := teaser.New()\n\tdeleted := target.Delete(\"6e0c9774-2674-4c6f-906e-6ccaebad3772\")\n\tif deleted {\n\t\tt.Fatal(\"deleting from an empty queue should not be possbile!\")\n\t}\n}", "func (eq *ExpiryQueue) Remove(orderId int64) bool {\n\tindex, ok := eq.hp.mapIndexByOrderId[orderId]\n\tif !ok {\n\t\treturn false\n\t}\n\theap.Remove(eq.hp, index)\n\treturn true\n}", "func (mcq *MyCircularQueue) DeQueue() bool {\n\tif mcq.length == 0 {\n\t\treturn false\n\t}\n\tshouldDeleteNode := mcq.dummyHead.Next\n\tdeleteNodeInList(shouldDeleteNode)\n\tmcq.length--\n\treturn true\n}", "func (q *SliceQueue) DeQueue() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.IsEmpty() {\n\t\treturn false\n\t}\n\n\tq.Data = q.Data[1:]\n\treturn true\n}", "func (q *UniqueQueue) Dequeue() (string, interface{}, bool) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tif q.head == q.tail {\n\t\treturn \"\", nil, false\n\t}\n\n\tentry := q.queue[q.head]\n\tq.head = q.inc(q.head)\n\tdelete(q.queuedSet, entry.key)\n\treturn entry.key, entry.val, true\n}", "func (q *Queue) Remove() (interface{}, bool) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tif q.queueLen == 0 {\n\t\treturn nil, false\n\t}\n\treturn q.popFront(), true\n}", "func (sb *shardBuffer) remove(toRemove *entry) {\n\tsb.mu.Lock()\n\tdefer sb.mu.Unlock()\n\n\tif sb.queue == nil {\n\t\t// Queue is cleared because we're already in the DRAIN phase.\n\t\treturn\n\t}\n\n\t// If entry is still in the queue, delete it and cancel it internally.\n\tfor i, e := range sb.queue {\n\t\tif e == toRemove {\n\t\t\t// Delete entry at index \"i\" from slice.\n\t\t\tsb.queue = append(sb.queue[:i], sb.queue[i+1:]...)\n\n\t\t\t// Cancel the entry's \"bufferCtx\".\n\t\t\t// The usual drain or eviction code would unblock the request and then\n\t\t\t// wait for the \"bufferCtx\" to be done.\n\t\t\t// But this code path is different because it's going to return an error\n\t\t\t// to the request and not the \"e.bufferCancel\" function i.e. the request\n\t\t\t// cannot cancel the \"bufferCtx\" itself.\n\t\t\t// Therefore, we call \"e.bufferCancel\". This also avoids that the\n\t\t\t// context's Go routine could leak.\n\t\t\te.bufferCancel()\n\t\t\t// Release the buffer slot and close the \"e.done\" channel.\n\t\t\t// By closing \"e.done\", we finish it explicitly and timeoutThread will\n\t\t\t// find out about it as well.\n\t\t\tsb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */)\n\n\t\t\t// Track it as \"ContextDone\" eviction.\n\t\t\tstatsKeyWithReason := append(sb.statsKey, string(evictedContextDone))\n\t\t\trequestsEvicted.Add(statsKeyWithReason, 1)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Entry was already removed. Keep the queue as it is.\n}", "func (q *Queue) DeQueue() (interface{}, bool) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.closed && q.items.Len() == 0 {\n\t\treturn nil, false\n\t}\n\n\tfor !q.closed && q.items.Len() == 0 {\n\t\tq.cond.Wait()\n\t}\n\n\tif q.closed && q.items.Len() == 0 {\n\t\treturn nil, false\n\t}\n\n\thi := heap.Pop(&q.items).(*heapItem)\n\titem := hi.value\n\tq.vt += hi.size * q.inv_wsum\n\thi.fi.size -= hi.size\n\tq.size -= hi.size\n\tif hi.fi.size == 0 && hi.fi.pendSize == 0 {\n\t\t// The flow is empty (i.e. inactive), delete it\n\t\tdelete(q.flows, hi.key)\n\t\tq.wsum += uint64(hi.fi.weight)\n\t\tq.inv_wsum = scaledOne / uint64(q.wsum)\n\t\tputFlowInfo(hi.fi)\n\t\tputHeapItem(hi)\n\t} else {\n\t\thi.fi.cond.Signal()\n\t\tputHeapItem(hi)\n\t}\n\n\tif !q.closed {\n\t\t// While there is room in the queue move items from the overflow to the main heap.\n\t\tfor q.next_ohi != nil && q.size+q.next_ohi.hi.size <= q.maxQueueSize {\n\t\t\tq.size += q.next_ohi.hi.size\n\t\t\theap.Push(&q.items, q.next_ohi.hi)\n\t\t\tq.next_ohi.wg.Done()\n\t\t\tif q.overflow.Len() > 0 {\n\t\t\t\tq.next_ohi = heap.Pop(&q.overflow).(*overflowHeapItem)\n\t\t\t} else {\n\t\t\t\tq.next_ohi = nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn item, true\n}", "func (q *dStarLiteQueue) remove(n *dStarLiteNode) {\n\theap.Remove(q, n.idx)\n\tn.key = badKey\n\tn.idx = -1\n}", "func (s *SliceQueue) Dequeue() (val string, ok bool) {\n\tif s.Len() == 0 {\n\t\treturn \"\", false\n\t}\n\n\tval = s.elements[0] // Obtain the first inserted element.\n\ts.elements = s.elements[1:] // Remove the first inserted element.\n\treturn val, true\n}", "func (c *caches) remove(qname string) (ok bool) {\n\tc.Lock()\n\tfor e := c.lru.Front(); e != nil; e = e.Next() {\n\t\tanswer := e.Value.(*answer)\n\t\tif answer.qname != qname {\n\t\t\tcontinue\n\t\t}\n\n\t\tc.lru.Remove(e)\n\t\tdelete(c.v, qname)\n\t\tanswer.clear()\n\t\tok = true\n\t\tbreak\n\t}\n\tif !ok {\n\t\t_, ok = c.v[qname]\n\t\tif ok {\n\t\t\t// If the qname is not found in non-local caches, it\n\t\t\t// may exist as local answer.\n\t\t\tdelete(c.v, qname)\n\t\t}\n\t}\n\tc.Unlock()\n\treturn ok\n}", "func (block *SimpleQueueBlock) clearOldStorage(ctx context.Context, q *SimpleQueue) (notNeed bool, err *mft.Error) {\n\n\tif !block.mxFileSave.TryLock(ctx) {\n\t\treturn false, GenerateError(10017000)\n\t}\n\tdefer block.mxFileSave.Unlock()\n\n\tif len(block.RemoveMarks) == 0 {\n\t\treturn true, nil\n\t}\n\n\tfileName := block.blockFileName()\n\n\tfor _, stName := range block.RemoveMarks {\n\t\tif block.Mark == stName {\n\t\t\tcontinue\n\t\t}\n\t\tst, err := q.getStorageLock(ctx, stName)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\terr = storage.DeleteIfExists(ctx, st, fileName)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tif !q.mx.TryLock(ctx) {\n\t\treturn false, GenerateError(10017001)\n\t}\n\n\tblock.RemoveMarks = make([]string, 0)\n\n\tq.ChangesRv = q.IDGenerator.RvGetPart()\n\n\tq.mx.Unlock()\n\n\treturn false, nil\n}", "func (c *CircularBuffer[T]) Dequeue() (T, bool) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tvar msg T\n\t// record that we have accessed the buffer\n\tc.lastAccess = time.Now()\n\t// if our head and tail are equal there is nothing in our buffer to return\n\tif c.head == c.tail {\n\t\treturn msg, false\n\t}\n\n\tmsg = c.buffer[c.tail]\n\tc.tail = (c.tail + 1) % BUFLEN\n\treturn msg, true\n}", "func (this *MyCircularQueue) DeQueue() bool {\n\tif this.Count == 0 {\n\t\treturn false\n\t}\n\tthis.Count--\n\tthis.Head++\n\tif this.Head == len(this.Queue) {\n\t\tthis.Head = 0\n\t}\n\treturn true\n}", "func (b *backend) removeUnsafe(id *entroq.TaskID) {\n\tif !b.existsIDVersionUnsafe(id) {\n\t\tlog.Panicf(\"Item not found for removal: %v\", id)\n\t}\n\titem := b.byID[id.ID]\n\tif item.task.Version != id.Version {\n\t\tlog.Panicf(\"Item removal version mismatch: wanted %q, got %q\", id, item.task.IDVersion())\n\t}\n\th, ok := b.heaps[item.task.Queue]\n\tif !ok {\n\t\tlog.Panicf(\"Queues not in sync; found item to remove in queues but not index: %v\", id)\n\t}\n\n\tdelete(b.byID, id.ID)\n\theap.Remove(h, item.idx)\n\tif h.Len() == 0 {\n\t\tdelete(b.heaps, item.task.Queue)\n\t}\n}", "func (lru *LRUMap) removeFromQueue(node *keyValNode) {\n\tif node.prev != nil {\n\t\tnode.prev.next = node.next\n\t} else {\n\t\tlru.rear = node.next\n\t}\n\n\tif node.next != nil {\n\t\tnode.next.prev = node.prev\n\t} else {\n\t\tlru.front = node.prev\n\t}\n}", "func (q *Queue) Remove(v interface{}) bool {\r\n\tq.mu.Lock()\r\n\tdefer q.mu.Unlock()\r\n\r\n\tel, ok := q.m[v]\r\n\tif !ok {\r\n\t\treturn false\r\n\t}\r\n\r\n\tfirst := q.first\r\n\tdelete(q.m, v)\r\n\tq.remove(el)\r\n\r\n\t// If the element was first, we need to start a new timer\r\n\tif first == el && q.first != nil {\r\n\t\tgo q.timer(q.first, q.first.time)\r\n\t}\r\n\treturn true\r\n}", "func (gc *GceCache) UnregisterMig(toBeRemoved Mig) bool {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\t_, found := gc.migs[toBeRemoved.GceRef()]\n\tif found {\n\t\tklog.V(1).Infof(\"Unregistered Mig %s\", toBeRemoved.GceRef().String())\n\t\tdelete(gc.migs, toBeRemoved.GceRef())\n\t\tgc.removeMigInstances(toBeRemoved.GceRef())\n\t\treturn true\n\t}\n\treturn false\n}", "func (q *Queue) DeQueue() error {\r\n\tif len(q.QueueList) > 0 {\r\n\t\tq.QueueList = q.QueueList[1:]\r\n\t\treturn nil\r\n\t}\r\n\treturn errors.New(\"Queue is empty\")\r\n}", "func (sl *LockFreeSkipList) Remove(value interface{}) bool {\n\tvar prevs [maxLevel]*node\n\tvar nexts [maxLevel]*node\n\tif !sl.find(value, &prevs, &nexts) {\n\t\treturn false\n\t}\n\tremoveNode := nexts[0]\n\tfor level := removeNode.level - 1; level > 0; level-- {\n\t\tnext := removeNode.loadNext(level)\n\t\tfor !isMarked(next) {\n\t\t\t// Make sure that all but the bottom next are marked from top to bottom.\n\t\t\tremoveNode.casNext(level, next, getMarked(next))\n\t\t\tnext = removeNode.loadNext(level)\n\t\t}\n\t}\n\tfor next := removeNode.loadNext(0); true; next = removeNode.loadNext(0) {\n\t\tif isMarked(next) {\n\t\t\t// Other thread already maked the next, so this thread delete failed.\n\t\t\treturn false\n\t\t}\n\t\tif removeNode.casNext(0, next, getMarked(next)) {\n\t\t\t// This thread marked the bottom next, delete successfully.\n\t\t\tbreak\n\t\t}\n\t}\n\tatomic.AddInt32(&sl.size, -1)\n\treturn true\n}", "func (gc *GceCache) UnregisterMig(toBeRemoved Mig) bool {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\t_, found := gc.migs[toBeRemoved.GceRef()]\n\tif found {\n\t\tklog.V(1).Infof(\"Unregistered Mig %s\", toBeRemoved.GceRef().String())\n\t\tdelete(gc.migs, toBeRemoved.GceRef())\n\t\tgc.removeInstancesForMigs(toBeRemoved.GceRef())\n\t\treturn true\n\t}\n\treturn false\n}", "func (q *SignalQueue) Dequeue() int {\n\tq.Cond.L.Lock()\n\t// Wait for not empty\n\tfor len(q.Queue) == 0 {\n\t\tq.Cond.Wait()\n\t}\n\tretval := q.Queue[0]\n\tq.Queue[0] = 0\n\tq.Queue = q.Queue[1:]\n\tq.Cond.L.Unlock()\n\n\treturn retval\n}", "func (queues *requestQueueImpl) CleanupQueue(gwId string) chan *protos.SyncRPCRequest {\n\tqueues.Lock()\n\tdefer queues.Unlock()\n\tif queue, ok := queues.reqQueueByGwId[gwId]; ok {\n\t\t// sends on a closed queue will panic, but no one will send onto this queue,\n\t\t// because all sends are through enqueue.\n\t\tclose(queue)\n\t\tdelete(queues.reqQueueByGwId, gwId)\n\t\t// the broker will cleanup requests in the queue\n\t\treturn queue\n\t} else {\n\t\tglog.Warningf(\"HWID %v: no request queue found to clean up\", gwId)\n\t}\n\treturn nil\n}", "func (i *invocation) removeIfEmpty() {\n\tif i.queuedOperations.Len() == 0 && i.executingWorkersCount == 0 && i.idleWorkersCount == 0 {\n\t\tscq := i.sizeClassQueue\n\t\tif scq.invocations[i.invocationKey] != i {\n\t\t\tpanic(\"Attempted to remove an invocation that was already removed\")\n\t\t}\n\t\tdelete(scq.invocations, i.invocationKey)\n\t}\n}", "func (q *Queue) TryDequeue() (ptr unsafe.Pointer, dequeued bool) {\n\tvar c *cell\n\tpos := atomic.LoadUintptr(&q.deqPos)\n\tfor {\n\t\tc = &q.cells[pos&q.mask]\n\t\tseq := atomic.LoadUintptr(&c.seq)\n\t\tcmp := int(seq - (pos + 1))\n\t\tif cmp == 0 {\n\t\t\tvar swapped bool\n\t\t\tif pos, swapped = primitive.CompareAndSwapUintptr(&q.deqPos, pos, pos+1); swapped {\n\t\t\t\tdequeued = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif cmp < 0 {\n\t\t\treturn\n\t\t}\n\t\tpos = atomic.LoadUintptr(&q.deqPos)\n\t}\n\tptr = c.ptr\n\tc.ptr = primitive.Null\n\tatomic.StoreUintptr(&c.seq, pos+q.mask)\n\treturn\n}", "func (q *LockFree) Dequeue() memory.Bytes {\nretry:\n\tfirst := atomic.LoadUintptr(&q.head)\n\tfirstV := (*lockFreeNode)(unsafe.Pointer(first))\n\tlast := atomic.LoadUintptr(&q.tail)\n\tnext := atomic.LoadUintptr(&firstV.next)\n\t// Are first, tail, and next consistent?\n\tif first == atomic.LoadUintptr(&q.head) {\n\t\t// Is queue empty or tail falling behind?\n\t\tif first == last {\n\t\t\t// Is queue empty?\n\t\t\tif next == 0 {\n\t\t\t\t//println(\"empty\")\n\t\t\t\treturn memory.Bytes{}\n\t\t\t}\n\t\t\t//println(\"first == tail\")\n\t\t\tatomic.CompareAndSwapUintptr(&q.tail, last, next) // tail is falling behind, try to advance it.\n\t\t} else {\n\t\t\t// Read value before CAS, otherwise another dequeue might free the next node.\n\t\t\ttask := (*lockFreeNode)(unsafe.Pointer(next)).value\n\t\t\tif atomic.CompareAndSwapUintptr(&q.head, first, next) { // dequeue is done, return value.\n\t\t\t\tatomic.AddInt32(&q.length, -1)\n\t\t\t\tmemory.Free(memory.Pointer(first))\n\t\t\t\treturn task\n\t\t\t}\n\t\t}\n\t}\n\tgoto retry\n}", "func (q *Queue) RemoveResource(resUUID string) error {\n\t// Check for the resource with given UUID\n\t_, ok := q.pool[resUUID]\n\tif !ok {\n\t\treturn errors.New(\"Given Resource UUID does not exist.\")\n\t}\n\n\t// Lock the queue\n\tq.Lock()\n\tdefer q.Unlock()\n\n\t// Loop through any jobs assigned to the resource and quit them if they are not completed\n\tfor i, v := range q.stack {\n\t\tif v.ResAssigned == resUUID {\n\t\t\t// Check status\n\t\t\tif v.Status == common.STATUS_RUNNING || v.Status == common.STATUS_PAUSED {\n\t\t\t\t// Quit the task\n\t\t\t\tquitTask := common.RPCCall{Job: v}\n\n\t\t\t\terr := q.pool[resUUID].Client.Call(\"Queue.TaskQuit\", quitTask, &q.stack[i])\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Close the connection to the client\n\tq.pool[resUUID].Client.Close()\n\n\t// Remove information that might affect additional resource adding\n\tres, _ := q.pool[resUUID]\n\tres.Address = \"closed\"\n\tres.Status = common.STATUS_QUIT\n\tfor key := range res.Tools {\n\t\tdelete(res.Tools, key)\n\t}\n\tq.pool[resUUID] = res\n\tfor i, _ := range q.pool[resUUID].Hardware {\n\t\tq.pool[resUUID].Hardware[i] = false\n\t}\n\n\treturn nil\n}", "func (m *MemoryQueueStorage) Dequeue(queue string) (*frame.Frame, error) {\n\tl, ok := m.lists[queue]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\telement := l.Front()\n\tif element == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn l.Remove(element).(*frame.Frame), nil\n}", "func CancelTimerQueueTimer(timerQueue HANDLE, timer HANDLE) bool {\n\tret1 := syscall3(cancelTimerQueueTimer, 2,\n\t\tuintptr(timerQueue),\n\t\tuintptr(timer),\n\t\t0)\n\treturn ret1 != 0\n}", "func (s *ConcurrentSet) Remove(e interface{}) bool {\n\t_, exists := s.hash.Load(e)\n\ts.hash.Delete(e)\n\tif exists {\n\t\tatomic.AddUint32(&s.size, ^uint32(0))\n\t}\n\treturn exists\n}", "func (k *Kuzzle) cleanQueue() {\n\tnow := time.Now()\n\tnow = now.Add(-k.queueTTL * time.Millisecond)\n\n\t// Clean queue of timed out query\n\tif k.queueTTL > 0 {\n\t\tvar query *types.QueryObject\n\t\tfor _, query = range k.offlineQueue {\n\t\t\tif query.Timestamp.Before(now) {\n\t\t\t\tk.offlineQueue = k.offlineQueue[1:]\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif k.queueMaxSize > 0 && len(k.offlineQueue) > k.queueMaxSize {\n\t\tfor len(k.offlineQueue) > k.queueMaxSize {\n\t\t\teventListener := k.eventListeners[event.OfflineQueuePop]\n\t\t\tfor c := range eventListener {\n\t\t\t\tjson, _ := json.Marshal(k.offlineQueue[0])\n\t\t\t\tc <- json\n\t\t\t}\n\n\t\t\teventListener = k.eventListenersOnce[event.OfflineQueuePop]\n\t\t\tfor c := range eventListener {\n\t\t\t\tjson, _ := json.Marshal(k.offlineQueue[0])\n\t\t\t\tc <- json\n\t\t\t\tdelete(k.eventListenersOnce[event.OfflineQueuePop], c)\n\t\t\t}\n\n\t\t\tk.offlineQueue = k.offlineQueue[1:]\n\t\t}\n\t}\n}", "func (q *Queue) Drop() {\n\tif q.isShared {\n\t\treturn\n\t}\n\tq.Close()\n\tos.RemoveAll(q.Path())\n}", "func Unregister(qi inomap.QIno) {\n\tt.Lock()\n\tdefer t.Unlock()\n\n\te := t.entries[qi]\n\te.refCount--\n\tif e.refCount == 0 {\n\t\tdelete(t.entries, qi)\n\t}\n}", "func (q *CircularQueue) DeQueue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn false\n\t}\n\tval := q.q[q.head]\n\tq.head = (q.head + 1) % q.capacity\n\treturn val\n}", "func (gcq *gcQueue) shouldQueue(\n\tctx context.Context, now hlc.ClockTimestamp, repl *Replica, _ *config.SystemConfig,\n) (bool, float64) {\n\n\t// Consult the protected timestamp state to determine whether we can GC and\n\t// the timestamp which can be used to calculate the score.\n\t_, zone := repl.DescAndZone()\n\tcanGC, _, gcTimestamp, oldThreshold, newThreshold := repl.checkProtectedTimestampsForGC(ctx, *zone.GC)\n\tif !canGC {\n\t\treturn false, 0\n\t}\n\t// If performing a GC will not advance the GC threshold, there's no reason\n\t// to GC again.\n\tif newThreshold.Equal(oldThreshold) {\n\t\treturn false, 0\n\t}\n\tr := makeGCQueueScore(ctx, repl, gcTimestamp, *zone.GC)\n\treturn r.ShouldQueue, r.FinalScore\n}", "func (f *fileScorer) trimQueue() {\n\tfor {\n\t\te := f.queue.Back()\n\t\tif e == nil {\n\t\t\treturn\n\t\t}\n\t\tv := e.Value.(queuedFile)\n\t\tif f.queuedBytes-v.size < f.saveBytes {\n\t\t\treturn\n\t\t}\n\t\tf.queue.Remove(e)\n\t\tf.queuedBytes -= v.size\n\t}\n}", "func (scq *sizeClassQueue) remove(bq *InMemoryBuildQueue) {\n\t// Cancel all queued operations.\n\tfor scq.queuedInvocations.Len() > 0 {\n\t\ti := scq.queuedInvocations[scq.queuedInvocations.Len()-1]\n\t\ti.queuedOperations[i.queuedOperations.Len()-1].task.complete(bq, &remoteexecution.ExecuteResponse{\n\t\t\tStatus: status.New(codes.Unavailable, \"Workers for this instance name, platform and size class disappeared while task was queued\").Proto(),\n\t\t}, false)\n\t}\n\n\tdelete(bq.sizeClassQueues, scq.getKey())\n\tpq := scq.platformQueue\n\ti := 0\n\tfor pq.sizeClassQueues[i] != scq {\n\t\ti++\n\t}\n\tpq.sizeClasses = append(pq.sizeClasses[:i], pq.sizeClasses[i+1:]...)\n\tpq.sizeClassQueues = append(pq.sizeClassQueues[:i], pq.sizeClassQueues[i+1:]...)\n\n\tif len(pq.sizeClasses) == 0 {\n\t\t// No size classes remain for this platform queue,\n\t\t// meaning that we can remove it. We must make sure the\n\t\t// list of platform queues remains contiguous.\n\t\tindex := bq.platformQueuesTrie.GetExact(pq.platformKey)\n\t\tnewLength := len(bq.platformQueues) - 1\n\t\tlastPQ := bq.platformQueues[newLength]\n\t\tbq.platformQueues[index] = lastPQ\n\t\tbq.platformQueues = bq.platformQueues[:newLength]\n\t\tbq.platformQueuesTrie.Set(lastPQ.platformKey, index)\n\t\tbq.platformQueuesTrie.Remove(pq.platformKey)\n\t}\n}", "func (this *MyCircularQueue) DeQueue() bool {\n\tif this.IsEmpty() {\n\t\treturn false\n\t}\n\n\tif this.Head == this.Tail {\n\t\tthis.CircularQueue[this.Head] = -1\n\t\treturn true\n\t}\n\n\t// 余数除法,指针向后移一位\n\tthis.CircularQueue[this.Head] = -1\n\tthis.Head = (this.Head + 1) % len(this.CircularQueue)\n\t/*\n\t\tthis.CircularQueue[this.Head] = -1\n\t\tthis.Head = this.Head + 1\n\t\tif this.Head > len(this.CircularQueue) - 1 {\n\t\t\tthis.Head = 0\n\t\t}*/\n\treturn true\n}", "func (m *MRUQueue) Empty() bool {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\treturn m.store.Len() == 0\n}", "func (c *LRU) RemoveUnused() (key string, value interface{}, ok bool) {\n\tif e := c.l.Back(); e != nil {\n\t\tc.l.Remove(e)\n\t\tent := e.Value.(*lruEntry)\n\t\tdelete(c.m, ent.k)\n\t\treturn ent.k, ent.v, true\n\t}\n\treturn\n}", "func (this *MyCircularQueue) DeQueue() bool {\n\tif this.IsEmpty() {\n\t\treturn false\n\t}\n\t//\n\tthis.front = (this.front + 1) % this.size\n\t//\n\treturn true\n}", "func (c *changeCache) CleanSkippedSequenceQueue(ctx context.Context) error {\n\n\toldSkippedSequences := c.GetSkippedSequencesOlderThanMaxWait()\n\tif len(oldSkippedSequences) == 0 {\n\t\treturn nil\n\t}\n\n\tbase.InfofCtx(ctx, base.KeyCache, \"Starting CleanSkippedSequenceQueue, found %d skipped sequences older than max wait for database %s\", len(oldSkippedSequences), base.MD(c.db.Name))\n\n\t// Purge sequences not found from the skipped sequence queue\n\tnumRemoved := c.RemoveSkippedSequences(ctx, oldSkippedSequences)\n\tc.db.DbStats.Cache().AbandonedSeqs.Add(numRemoved)\n\n\tbase.InfofCtx(ctx, base.KeyCache, \"CleanSkippedSequenceQueue complete. Not Found:%d for database %s.\", len(oldSkippedSequences), base.MD(c.db.Name))\n\treturn nil\n}", "func (q *Queue) TryEnqueue(ptr unsafe.Pointer) (enqueued bool) {\n\tc := &q.cells[q.enqPos&q.mask]\n\tseq := atomic.LoadUintptr(&c.seq)\n\tif seq < q.enqPos {\n\t\treturn\n\t}\n\tq.enqPos++\n\tc.ptr = ptr\n\tatomic.StoreUintptr(&c.seq, q.enqPos)\n\treturn true\n}", "func (q *PriorityQueue) Remove() interface{} {\n\tif q.count <= 0 {\n\t\tpanic(\"queue: Remove() called on empty queue\")\n\t}\n\tret := q.buf[q.head]\n\tq.buf[q.head] = nil\n\t// bitwise modulus\n\tq.head = (q.head + 1) & (len(q.buf) - 1)\n\tq.count--\n\t// Resize down if buffer 1/4 full.\n\tif len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) {\n\t\tq.resize()\n\t}\n\treturn ret\n}", "func (s *SyncStorage) RemoveIf(ns string, key string, data interface{}) (bool, error) {\n\tstatus, err := s.getDbBackend(ns).DelIE(getNsPrefix(ns)+key, data)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn status, nil\n}", "func (d *deferredConfirmations) remove(tag uint64) {\n\td.m.Lock()\n\tdefer d.m.Unlock()\n\tdc, found := d.confirmations[tag]\n\tif !found {\n\t\treturn\n\t}\n\tclose(dc.done)\n\tdelete(d.confirmations, tag)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) HasExitQueue(opts *bind.CallOpts, vaultId *big.Int, token common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"hasExitQueue\", vaultId, token)\n\treturn *ret0, err\n}", "func (h *sendPacketHeap) Remove(packetID packet.PacketID) bool {\n\tlen := len(*h)\n\tidx := 0\n\tfor idx < len {\n\t\tpid := (*h)[idx].pkt.Seq\n\t\tif pid.Seq == packetID.Seq {\n\t\t\theap.Remove(h, idx)\n\t\t\treturn true\n\t\t} else if pid.Seq > packetID.Seq {\n\t\t\tidx = idx * 2\n\t\t} else {\n\t\t\tidx = idx*2 + 1\n\t\t}\n\t}\n\treturn false\n}", "func (q *Queue) Dequeue() interface{} {\n\tvar first, last, firstnext *queueitem\n\tfor {\n\t\tfirst = loadqitem(&q.head)\n\t\tlast = loadqitem(&q.tail)\n\t\tfirstnext = loadqitem(&first.next)\n\t\tif first == loadqitem(&q.head) { // are head, tail and next consistent?\n\t\t\tif first == last { // is queue empty?\n\t\t\t\tif firstnext == nil { // queue is empty, couldn't dequeue\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tcasqitem(&q.tail, last, firstnext) // tail is falling behind, try to advance it\n\t\t\t} else { // read value before cas, otherwise another dequeue might free the next node\n\t\t\t\tv := firstnext.v\n\t\t\t\tif casqitem(&q.head, first, firstnext) { // try to swing head to the next node\n\t\t\t\t\tatomic.AddUint64(&q.len, ^uint64(0))\n\t\t\t\t\treturn v // queue was not empty and dequeue finished.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (this *MyQueue) Empty() bool {\n return len(this.q) == 0\n}", "func (m *etcdMinion) checkQueue() error {\n\topts := &etcdclient.GetOptions{\n\t\tRecursive: true,\n\t\tSort: true,\n\t}\n\n\t// Get backlog tasks if any\n\t// If the directory key in etcd is missing that is okay, since\n\t// it means there are no pending tasks for processing\n\tresp, err := m.kapi.Get(context.Background(), m.queueDir, opts)\n\tif err != nil {\n\t\tif eerr, ok := err.(etcdclient.Error); !ok || eerr.Code == etcdclient.ErrorCodeKeyNotFound {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbacklog := resp.Node.Nodes\n\tif len(backlog) == 0 {\n\t\t// No backlog tasks found\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"Found %d pending tasks in queue\", len(backlog))\n\tfor _, node := range backlog {\n\t\tt, err := EtcdUnmarshalTask(node)\n\t\tm.kapi.Delete(context.Background(), node.Key, nil)\n\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tm.taskQueue <- t\n\t}\n\n\treturn nil\n}", "func (q *OperationQueue) Remove(op *SignedOperation) {\n\tif op == nil {\n\t\treturn\n\t}\n\tq.set.Remove(op)\n}", "func (s *API) UntagQueue(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"UntagQueue\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func (s *API) PurgeQueue(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"PurgeQueue\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func ClearQueue(queueLetter ...string) error {\n\tif len(queueLetter) == 0 {\n\t\tqueueLetter = []string{\"a\"}\n\t}\n\n\tatqCmd := exec.Command(\"atq\", \"-q\", fmt.Sprintf(\"%c\", queueLetter[0][0]))\n\tatqStdout, err := atqCmd.Output()\n\tif err != nil {\n\t\treturn errors.New(\"could not get job IDs\")\n\t}\n\n\tjobIDs := regexp.MustCompile(`(?m:^\\d+)`).FindAllStringSubmatch(string(atqStdout), -1)\n\n\tfor _, idToken := range jobIDs {\n\t\tjobID, _ := strconv.Atoi(idToken[0])\n\n\t\tif err := RemoveJob(jobID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (q *dStarLiteNode) inQueue() bool {\n\treturn q.idx >= 0\n}", "func (q LinkedListQueue) Dequeue() (data interface{}, err error) {\n\tif q.list.Len() == 0 {\n\t\treturn data, errors.New(\"The queue is empty\")\n\t}\n\n\tdata = q.list.Remove(q.list.Front())\n\n\treturn data, nil\n}", "func (q *Queue) Disposed() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn q.disposed\n}", "func (s *MyStack) Empty() bool {\n return len(s.queue1) == 0\n}", "func (f *ccFixture) popQueue() {\n\tf.T().Helper()\n\n\tdone := make(chan error)\n\tgo func() {\n\t\titem, _ := f.q.Get()\n\t\t_, err := f.tfr.Reconcile(f.ctx, item.(reconcile.Request))\n\t\tf.q.Done(item)\n\t\tdone <- err\n\t}()\n\n\tselect {\n\tcase <-time.After(time.Second):\n\t\tf.T().Fatal(\"timeout waiting for workqueue\")\n\tcase err := <-done:\n\t\tassert.NoError(f.T(), err)\n\t}\n}", "func (f *FakeWatchEventQ) Dequeue(ctx context.Context,\n\tfromver uint64, ignoreBulk bool, cb apiintf.EventHandlerFn, cleanupfn func(), opts *api.ListWatchOptions) {\n\tdefer f.Unlock()\n\tf.Lock()\n\tclose(f.DqCh)\n\tf.Dequeues++\n\tif f.DQFn != nil {\n\t\tf.DQFn(ctx, fromver, cb, cleanupfn)\n\t}\n}", "func (ls *ListStack) Remove(item adts.ContainerElement) bool {\n\tif ls.threadSafe {\n\t\tls.lock.Lock()\n\t\tdefer ls.lock.Unlock()\n\t\treturn ls.removeHelper(item)\n\t}\n\n\treturn ls.removeHelper(item)\n}", "func (q *queue) Dequeue() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not remove from empty queue\")\n\t}\n\n\tdata := q.items[q.head].Data\n\tq.items[q.head] = item{}\n\tq.head = (q.head + 1) % q.capacity\n\tq.len--\n\n\treturn data, nil\n}", "func (q *Queue) Dequeue() (string, error) {\n\t// TODO: fewer round trips by fetching more than one key\n\tresp, err := q.client.Get(q.ctx, q.keyPrefix, v3.WithFirstRev()...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkv, err := claimFirstKey(q.client, resp.Kvs)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if kv != nil {\n\t\treturn string(kv.Value), nil\n\t} else if resp.More {\n\t\t// missed some items, retry to read in more\n\t\treturn q.Dequeue()\n\t}\n\n\t// nothing yet; wait on elements\n\tev, err := WaitPrefixEvents(\n\t\tq.client,\n\t\tq.keyPrefix,\n\t\tresp.Header.Revision,\n\t\t[]mvccpb.Event_EventType{mvccpb.PUT})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tok, err := deleteRevKey(q.client, string(ev.Kv.Key), ev.Kv.ModRevision)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if !ok {\n\t\treturn q.Dequeue()\n\t}\n\treturn string(ev.Kv.Value), err\n}", "func (sq *SegmentQueue) Remove(seg *Segment) {\n\tsq.mtx.Lock()\n\tdefer sq.mtx.Unlock()\n\n\tfor i, segi := range sq.pq {\n\t\tif seg == segi {\n\t\t\theap.Remove(&sq.pq, i)\n\t\t\tbreak\n\t\t}\n\t}\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 groomQueues(queues *Queues) (err kv.Error) {\n\tfor qName, qDetails := range *queues {\n\t\t// If we have enough runners drop the queue as it needs nothing done to it\n\t\tif len(qDetails.NodeGroup) == 0 || qDetails.Running >= qDetails.Ready+qDetails.NotVisible {\n\t\t\tif logger.IsTrace() {\n\t\t\t\tlogger.Trace(\"queue already handled\", \"queue\", qName, \"stack\", stack.Trace().TrimRuntime())\n\t\t\t}\n\t\t\tdelete(*queues, qName)\n\t\t}\n\t}\n\treturn nil\n}", "func (b *CompactableBuffer) Remove(address *EntryAddress) error {\n\taddress.LockForWrite()\n\tdefer address.UnlockWrite()\n\tresult := b.removeWithoutLock(address)\n\treturn result\n}", "func (q *Queue) Dequeue() interface{} {\n\treturn q.Elements.Remove(q.Elements.Front())\n}", "func (reg *registry[Item]) remove(topic string, ch chan Item, drain_channel bool) {\n\treg.lock.Lock()\n\tdefer reg.lock.Unlock()\n\tif _, ok := reg.topics[topic]; !ok {\n\t\treturn\n\t}\n\n\tif _, ok := reg.topics[topic][ch]; !ok {\n\t\treturn\n\t}\n\n\tdelete(reg.topics[topic], ch)\n\tdelete(reg.revTopics[ch], topic)\n\n\tif len(reg.topics[topic]) == 0 {\n\t\tdelete(reg.topics, topic)\n\t}\n\n\tif len(reg.revTopics[ch]) == 0 {\n\t\tif drain_channel {\n\t\t\treg.drainAndScheduleCloseChannel(ch)\n\t\t}\n\t\tdelete(reg.revTopics, ch)\n\t}\n}", "func (q *Queue) Dequeue() Lit {\n\tif len(q.items) == 0 {\n\t\treturn Undef\n\t}\n\tfirst := q.items[0]\n\tq.items = q.items[1:len(q.items)]\n\n\treturn first\n}", "func (j *JPNSoftwareMap) Del(ID string) (ok bool) {\n\tdelete(*j, ID)\n\tok = j.Has(ID) == false\n\treturn\n}", "func (q *Queue) Empty() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn len(q.items) == 0\n}", "func (n *trieNode) okToRemove() bool {\n\tif n.member {\n\t\treturn false\n\t}\n\tfor _, c := range n.children {\n\t\tif c != nil {\n\t\t\t// Still has a child, can't remove\n\t\t\treturn false\n\t\t}\n\t}\n\tif n.bitmap == nil {\n\t\t// not a bitmap node, so OK to remove.\n\t\treturn true\n\t}\n\treturn n.bitmap.isEmpty()\n}", "func (m *Map) Drop(seqno uint16, pid uint16) bool {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tif seqno != m.next {\n\t\treturn false\n\t}\n\n\tif len(m.entries) == 0 {\n\t\tm.entries = []entry{\n\t\t\tentry{\n\t\t\t\tfirst: seqno - 8192,\n\t\t\t\tcount: 8192,\n\t\t\t\tdelta: 0,\n\t\t\t\tpidDelta: 0,\n\t\t\t},\n\t\t}\n\t}\n\n\tm.pidDelta += pid - m.nextPid\n\tm.nextPid = pid\n\n\tm.delta--\n\tm.next = seqno + 1\n\treturn true\n}", "func (q *Queue) Remove() (int, error) {\r\n\tif len(q.data) == 0 {\r\n\t\treturn 0, fmt.Errorf(\"Queue is empty\")\r\n\t}\r\n\telement := q.data[0]\r\n\tq.data = q.data[1:]\r\n\treturn element, nil\r\n}", "func (this *MyQueue) Empty() bool {\n\treturn this.stack.IsEmpty()\n}", "func (st *FixedFIFO) Dequeue() (interface{}, error) {\n\tif st.IsLocked() {\n\t\treturn nil, NewQueueError(QueueErrorCodeLockedQueue, \"The queue is locked\")\n\t}\n\n\tselect {\n\tcase value, ok := <-st.queue:\n\t\tif ok {\n\t\t\treturn value, nil\n\t\t}\n\t\treturn nil, NewQueueError(QueueErrorCodeInternalChannelClosed, \"internal channel is closed\")\n\tdefault:\n\t\treturn nil, NewQueueError(QueueErrorCodeEmptyQueue, \"empty queue\")\n\t}\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.Stack) == 0\n}", "func (q *Queue) Dequeue() error {\n\tif q.IsEmpty() {\n\t\treturn fmt.Errorf(\"the queue is empty\")\n\t}\n\telement := q.tail\n\tfor i := 0; i < q.len-2; i++ {\n\t\telement = element.next\n\t}\n\tq.head = element\n\tq.head.next = nil\n\tq.len--\n\treturn nil\n}", "func (q *Queue) Pop() (repoName string, opts IndexOptions, ok bool) {\n\tq.mu.Lock()\n\tif len(q.pq) == 0 {\n\t\tq.mu.Unlock()\n\t\treturn \"\", IndexOptions{}, false\n\t}\n\titem := heap.Pop(&q.pq).(*queueItem)\n\trepoName = item.repoName\n\topts = item.opts\n\n\tmetricQueueLen.Set(float64(len(q.pq)))\n\tmetricQueueCap.Set(float64(len(q.items)))\n\n\tq.mu.Unlock()\n\treturn repoName, opts, true\n}", "func (q *wantConnQueue) clearFront() (cleaned bool) {\n\tfor {\n\t\tw := q.peekFront()\n\t\tif w == nil || w.waiting() {\n\t\t\treturn cleaned\n\t\t}\n\t\tq.popFront()\n\t\tcleaned = true\n\t}\n}", "func (q *Queue) updateQueue() {\n\tpurge := []int{}\n\t// Loop through jobs and get the status of running jobs\n\tfor i, _ := range q.stack {\n\t\tif q.stack[i].Status == common.STATUS_RUNNING {\n\t\t\t// Build status update call\n\t\t\tjobStatus := common.RPCCall{Job: q.stack[i]}\n\n\t\t\terr := q.pool[q.stack[i].ResAssigned].Client.Call(\"Queue.TaskStatus\", jobStatus, &q.stack[i])\n\t\t\t// we care about the errors, but only from a logging perspective\n\t\t\tif err != nil {\n\t\t\t\tlog.WithField(\"rpc error\", err.Error()).Error(\"Error during RPC call.\")\n\t\t\t}\n\n\t\t\t// Check if this is now no longer running\n\t\t\tif q.stack[i].Status != common.STATUS_RUNNING {\n\t\t\t\t// Release the resources from this change\n\t\t\t\tlog.WithField(\"JobID\", q.stack[i].UUID).Debug(\"Job has finished.\")\n\n\t\t\t\t// Call out to the registered hooks that the job is complete\n\t\t\t\tgo HookOnJobFinish(Hooks.JobFinish, q.stack[i])\n\n\t\t\t\tvar hw string\n\t\t\t\tfor _, v := range q.pool[q.stack[i].ResAssigned].Tools {\n\t\t\t\t\tif v.UUID == q.stack[i].ToolUUID {\n\t\t\t\t\t\thw = v.Requirements\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tq.pool[q.stack[i].ResAssigned].Hardware[hw] = true\n\n\t\t\t\t// Set a purge time\n\t\t\t\tq.stack[i].PurgeTime = time.Now().Add(time.Duration(q.jpurge*24) * time.Hour)\n\t\t\t\t// Log purge time\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"JobID\": q.stack[i].UUID,\n\t\t\t\t\t\"PurgeTime\": q.stack[i].PurgeTime,\n\t\t\t\t}).Debug(\"Updated PurgeTime value\")\n\t\t\t}\n\t\t}\n\n\t\t// Check and delete jobs past their purge timer\n\t\tif q.stack[i].Status == common.STATUS_DONE || q.stack[i].Status == common.STATUS_FAILED || q.stack[i].Status == common.STATUS_QUIT {\n\t\t\tif time.Now().After(q.stack[i].PurgeTime) {\n\t\t\t\tpurge = append(purge, i)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Do we need to purge?\n\tif len(purge) > 0 {\n\t\t// Let the purge begin\n\t\tnewStack := []common.Job{}\n\t\t// Loop on the stack looking for index values that patch a value in the purge\n\t\tfor i := range q.stack {\n\t\t\t// Check if our index is in the purge\n\t\t\tvar inPurge bool\n\t\t\tfor _, v := range purge {\n\t\t\t\tif i == v {\n\t\t\t\t\tinPurge = true\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// It is not in the purge so append to new stack\n\t\t\tif !inPurge {\n\t\t\t\tnewStack = append(newStack, q.stack[i])\n\t\t\t}\n\t\t}\n\t\tq.stack = newStack\n\t}\n}", "func (f *frontier) Dequeue() {\n\tf.lk.Lock()\n\tdefer f.lk.Unlock()\n\tif len(f.nbs) == 0 {\n\t\treturn\n\t}\n\tf.nbs = f.nbs[1:]\n}", "func EnsureNoQueue(ctx context.Context, cli sqsiface.SQSAPI) error {\n\tsrc := commonv1alpha1.ReconcilableFromContext(ctx)\n\ttypedSrc := src.(*v1alpha1.AWSS3Source)\n\n\tif dest := typedSrc.Spec.Destination; dest != nil {\n\t\tif userProvidedQueue := dest.SQS; userProvidedQueue != nil {\n\t\t\t// do not delete queues managed by the user\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tqueueURL, err := sqs.QueueURL(cli, queueName(typedSrc))\n\tswitch {\n\tcase isNotFound(err):\n\t\tevent.Warn(ctx, ReasonUnsubscribed, \"Queue not found, skipping deletion\")\n\t\treturn nil\n\tcase isDenied(err):\n\t\t// it is unlikely that we recover from auth errors in the\n\t\t// finalizer, so we simply record a warning event and return\n\t\tevent.Warn(ctx, ReasonFailedUnsubscribe,\n\t\t\t\"Authorization error getting SQS queue. Ignoring: %s\", toErrMsg(err))\n\t\treturn nil\n\tcase err != nil:\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Failed to determine URL of SQS queue: %s\", toErrMsg(err))\n\t}\n\n\towns, err := assertOwnership(cli, queueURL, typedSrc)\n\tif err != nil {\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Failed to verify owner of SQS queue: %s\", toErrMsg(err))\n\t}\n\n\tif !owns {\n\t\tevent.Warn(ctx, ReasonUnsubscribed, \"Queue %q is not owned by this source instance, \"+\n\t\t\t\"skipping deletion\", queueURL)\n\t\treturn nil\n\t}\n\n\terr = sqs.DeleteQueue(cli, queueURL)\n\tswitch {\n\tcase isDenied(err):\n\t\t// it is unlikely that we recover from auth errors in the\n\t\t// finalizer, so we simply record a warning event and return\n\t\tevent.Warn(ctx, ReasonFailedUnsubscribe,\n\t\t\t\"Authorization error deleting SQS queue. Ignoring: %s\", toErrMsg(err))\n\t\treturn nil\n\tcase err != nil:\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Error deleting SQS queue: %s\", toErrMsg(err))\n\t}\n\n\tevent.Normal(ctx, ReasonQueueDeleted, \"Deleted SQS queue %q\", queueURL)\n\n\treturn nil\n}", "func (m refCountedUrlSet) removeUrl(urlStr string) bool {\n\tremoved := false\n\tif ref, ok := m[urlStr]; ok {\n\t\tif ref == 1 {\n\t\t\tremoved = true\n\t\t\tdelete(m, urlStr)\n\t\t} else {\n\t\t\tm[urlStr]--\n\t\t}\n\t}\n\treturn removed\n}", "func (s *MQImpressionsStorage) Empty() bool {\n\ts.mutexQueue.Lock()\n\tdefer s.mutexQueue.Unlock()\n\treturn s.queue.Len() == 0\n}", "func whetherRemoveHost(info storage.HostInfo, currentBlockHeight uint64) bool {\n\tupRate := getHostUpRate(info)\n\tcriteria := calcHostRemoveCriteria(info, currentBlockHeight)\n\tif upRate > criteria {\n\t\treturn false\n\t}\n\treturn true\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.q) == 0\n}", "func (q *QueueWatcher) checkQueueEmpty(jobName string) (bool, error) {\n\tqueues, err := q.client.Queues()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, queue := range queues {\n\t\tif queue.JobName == jobName {\n\t\t\treturn queue.Count == 0, nil\n\t\t}\n\t}\n\n\t// If queue does not exist consider it empty.\n\t// QueueWatcher is not active in the initial phase during which no items\n\t// have been enqueued yet.\n\t// E.g. when active checks start, the ProductionExhausted channel has been\n\t// closed.\n\treturn true, nil\n}", "func (q *FileQueue) Dequeue() (int64, []byte, error) {\n\n\tif q.IsEmpty() {\n\t\treturn -1, nil, nil\n\t}\n\n\t// check and update queue front index info\n\tindex, err := q.updateQueueFrontIndex()\n\tif err != nil {\n\t\treturn -1, nil, err\n\t}\n\tbb, err := q.peek(index)\n\treturn index, bb, err\n}", "func (pq *packetQueue) remove(s *sender, seqno int64, scope int) {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\tfor next := pq.Front(); next != nil; next = next.Next() {\n\t\tp := next.Value.(*Packet)\n\t\tif p.sender.getID() == s.id && p.seqno == seqno && p.scope == scope {\n\t\t\tpq.Remove(next)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (storage *SrvStorage) DelQueue(vhost string, queue *queue.Queue) error {\n\tkey := fmt.Sprintf(\"%s.%s.%s\", queuePrefix, vhost, queue.GetName())\n\treturn storage.db.Del(key)\n}", "func (rate *Ratelimiter) cleanup() (empty bool) {\n\trate.mu.Lock()\n\tdefer rate.mu.Unlock()\n\n\tfor key, entry := range rate.tableIPv4 {\n\t\tentry.mu.Lock()\n\t\tif rate.timeNow().Sub(entry.lastTime) > garbageCollectTime {\n\t\t\tdelete(rate.tableIPv4, key)\n\t\t}\n\t\tentry.mu.Unlock()\n\t}\n\n\tfor key, entry := range rate.tableIPv6 {\n\t\tentry.mu.Lock()\n\t\tif rate.timeNow().Sub(entry.lastTime) > garbageCollectTime {\n\t\t\tdelete(rate.tableIPv6, key)\n\t\t}\n\t\tentry.mu.Unlock()\n\t}\n\n\treturn len(rate.tableIPv4) == 0 && len(rate.tableIPv6) == 0\n}", "func (Q *Queue) Dequeue() error {\n\tif Q.head == nil {\n\t\treturn errors.New(\"your queue is empty and impossible delete element\")\n\t}\n\telement := Node {}\n\telement.value = Q.head.value\n\tif Q.head.next != nil {\n\t\tQ.head = Q.head.next\n\t} else {\n\t\tQ.head = nil\n\t\tQ.tail = nil\n\t}\n\tQ.size--\n\treturn nil\n}", "func (svc *SQS) XPurgeQueue(ctx context.Context, queueURL string) error {\n\t_, err := svc.PurgeQueue(ctx, PurgeQueueRequest{\n\t\tQueueURL: queueURL,\n\t})\n\treturn err\n}" ]
[ "0.60027367", "0.5677631", "0.563571", "0.5616582", "0.5497436", "0.5481202", "0.54472536", "0.54457", "0.54185396", "0.53994423", "0.5352575", "0.5277354", "0.52290535", "0.5129753", "0.5122774", "0.5116718", "0.5096262", "0.5095654", "0.50874686", "0.5082583", "0.50537497", "0.5035871", "0.5032258", "0.50291175", "0.49949875", "0.49812487", "0.4974222", "0.49680665", "0.4962087", "0.49320486", "0.4899363", "0.48835176", "0.48524597", "0.48419195", "0.48312575", "0.48282716", "0.48249096", "0.48233986", "0.48196465", "0.48193744", "0.4815103", "0.48008442", "0.48003933", "0.4800091", "0.47984758", "0.479751", "0.47862777", "0.47790205", "0.477492", "0.4762616", "0.47606456", "0.4760467", "0.47589296", "0.47570157", "0.4753619", "0.4748258", "0.4739021", "0.4730927", "0.4724802", "0.47224575", "0.4715394", "0.47058278", "0.4701159", "0.47008216", "0.46910936", "0.46872234", "0.4679357", "0.46789578", "0.46784747", "0.46750498", "0.4674063", "0.4670224", "0.4658082", "0.46545246", "0.46303105", "0.46267974", "0.4626767", "0.46217495", "0.46135563", "0.46108082", "0.4609327", "0.46045154", "0.46002463", "0.45996818", "0.45897272", "0.45854053", "0.45818788", "0.45813116", "0.45803353", "0.45691097", "0.456546", "0.45589873", "0.45588738", "0.45564783", "0.45540878", "0.45534775", "0.45524666", "0.4550421", "0.45349345", "0.45346123" ]
0.83653677
0
GetSecret returns the value of the NovaScheduler.Spec.Secret
GetSecret возвращает значение NovaScheduler.Spec.Secret
func (n NovaScheduler) GetSecret() string { return n.Spec.Secret }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AssetReportRefreshRequest) GetSecret() string {\n\tif o == nil || o.Secret == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Secret\n}", "func GetSecret(tid string) ([]byte, error) {\n\tvar token string\n\n\tif err := db.QueryRow(\"SELECT token FROM event_tasks WHERE id = $1\", tid).\n\t\tScan(&token); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(token), nil\n}", "func (p *provider) GetSecret(ctx context.Context, name string) string {\n\tsecretPath := filepath.Join(\"projects\", p.projectID, \"secrets\", name, \"versions\", \"latest\")\n\treq := &secretmanagerpb.AccessSecretVersionRequest{\n\t\tName: secretPath,\n\t}\n\n\tres, err := p.client.AccessSecretVersion(ctx, req)\n\tif err != nil {\n\t\tlog.Fatalf(\"AccessSecretVersion error: %+v\", err)\n\t}\n\n\treturn string(res.Payload.Data)\n}", "func (o *ProcessorSignalDecisionReportRequest) GetSecret() string {\n\tif o == nil || o.Secret == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Secret\n}", "func (k *Instance) GetSecret(sel *core_api.SecretKeySelector, namespace string) ([]byte, error) {\n\tif sel == nil {\n\t\treturn nil, nil\n\t}\n\tsec, err := k.k8sOps.GetSecret(sel.Name, namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sec.Data[sel.Key], nil\n}", "func GetSecret() (string, string, error) {\n\tsecretMap := make(map[string]map[string]string)\n\tsecretCfg := os.Getenv(\"SQLFLOW_WORKFLOW_SECRET\")\n\tif secretCfg == \"\" {\n\t\treturn \"\", \"\", nil\n\t}\n\tif e := json.Unmarshal([]byte(secretCfg), &secretMap); e != nil {\n\t\treturn \"\", \"\", e\n\t}\n\tif len(secretMap) != 1 {\n\t\treturn \"\", \"\", fmt.Errorf(`SQLFLOW_WORKFLOW_SECRET should be a json string, e.g. {name: {key: value, ...}}`)\n\t}\n\tname := reflect.ValueOf(secretMap).MapKeys()[0].String()\n\tvalue, e := json.Marshal(secretMap[name])\n\tif e != nil {\n\t\treturn \"\", \"\", e\n\t}\n\treturn name, string(value), nil\n}", "func (s *SsmSecret) GetSecret() (string, error) {\n\tif s.isSecretValid() {\n\t\treturn s.value, nil\n\t}\n\tlog.Println(\"Refreshing secret...\")\n\tif err := s.refreshSecret(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn s.value, nil\n}", "func (c *Context) GetSecret(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tif c.secrets == nil {\n\t\treturn starlark.None, fmt.Errorf(\"no secrets provided\")\n\t}\n\n\tvar key starlark.String\n\tif err := starlark.UnpackPositionalArgs(\"get_secret\", args, kwargs, 1, &key); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn util.Marshal(c.secrets[string(key)])\n}", "func GetSecret(c *gin.Context) {\n\tvar (\n\t\trepo = session.Repo(c)\n\t\tname = c.Param(\"secret\")\n\t)\n\tsecret, err := Config.Services.Secrets.SecretFind(repo, name)\n\tif err != nil {\n\t\tc.String(404, \"Error getting secret %q. %s\", name, err)\n\t\treturn\n\t}\n\tc.JSON(200, secret.Copy())\n}", "func (p *ProxyTypeMtproto) GetSecret() (value string) {\n\tif p == nil {\n\t\treturn\n\t}\n\treturn p.Secret\n}", "func (m *Manager) GetSecret() string {\n\treturn m.user.Secret\n}", "func (f *FileLocation) GetSecret() (value int64) {\n\treturn f.Secret\n}", "func (f *FileLocationUnavailable) GetSecret() (value int64) {\n\treturn f.Secret\n}", "func (o *PartnerCustomerCreateRequest) GetSecret() string {\n\tif o == nil || o.Secret == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Secret\n}", "func (c *Client) GetSecret() string {\n\treturn c.Secret\n}", "func (system *System) GetSecret() (string, error) {\n\tdb := GetGORMDbConnection()\n\tdefer Close(db)\n\n\tsecret := Secret{}\n\n\terr := db.Where(\"system_id = ?\", system.ID).First(&secret).Error\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get hashed secret for clientID %s: %s\", system.ClientID, err.Error())\n\t}\n\n\tif secret.Hash == \"\" {\n\t\treturn \"\", fmt.Errorf(\"stored hash of secret for clientID %s is blank\", system.ClientID)\n\t}\n\n\treturn secret.Hash, nil\n}", "func GetSecret(namespace string, secretName string, data string) *v1.Secret {\n\treturn &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: secretName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\"firstLabel\": \"temp\"},\n\t\t},\n\t\tData: map[string][]byte{\"test.url\": []byte(data)},\n\t}\n}", "func (d *KfDef) GetSecret(name string) (string, error) {\n\tfor _, s := range d.Spec.Secrets {\n\t\tif s.Name != name {\n\t\t\tcontinue\n\t\t}\n\t\tif s.SecretSource.LiteralSource != nil {\n\t\t\treturn s.SecretSource.LiteralSource.Value, nil\n\t\t}\n\t\tif s.SecretSource.HashedSource != nil {\n\t\t\treturn s.SecretSource.HashedSource.HashedValue, nil\n\t\t}\n\t\tif s.SecretSource.EnvSource != nil {\n\t\t\treturn os.Getenv(s.SecretSource.EnvSource.Name), nil\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"No secret source provided for secret %v\", name)\n\t}\n\treturn \"\", NewSecretNotFound(name)\n}", "func getSecret() (string, error) {\n\tlog.Println(prefixLog, os.Args)\n\tif len(os.Args) == 1 || len(os.Args[1]) < 10 {\n\t\treturn \"\", errors.New(\"worker secret key invalid\")\n\t}\n\treturn os.Args[1], nil\n}", "func (s *SecretAPI) GetSecret(secretID, versionID, versionStage string) (*Secret, error) {\n\n\tif s.err != nil {\n\t\treturn nil, s.err\n\t}\n\n\tcs := C.CString(secretID)\n\tcv := C.CString(versionID)\n\tct := C.CString(versionStage)\n\n\tdefer func() {\n\t\ts.close()\n\t\tC.free(unsafe.Pointer(cs))\n\t\tC.free(unsafe.Pointer(cv))\n\t\tC.free(unsafe.Pointer(ct))\n\t}()\n\n\tres := C.gg_request_result{}\n\n\ts.APIRequest.initialize()\n\n\te := GreenGrassCode(C.gg_get_secret_value(s.request, cs, cv, ct, &res))\n\n\ts.response = s.handleRequestResponse(\n\t\t\"Failed to get secret\",\n\t\te, RequestStatus(res.request_status),\n\t)\n\n\tif s.err != nil {\n\t\treturn nil, s.err\n\t}\n\n\tLog(LogLevelInfo, \"Got Secret: %s\", s.response)\n\n\tvar secret Secret\n\tif err := json.Unmarshal([]byte(s.response), &secret); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &secret, nil\n\n}", "func GetSecret( blockchain string, key string)( *SecretResponse, error ){\r\n\t//KMS HOST\r\n\tvar kmsHost = os.Getenv(\"KMS_HOST\")\r\n\tres, err := http.Get( fmt.Sprintf(kmsHost+\"/secret?blockchain=%s&key=%s\",blockchain,key) )\r\n\tif err != nil {\r\n\t\treturn &SecretResponse{}, ErrKeyNotFound\r\n\t}\r\n\tdefer res.Body.Close()\r\n\tvar secretresp SecretResponse\r\n\tif err := json.NewDecoder(res.Body).Decode(&secretresp); err!=nil{\r\n\t\treturn &SecretResponse{}, ErrDecodeErr\r\n\t}\r\n\treturn &secretresp,nil\r\n}", "func (s Secret) Get() (*corev1.Secret, error) {\n\tsec := &corev1.Secret{}\n\terr := s.client.Get(context.TODO(), s.NamespacedName, sec)\n\treturn sec, err\n}", "func (factory *Factory) GetSecretName() string {\n\treturn factory.singleton.certificate.Name\n}", "func getSecret(name, namespace string, labels map[string]string) *corev1.Secret {\n\treturn &corev1.Secret{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: APIv1,\n\t\t\tKind: SecretKind,\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t}\n}", "func (s *provider) Get(name string) (string, error) {\n\ts.logger.Debug(\"Requesting secret\", common.LogSecretToken, name, common.LogSystemToken, logSystem)\n\tvalue, err := s.Secret.Get(name)\n\tif err != nil {\n\t\ts.logger.Error(\"Can't find requested secret\", err,\n\t\t\tcommon.LogSecretToken, name, common.LogSystemToken, logSystem)\n\t\treturn \"\", errors.Wrap(err, \"secret not found\")\n\t}\n\n\treturn value, nil\n}", "func (s *Secret) Get() (*corev1.Secret, error) {\n\tlog.Debug(\"Secret.Get()\")\n\tvar err error\n\ts.secrets, err = s.Interface.Get(s.Name, metav1.GetOptions{})\n\n\treturn s.secrets, err\n}", "func (c *Client) GetSecret(ctx context.Context, secretName string, projectId string, version string) (*pb.SecretPayload, error) {\n\tif version == \"\" {\n\t\tversion = \"latest\"\n\t}\n\t\n\tgetSecret := pb.AccessSecretVersionRequest{\n\t\tName: fmt.Sprintf(\"projects/%v/secrets/%v/versions/%v\", projectId, secretName, version),\n\t}\n\t\n\tresult, err := c.smc.AccessSecretVersion(ctx, &getSecret)\n\tif err != nil {\n\t\tlog.Printf(\"failed to get secret: %v\", err)\n\t\treturn nil, err\n\t}\n\t\n\treturn result.Payload, nil\n}", "func (s *Store) GetSecret(ctx context.Context, req secretstores.GetSecretRequest) (secretstores.GetSecretResponse, error) {\n\tres := secretstores.GetSecretResponse{Data: nil}\n\n\tif s.client == nil {\n\t\treturn res, fmt.Errorf(\"client is not initialized\")\n\t}\n\n\tif req.Name == \"\" {\n\t\treturn res, fmt.Errorf(\"missing secret name in request\")\n\t}\n\tsecretName := fmt.Sprintf(\"projects/%s/secrets/%s\", s.ProjectID, req.Name)\n\n\tversionID := \"latest\"\n\tif value, ok := req.Metadata[VersionID]; ok {\n\t\tversionID = value\n\t}\n\n\tsecret, err := s.getSecret(ctx, secretName, versionID)\n\tif err != nil {\n\t\treturn res, fmt.Errorf(\"failed to access secret version: %v\", err)\n\t}\n\n\treturn secretstores.GetSecretResponse{Data: map[string]string{req.Name: *secret}}, nil\n}", "func (ks *keystore) getSecret(input *secretsmanager.GetSecretValueInput) (string, error) {\n\tvar secret string\n\n\tresult, err := ks.manager.GetSecretValue(input)\n\n\tif err != nil {\n\t\treturn secret, err\n\t}\n\n\tif result.SecretString != nil {\n\t\tsecret = *result.SecretString\n\t} else {\n\t\tdecodedBinarySecretBytes := make([]byte, base64.StdEncoding.DecodedLen(len(result.SecretBinary)))\n\t\tlength, err := base64.StdEncoding.Decode(decodedBinarySecretBytes, result.SecretBinary)\n\t\tif err != nil {\n\t\t\treturn secret, err\n\t\t}\n\t\tsecret = string(decodedBinarySecretBytes[:length])\n\t}\n\n\treturn secret, nil\n}", "func (postgres *PostgreSQLReconciler) GetSecret(secretName string) (map[string][]byte, error) {\n\tsecret := &corev1.Secret{}\n\terr := postgres.Client.Get(types.NamespacedName{Name: secretName, Namespace: postgres.HarborCluster.Namespace}, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := secret.Data\n\treturn data, nil\n}", "func GetSecret(apiURL, ak, potp, secretKey string) (string, string, error) {\n\ttk, err := authenticate(apiURL, ak, potp)\n\tif err != nil {\n\t\tStatus = StatusKO\n\t\treturn \"\", \"\", err\n\t}\n\n\tns, err := getAppNamespace(apiURL, tk)\n\tif err != nil {\n\t\tStatus = StatusKO\n\t\treturn \"\", \"\", err\n\t}\n\n\tsecrets, err := getSecrets(apiURL, tk, ns)\n\tif err != nil {\n\t\tStatus = StatusKO\n\t\treturn \"\", \"\", err\n\t}\n\tif s := secrets[secretKey]; s != \"\" {\n\t\tStatus = StatusOK\n\t\treturn secretKey, s, nil\n\t}\n\tlog.Warning(\"vault.GetSecret> Unable to find %s\\n\", secretKey)\n\tStatus = StatusKO\n\treturn \"\", \"\", err\n}", "func getSecret(secretName string) (*api.Secret, error) {\n\t// Get the namespace this is running in from the env variable.\n\tnamespace := os.Getenv(\"POD_NAMESPACE\")\n\tif namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"unexpected: POD_NAMESPACE env var returned empty string\")\n\t}\n\t// Get a client to talk to the k8s apiserver, to fetch secrets from it.\n\tcc, err := restclient.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error in creating in-cluster config: %s\", err)\n\t}\n\tclient, err := clientset.NewForConfig(cc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error in creating in-cluster client: %s\", err)\n\t}\n\tvar secret *api.Secret\n\terr = wait.PollImmediate(1*time.Second, getSecretTimeout, func() (bool, error) {\n\t\tsecret, err = client.Core().Secrets(namespace).Get(secretName, metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tglog.Warningf(\"error in fetching secret: %s\", err)\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"timed out waiting for secret: %s\", err)\n\t}\n\tif secret == nil {\n\t\treturn nil, fmt.Errorf(\"unexpected: received null secret %s\", secretName)\n\t}\n\treturn secret, nil\n}", "func (h *KubernetesHelper) GetSecret(ctx context.Context, namespace, name string) (*corev1.Secret, error) {\n\treturn h.clientset.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})\n}", "func (m *Machine) GetSecret(namespace string, name string) (*corev1.Secret, error) {\n\tsecret, err := m.Clientset.CoreV1().Secrets(namespace).Get(context.Background(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"waiting for secret \"+name)\n\t}\n\n\treturn secret, nil\n}", "func (c client) GetSecret(objectKey k8sClient.ObjectKey) (corev1.Secret, error) {\n\ts := corev1.Secret{}\n\tif err := c.Get(context.TODO(), objectKey, &s); err != nil {\n\t\treturn corev1.Secret{}, err\n\t}\n\treturn s, nil\n}", "func (p *EnvironmentProvider) GetSecret(secretName string) (string, bool) {\n\tname := strings.ToUpper(strings.Replace(secretName, \"/\", \"_\", -1))\n\treturn p.lookup(name)\n}", "func getSecret() ([]byte, error) {\n\tif err := godotenv.Load(\".env\"); err != nil {\n\t\treturn nil, err\n\t}\n\treturn []byte(os.Getenv(\"SIGKEY\")), nil\n}", "func (o FunctionServiceConfigSecretVolumeOutput) Secret() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FunctionServiceConfigSecretVolume) string { return v.Secret }).(pulumi.StringOutput)\n}", "func (c *client) Get(sType, org, name, path string) (*library.Secret, error) {\n\t// create log fields from secret metadata\n\tfields := logrus.Fields{\n\t\t\"org\": org,\n\t\t\"repo\": name,\n\t\t\"secret\": path,\n\t\t\"type\": sType,\n\t}\n\n\t// check if secret is a shared secret\n\tif strings.EqualFold(sType, constants.SecretShared) {\n\t\t// update log fields from secret metadata\n\t\tfields = logrus.Fields{\n\t\t\t\"org\": org,\n\t\t\t\"team\": name,\n\t\t\t\"secret\": path,\n\t\t\t\"type\": sType,\n\t\t}\n\t}\n\n\tc.Logger.WithFields(fields).Tracef(\"getting native %s secret %s for %s/%s\", sType, path, org, name)\n\n\t// capture the secret from the native service\n\ts, err := c.Database.GetSecret(sType, org, name, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}", "func Get() (*Secret, error) {\n\tif sec != nil {\n\t\treturn sec, nil\n\t}\n\n\tfile, err := ioutil.ReadFile(\"files/secret.yaml\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(file, &sec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sec, nil\n}", "func (c *clientWrapper) GetSecret(namespace, name string) (*corev1.Secret, bool, error) {\n\tif !c.isWatchedNamespace(namespace) {\n\t\treturn nil, false, fmt.Errorf(\"failed to get secret %s/%s: namespace is not within watched namespaces\", namespace, name)\n\t}\n\n\tsecret, err := c.factoriesSecret[c.lookupNamespace(namespace)].Core().V1().Secrets().Lister().Secrets(namespace).Get(name)\n\texist, err := translateNotFoundError(err)\n\n\treturn secret, exist, err\n}", "func (s *server) Get(ctx context.Context, req *pb.SecretRequest) (res *pb.SecretResponse, err error) {\n\tbts, err := ioutil.ReadFile(fmt.Sprintf(\"/run/secrets/%v\", req.GetName()))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%v secret does not exist\", req.GetName())\n\t}\n\n\tres = &pb.SecretResponse{\n\t\tExists: true,\n\t\tData: bts,\n\t}\n\n\treturn\n}", "func getSecret(kubeClient client.Client, secretName, namespace string) (*corev1.Secret, error) {\n\ts := &corev1.Secret{}\n\n\terr := kubeClient.Get(context.TODO(), kubetypes.NamespacedName{Name: secretName, Namespace: namespace}, s)\n\n\tif err != nil {\n\t\treturn &corev1.Secret{}, err\n\t}\n\treturn s, nil\n}", "func (o FunctionServiceConfigSecretEnvironmentVariableOutput) Secret() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FunctionServiceConfigSecretEnvironmentVariable) string { return v.Secret }).(pulumi.StringOutput)\n}", "func Secret(c *cli.Context) string {\n\tv := c.String(flagSecret)\n\tif v == \"\" {\n\t\treturn env.GetString(EnvBittrexSecret)\n\t}\n\n\treturn v\n}", "func GetSecret(session client.ConfigProvider, secretName string) (io.Reader, error) {\n\n\t// Create a Secrets Manager client\n\tsvc := secretsmanager.New(session)\n\tinput := &secretsmanager.GetSecretValueInput{\n\t\tSecretId: aws.String(secretName),\n\t\tVersionStage: aws.String(\"AWSCURRENT\"), // VersionStage defaults to AWSCURRENT if unspecified\n\t}\n\n\tresult, err := svc.GetSecretValue(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Decrypts secret using the associated KMS CMK.\n\t// Depending on whether the secret is a string or binary, one of these fields will be populated.\n\tvar secretString string\n\tif result.SecretString != nil {\n\t\tsecretString = *result.SecretString\n\t} else {\n\t\tdecodedBinarySecretBytes := make([]byte, base64.StdEncoding.DecodedLen(len(result.SecretBinary)))\n\t\tn, err := base64.StdEncoding.Decode(decodedBinarySecretBytes, result.SecretBinary)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecretString = string(decodedBinarySecretBytes[:n])\n\t}\n\n\treturn strings.NewReader(secretString), nil\n}", "func (c *clusterApi) getSecret(w http.ResponseWriter, r *http.Request) {\n\tmethod := \"getSecret\"\n\tparams := r.URL.Query()\n\tsecretID := params[secrets.SecretKey]\n\n\tif len(secretID) == 0 || secretID[0] == \"\" {\n\t\tc.sendError(c.name, method, w, \"Missing secret ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tinst, err := clustermanager.Inst()\n\tif err != nil {\n\t\tc.sendError(c.name, method, w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsecretValue, err := inst.SecretGet(secretID[0])\n\tif err != nil {\n\t\tc.sendError(c.name, method, w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsecResp := &secrets.GetSecretResponse{\n\t\tSecretValue: secretValue,\n\t}\n\tjson.NewEncoder(w).Encode(secResp)\n}", "func (ckms *CKMS) GetSecret(secretName string) (map[string]string, error) {\n\toutput, err := ckms.sm.GetSecretValue(&secretsmanager.GetSecretValueInput{SecretId: &secretName})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tvar secretObj map[string]string\n\terr = json.Unmarshal([]byte(*output.SecretString), &secretObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn secretObj, nil\n}", "func (h *Handler) getSecret(secret *corev1.Secret) (*corev1.Secret, error) {\n\tnamespace := secret.GetNamespace()\n\tif len(namespace) == 0 {\n\t\tnamespace = h.namespace\n\t}\n\treturn h.clientset.CoreV1().Secrets(namespace).Get(h.ctx, secret.Name, h.Options.GetOptions)\n}", "func GetSecret(secretName string) (secret string, err error) {\n\tdefVal := os.Getenv(secretName)\n\tif Context == ContextAWS {\n\t\tif defVal, err = getAwsSsmSecret(secretName); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else if Context == ContextOpenfaas {\n\t\tif defVal, err = getOpenFaasSecret(secretName); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif defVal == \"\" {\n\t\treturn \"\", errors.New(\"missing secret \" + secretName)\n\t}\n\treturn defVal, nil\n}", "func (c *secrets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Secret, err error) {\n\tresult = &v1.Secret{}\n\terr = c.client.Get().\n\t\tResource(\"secrets\").\n\t\tName(name).\n\t\tVersionedParams(options).\n\t\tDo(ctx).\n\t\tInto(result)\n\n\treturn\n}", "func (k Kubernetes) GetSecret(secretName, namespace string, ctx context.Context) (*corev1.Secret, error) {\n\tsecret := &corev1.Secret{}\n\terr := k.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: secretName}, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn secret, err\n}", "func (o *Gojwt) GetSecretByte()([]byte){\n return []byte(o.secretKeyWord)\n}", "func (s *SecretStore) GetSecret(organizationID uint, name string) (clustersecret.SecretResponse, error) {\n\tsec, err := s.secrets.GetByName(organizationID, name)\n\tif err != nil {\n\t\treturn clustersecret.SecretResponse{}, err\n\t}\n\n\tif sec == nil {\n\t\treturn clustersecret.SecretResponse{}, clustersecret.ErrSecretNotFound\n\t}\n\n\treturn clustersecret.SecretResponse{\n\t\tName: sec.Name,\n\t\tType: sec.Type,\n\t\tValues: sec.Values,\n\t\tTags: sec.Tags,\n\t}, nil\n}", "func (client *Client) GetSmartContractSecret(secretName string) (_ string, err error) {\n\tscID := os.Getenv(\"SMART_CONTRACT_ID\")\n\tvar path string\n\t// Allow users to specify their own paths\n\tif strings.Contains(secretName, \"/\") {\n\t\tpath = secretName\n\t} else {\n\t\tpath = fmt.Sprintf(\"/var/openfaas/secrets/sc-%s-%s\", scID, secretName)\n\t}\n\n\tfile, err := os.Open(path)\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\tif err == nil {\n\t\treturn parseSecret(file)\n\t}\n\treturn \"\", err\n}", "func (secrets Secrets) Get(secretPath string) (interface{}, *time.Time, bool, error) {\n\tparts := strings.Split(secretPath, \"/\")\n\tif len(parts) != 2 {\n\t\treturn nil, nil, false, fmt.Errorf(\"unable to split kubernetes secret path into [namespace]/[secret]: %s\", secretPath)\n\t}\n\n\tvar namespace = parts[0]\n\tvar secretName = parts[1]\n\n\tsecret, found, err := secrets.findSecret(namespace, secretName)\n\tif err != nil {\n\t\tsecrets.logger.Error(\"failed-to-fetch-secret\", err, lager.Data{\n\t\t\t\"namespace\": namespace,\n\t\t\t\"secret-name\": secretName,\n\t\t})\n\t\treturn nil, nil, false, err\n\t}\n\n\tif found {\n\t\treturn secrets.getValueFromSecret(secret)\n\t}\n\n\tsecrets.logger.Info(\"secret-not-found\", lager.Data{\n\t\t\"namespace\": namespace,\n\t\t\"secret-name\": secretName,\n\t})\n\n\treturn nil, nil, false, nil\n}", "func (s *SecretsManagerProvider) GetSecret(name string) (string, error) {\n\tkey := strings.Replace(name, secretsManagerPrefix, \"\", 1)\n\tres, err := s.Client.GetSecretValue(&secretsmanager.GetSecretValueInput{\n\t\tSecretId: aws.String(key),\n\t})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not retrieve a value from Secrets Manager for secret %s\", err)\n\t}\n\treturn aws.StringValue(res.SecretString), nil\n}", "func (c *VaultClient) GetSecret(path string) (*vault.Secret, error) {\n\treturn c.client.Logical().Read(path)\n}", "func (s *SecretGetterFromK8s) GetSecret(namespace string, name string) (*corev1.Secret, error) {\n\tvar res corev1.Secret\n\terr := s.Reader.Get(context.TODO(), client.ObjectKey{Namespace: namespace, Name: name}, &res)\n\treturn &res, err\n}", "func (k *Key) Secret() string {\n\treturn k.Query().Get(\"secret\")\n}", "func Secret(s *dag.Secret) *envoy_api_v2_auth.Secret {\n\treturn &envoy_api_v2_auth.Secret{\n\t\tName: Secretname(s),\n\t\tType: &envoy_api_v2_auth.Secret_TlsCertificate{\n\t\t\tTlsCertificate: &envoy_api_v2_auth.TlsCertificate{\n\t\t\t\tPrivateKey: &envoy_api_v2_core.DataSource{\n\t\t\t\t\tSpecifier: &envoy_api_v2_core.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.PrivateKey(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCertificateChain: &envoy_api_v2_core.DataSource{\n\t\t\t\t\tSpecifier: &envoy_api_v2_core.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.Cert(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (k *Key) Secret() string {\n\tq := k.url.Query()\n\n\treturn q.Get(\"secret\")\n}", "func GetExpectedSecret(t *testing.T, fileName string) *v1.Secret {\n\tobj := getKubernetesObject(t, fileName)\n\tsecret, ok := obj.(*v1.Secret)\n\tassert.True(t, ok, \"Expected Secret object\")\n\treturn secret\n}", "func (secretsManager *SecretsManagerV2) GetSecret(getSecretOptions *GetSecretOptions) (result SecretIntf, response *core.DetailedResponse, err error) {\n\treturn secretsManager.GetSecretWithContext(context.Background(), getSecretOptions)\n}", "func (o *Gojwt) GetSecretKey()(string){\n return o.secretKeyWord\n}", "func (o IopingSpecVolumeVolumeSourceOutput) Secret() IopingSpecVolumeVolumeSourceSecretPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceSecret { return v.Secret }).(IopingSpecVolumeVolumeSourceSecretPtrOutput)\n}", "func GetSecret(secrets corev1controllers.SecretCache, repoSpec *v1.RepoSpec, repoNamespace string) (*corev1.Secret, error) {\n\tif repoSpec.ClientSecret == nil {\n\t\treturn nil, nil\n\t}\n\tns := repoSpec.ClientSecret.Namespace\n\tif repoNamespace != \"\" {\n\t\tns = repoNamespace\n\t}\n\n\treturn secrets.Get(ns, repoSpec.ClientSecret.Name)\n}", "func (k *Key) Secret() string {\n\treturn k.base.Secret()\n}", "func (s *DBSecretsService) GetSecret(ctx context.Context, organizationID string, name string, opts entitystore.Options) (*v1.Secret, error) {\n\tspan, ctx := trace.Trace(ctx, \"\")\n\tdefer span.Finish()\n\n\tif opts.Filter == nil {\n\t\topts.Filter = entitystore.FilterEverything()\n\t}\n\topts.Filter.Add(entitystore.FilterStat{\n\t\tScope: entitystore.FilterScopeField,\n\t\tSubject: \"Name\",\n\t\tVerb: entitystore.FilterVerbEqual,\n\t\tObject: name,\n\t})\n\n\tsecrets, err := s.GetSecrets(ctx, organizationID, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(secrets) < 1 {\n\t\treturn nil, SecretNotFound{}\n\t}\n\n\treturn secrets[0], nil\n}", "func get_auth_secret(ps *persist.PersistService, auth_token string) string {\n\tt, found := ps.Get(auth_token);\n\tif found {\n\t\treturn t.Data[\"secret\"];\n\t}\n\telse {\n\t\treturn \"BAD_TOKEN\"; // TODO better handling\n\t}\n\tpanic(\"unreachable\");\n\t// for n := range tokens.Data() {\n\t// \tt := tokens.At(n);\n\t// \ttoken, _ := t.(AuthToken);\n\t// \tif token.Token == auth_token { return token.Secret };\n\t// }\n\t// return \"BAD_TOKEN\"; // TODO: better handling this is terrible\n}", "func Get(ctx context.Context, name, namespace string, c kubernetes.Interface) (*v1.Secret, error) {\n\tsecret, err := c.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn secret, fmt.Errorf(\"error getting kubernetes secret: %s\", err)\n\t}\n\treturn secret, nil\n}", "func (s Keygen) Secret() *party.Secret {\n\treturn &party.Secret{\n\t\tID: s.selfID,\n\t}\n}", "func (c *Config) GetServiceAccountSecret() string {\n\treturn c.ServiceAccountSecret\n}", "func readVaultSecret(key string, f *framework.Framework) (string, string) {\n\tloginCmd := fmt.Sprintf(\"vault login -address=%s sample_root_token_id > /dev/null\", vaultAddr)\n\treadSecret := fmt.Sprintf(\"vault kv get -address=%s %s%s\", vaultAddr, vaultSecretNs, key)\n\tcmd := fmt.Sprintf(\"%s && %s\", loginCmd, readSecret)\n\topt := metav1.ListOptions{\n\t\tLabelSelector: \"app=vault\",\n\t}\n\tstdOut, stdErr := execCommandInPodAndAllowFail(f, cmd, cephCSINamespace, &opt)\n\treturn strings.TrimSpace(stdOut), strings.TrimSpace(stdErr)\n}", "func (s *StaticSource) ReadSecret(context.Context) (*Secret, error) {\n\treturn s.Secret, nil\n}", "func (factory *Factory) GetBackupSecretName() string {\n\treturn \"backup-credentials\"\n}", "func (c *clientImpl) GetSecret(namespace, name string) (*v1.Secret, bool, error) {\n\tvar secret *v1.Secret\n\titem, exists, err := c.secStores[c.lookupNamespace(namespace)].GetByKey(namespace + \"/\" + name)\n\tif err == nil && item != nil {\n\t\tsecret = item.(*v1.Secret)\n\t}\n\n\treturn secret, exists, err\n}", "func (c *Context) GetSecret(secretKey string) *v1.Secret {\n\tsecretInterface, exist, err := c.Caches.Secret.GetByKey(secretKey)\n\n\tif err != nil {\n\t\tglog.V(1).Infof(\"unable to get secret from store, error occurred %s\", err.Error())\n\t\treturn nil\n\t}\n\n\tif !exist {\n\t\tglog.V(1).Infof(\"unable to get secret from store, no such service %s\", secretKey)\n\t\treturn nil\n\t}\n\n\tsecret := secretInterface.(*v1.Secret)\n\treturn secret\n}", "func (client GroupClient) GetSecret(accountName string, databaseName string, secretName string) (result USQLSecret, err error) {\n\treq, err := client.GetSecretPreparer(accountName, databaseName, secretName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"GetSecret\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSecretSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"GetSecret\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetSecretResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"GetSecret\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (sp *SecretProposal) Secret() []uint32 { return sp.secret }", "func (b Banai) GetSecret(secretID string) (SecretInfo, error) {\n\tv, ok := b.secrets[secretID]\n\tif !ok {\n\t\treturn nil, ErrSecretNotFound\n\t}\n\n\treturn v, nil\n}", "func getSecretPhrase() (secret string) {\n\tsecret = \"LORAXSNUGGLEGEORGEICE\"\n\treturn\n}", "func (kv *FakeKeyVaultClient) GetSecret(ctx context.Context, vaultBaseURL string, secretName string, secretVersion string) (result azkeyvault.SecretBundle, err error) {\n\tkv.rp.Calls = append(kv.rp.Calls, \"KeyVaultClient:GetSecret:\"+secretName)\n\tfor _, s := range kv.rp.Secrets {\n\t\tif *s.ID == secretName {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\treturn azkeyvault.SecretBundle{}, fmt.Errorf(\"secret %s/%s not found\", vaultBaseURL, secretName)\n}", "func (c *Client) getValue(name string) (string, error) {\n\tinput := &secretsmanager.GetSecretValueInput{\n\t\tSecretId: aws.String(name),\n\t\tVersionStage: aws.String(\"AWSCURRENT\"), // VersionStage defaults to AWSCURRENT if unspecified.\n\t}\n\tresult, err := c.Client.GetSecretValue(context.TODO(), input)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"aws get getValue : %v\", err)\n\t}\n\n\treturn *result.SecretString, nil\n}", "func (i Item) GetSecret(s Session) (Secret, error) {\n\t// spec: GetSecret(IN ObjectPath session, OUT Secret secret);\n\tvar ret Secret\n\tcall := i.Call(_ItemGetSecret, 0, s.Path())\n\tif call.Err != nil {\n\t\treturn ret, call.Err\n\t}\n\tcall.Store(&ret)\n\treturn ret, nil\n}", "func GetSecret(client client.Client, parentNamespace string, secretRef *corev1.ObjectReference) (secret *corev1.Secret, err error) {\n\tsrLogger := log.WithValues(\"package\", \"utils\", \"method\", \"getSecret\")\n\tif secretRef != nil {\n\t\tsrLogger.Info(\"Retreive secret\", \"parentNamespace\", parentNamespace, \"secretRef\", secretRef)\n\t\tns := secretRef.Namespace\n\t\tif ns == \"\" {\n\t\t\tns = parentNamespace\n\t\t}\n\t\tsecret = &corev1.Secret{}\n\t\terr = client.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: secretRef.Name}, secret)\n\t\tif err != nil {\n\t\t\tsrLogger.Error(err, \"Failed to get secret \", \"Name:\", secretRef.Name, \" on namespace: \", secretRef.Namespace)\n\t\t\treturn nil, err\n\t\t}\n\t\tsrLogger.Info(\"Secret found \", \"Name:\", secretRef.Name, \" on namespace: \", secretRef.Namespace)\n\t} else {\n\t\tsrLogger.Info(\"No secret defined\", \"parentNamespace\", parentNamespace)\n\t}\n\treturn secret, err\n}", "func GetSecretName(dev *model.Dev) string {\n\treturn fmt.Sprintf(oktetoSecretTemplate, dev.Name)\n}", "func MustGetSecret(secretName string) (secret string) {\n\tvar err error\n\tdefVal := os.Getenv(secretName)\n\tif Context == ContextAWS {\n\t\tif defVal, err = getAwsSsmSecret(secretName); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else if Context == ContextOpenfaas {\n\t\tif defVal, err = getOpenFaasSecret(secretName); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif defVal == \"\" {\n\t\tlog.Fatalf(\"missing secret %s\", secretName)\n\t}\n\treturn defVal\n}", "func (c *Cluster) GetSecret(nameOrIDPrefix string) (types.Secret, error) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\tstate := c.currentNodeState()\n\tif !state.IsActiveManager() {\n\t\treturn types.Secret{}, c.errNoManager(state)\n\t}\n\n\tctx, cancel := c.getRequestContext()\n\tdefer cancel()\n\n\tsecret, err := getSecretByNameOrIDPrefix(ctx, &state, nameOrIDPrefix)\n\tif err != nil {\n\t\treturn types.Secret{}, err\n\t}\n\treturn convert.SecretFromGRPC(secret), nil\n}", "func (k Key) Secret() []byte {\n\treturn k.secret\n}", "func (in *K8SClient) GetSecret(namespace, name string) (*core_v1.Secret, error) {\n\tconfigMap, err := in.k8s.CoreV1().Secrets(namespace).Get(in.ctx, name, emptyGetOptions)\n\tif err != nil {\n\t\treturn &core_v1.Secret{}, err\n\t}\n\n\treturn configMap, nil\n}", "func (n *namespacedSecretStore) Get(selector *corev1api.SecretKeySelector) (string, error) {\n\tcreds, err := kube.GetSecretKey(n.client, n.namespace, selector)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to get key for secret\")\n\t}\n\n\treturn string(creds), nil\n}", "func (o GroupInitContainerVolumeOutput) Secret() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v GroupInitContainerVolume) map[string]string { return v.Secret }).(pulumi.StringMapOutput)\n}", "func (o *AssetReportRefreshRequest) GetSecretOk() (*string, bool) {\n\tif o == nil || o.Secret == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Secret, true\n}", "func (s Sign) Secret() *party.Secret {\n\treturn s.secret\n}", "func (c *configuration) Secret(clientSet ClientSet) *Secret {\n\tif clientSet != nil {\n\t\treturn NewSecret(clientSet)\n\t}\n\treturn nil\n\n}", "func (l *Libvirt) SecretGetValue(OptSecret Secret, Flags uint32) (rValue []byte, err error) {\n\tvar buf []byte\n\n\targs := SecretGetValueArgs {\n\t\tOptSecret: OptSecret,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(145, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Value: []byte\n\t_, err = dec.Decode(&rValue)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (o IopingSpecVolumeVolumeSourcePtrOutput) Secret() IopingSpecVolumeVolumeSourceSecretPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceSecret {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Secret\n\t}).(IopingSpecVolumeVolumeSourceSecretPtrOutput)\n}", "func (o FioSpecVolumeVolumeSourceOutput) Secret() FioSpecVolumeVolumeSourceSecretPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceSecret { return v.Secret }).(FioSpecVolumeVolumeSourceSecretPtrOutput)\n}", "func (ui *GUI) GenerateSecret() []byte {\n\tsecret := make([]byte, 32)\n\trand.Read(secret)\n\treturn secret\n}" ]
[ "0.7372657", "0.72075814", "0.7123475", "0.71159655", "0.70768034", "0.70471925", "0.7036488", "0.69847095", "0.6893502", "0.68894595", "0.68886346", "0.68447804", "0.6838665", "0.68321365", "0.67905784", "0.6787732", "0.6769878", "0.67160785", "0.67097425", "0.6685262", "0.66833276", "0.666304", "0.66231537", "0.66135746", "0.658484", "0.6578012", "0.65742016", "0.6544218", "0.65011305", "0.6480628", "0.64660364", "0.6454195", "0.6451419", "0.64454526", "0.64429957", "0.64417905", "0.64392996", "0.6429728", "0.642603", "0.64123243", "0.63927174", "0.63866884", "0.6386621", "0.6369176", "0.63638735", "0.6362147", "0.6347427", "0.6347307", "0.6341405", "0.63239026", "0.6318251", "0.6315943", "0.63123167", "0.6297722", "0.62782335", "0.6277504", "0.6276745", "0.6268179", "0.62622935", "0.6250925", "0.6235149", "0.62152946", "0.6210418", "0.6199889", "0.6196769", "0.6194789", "0.6187043", "0.61758846", "0.61737674", "0.6169456", "0.6168324", "0.6162776", "0.61563677", "0.6150255", "0.61476594", "0.6138072", "0.613422", "0.6132955", "0.6131109", "0.61254257", "0.61080134", "0.6100245", "0.60822815", "0.60706604", "0.6069727", "0.6069133", "0.6055864", "0.6048004", "0.60460013", "0.6035593", "0.60321164", "0.6024681", "0.6007601", "0.60014665", "0.5998929", "0.5994809", "0.5989177", "0.59788823", "0.59676933", "0.59416974" ]
0.9030379
0
NewTravisBuildListCommand will add a `travis build list` command which is responsible for showing a list of build
NewTravisBuildListCommand добавит команду `travis build list`, отвечающую за отображение списка сборок
func NewTravisBuildListCommand(client *travis.Client) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List all the builds", RunE: func(cmd *cobra.Command, args []string) error { return ListBuilds(client, os.Stdout) }, } return cmd }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ListBuilds(client *travis.Client, w io.Writer) error {\n\tfilterBranch := \"master\"\n\n\topt := &travis.RepositoryListOptions{Member: viper.GetString(\"TRAVIS_CI_OWNER\"), Active: true}\n\trepos, _, err := client.Repositories.Find(opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttr := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.FilterHTML)\n\tfmt.Fprintf(tr, \"%s\\t%s\\t%s\\t%s\\n\", \"\", \"Name\", \"Branch\", \"Finished\")\n\tfor _, repo := range repos {\n\t\t// Trying to remove the items that are not really running in Travis CI\n\t\t// Assume there is a better way to do this?\n\t\tif repo.LastBuildState == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, branchName := range strings.Split(filterBranch, \",\") {\n\t\t\tbranch, _, err := client.Branches.GetFromSlug(repo.Slug, branchName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfinish, err := time.Parse(time.RFC3339, branch.FinishedAt)\n\t\t\tfinishAt := finish.Format(ui.AppDateTimeFormat)\n\t\t\tif err != nil {\n\t\t\t\tfinishAt = branch.FinishedAt\n\t\t\t}\n\n\t\t\tresult := \"\"\n\t\t\tif branch.State == \"failed\" {\n\t\t\t\tresult = ui.AppFailure\n\t\t\t} else if branch.State == \"started\" {\n\t\t\t\tresult = ui.AppProgress\n\t\t\t} else {\n\t\t\t\tresult = ui.AppSuccess\n\t\t\t}\n\n\t\t\tfmt.Fprintf(tr, \"%s \\t%s\\t%s\\t%s\\n\", result, repo.Slug, branchName, finishAt)\n\t\t}\n\t}\n\n\ttr.Flush()\n\n\treturn nil\n}", "func NewListCommand() cli.Command {\n\treturn NewListCommandWithEnv(commoncli.DefaultEnv)\n}", "func (cli *bkCli) buildList(quietList bool) error {\n\n\tvar (\n\t\tbuilds []bk.Build\n\t\terr error\n\t)\n\n\tt := time.Now()\n\n\tprojects, err := cli.listProjects()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// did we locate a project\n\tproject := git.LocateProject(projects)\n\n\tif project != nil {\n\t\tfmt.Printf(\"Listing for project = %s\\n\\n\", *project.Name)\n\n\t\torg := extractOrg(*project.URL)\n\n\t\tbuilds, _, err = cli.client.Builds.ListByProject(org, *project.Slug, nil)\n\n\t} else {\n\t\tutils.Check(fmt.Errorf(\"Failed to locate the buildkite project using git.\")) // TODO tidy this up\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif quietList {\n\t\tfor _, build := range builds {\n\t\t\tfmt.Printf(\"%-36s\\n\", *build.ID)\n\t\t}\n\t\treturn nil // we are done\n\t}\n\n\ttb := table.New(buildColumns)\n\n\tfor _, build := range builds {\n\t\tvals := utils.ToMap(buildColumns, []interface{}{*build.Project.Name, *build.Number, *build.Branch, *build.Message, *build.State, *build.Commit})\n\t\ttb.AddRow(vals)\n\t}\n\n\ttb.Markdown = true\n\ttb.Print()\n\n\tfmt.Printf(\"\\nTime taken: %s\\n\", time.Now().Sub(t))\n\n\treturn nil\n}", "func buildList(c *cli.Context) error {\n\trepo := c.Args().First()\n\towner, name, err := parseRepo(repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := newClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilds, err := client.BuildList(owner, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbranch := c.String(\"branch\")\n\tevent := c.String(\"event\")\n\tstatus := c.String(\"status\")\n\tlimit := c.Int(\"limit\")\n\n\tvar count int\n\tfor _, build := range builds {\n\t\tif count >= limit {\n\t\t\tbreak\n\t\t}\n\t\tif branch != \"\" && build.Branch != branch {\n\t\t\tcontinue\n\t\t}\n\t\tif event != \"\" && build.Event != event {\n\t\t\tcontinue\n\t\t}\n\t\tif status != \"\" && build.Status != status {\n\t\t\tcontinue\n\t\t}\n\t\ttmpl.Execute(os.Stdout, build)\n\t\tcount++\n\t}\n\treturn nil\n}", "func NewListCommand() cli.Command {\n\treturn newListCommand(defaultEnv, newClients)\n}", "func NewAdoBuildListCommand(client *azuredevops.Client) *cobra.Command {\n\tvar opts ListOptions\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List all the builds\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.flags = args\n\t\t\treturn ListBuilds(client, opts, os.Stdout)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringVar(&opts.Branches, \"branches\", \"master\", \"Which branches should be displayed\")\n\n\treturn cmd\n}", "func buildPipelineListCmd() *cobra.Command {\n\tvars := listPipelineVars{}\n\tcmd := &cobra.Command{\n\t\tUse: \"ls\",\n\t\tShort: \"Lists all the deployed pipelines in an application.\",\n\t\tExample: `\n Lists all the pipelines for the frontend application.\n /code $ copilot pipeline ls -a frontend`,\n\t\tRunE: runCmdE(func(cmd *cobra.Command, args []string) error {\n\t\t\topts, err := newListPipelinesOpts(vars)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := opts.Ask(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn opts.Execute()\n\t\t}),\n\t}\n\n\tcmd.Flags().StringVarP(&vars.appName, appFlag, appFlagShort, tryReadingAppName(), appFlagDescription)\n\tcmd.Flags().BoolVar(&vars.shouldOutputJSON, jsonFlag, false, jsonFlagDescription)\n\treturn cmd\n}", "func NewListCommand(parent common.Registerer, globals *config.Data) *ListCommand {\n\tvar c ListCommand\n\tc.Globals = globals\n\tc.manifest.File.SetOutput(c.Globals.Output)\n\tc.manifest.File.Read(manifest.Filename)\n\tc.CmdClause = parent.Command(\"list\", \"List Syslog endpoints on a Fastly service version\")\n\tc.CmdClause.Flag(\"service-id\", \"Service ID\").Short('s').StringVar(&c.manifest.Flag.ServiceID)\n\tc.CmdClause.Flag(\"version\", \"Number of service version\").Required().IntVar(&c.Input.ServiceVersion)\n\treturn &c\n}", "func NewListCommand(c Command, run RunListFunc, subCommands SubCommands, mod ...CommandModifier) *cobra.Command {\n\treturn newCommand(c, run, subCommands, mod...)\n}", "func NewListCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List the proxies\",\n\t\tRun: listCommandFunc,\n\t}\n\n\treturn cmd\n}", "func (b Build) List(c *gin.Context) {\n\tproject := c.DefaultQuery(\"project\", \"\")\n\tpublic := c.DefaultQuery(\"public\", \"\")\n\tbuilds := []models.Build{}\n\tvar err error\n\n\tif public == \"true\" {\n\t\tbuilds, err = b.publicBuilds()\n\t} else {\n\t\tbuilds, err = b.userBuilds(c, project)\n\t}\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\tsugar.InternalError(c, err)\n\t\treturn\n\t}\n\n\tsugar.SuccessResponse(c, 200, builds)\n}", "func List() *cobra.Command {\n\tvar yamlOutput bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List your active cloud native development environments\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn list(yamlOutput)\n\t\t},\n\t}\n\tcmd.Flags().BoolVarP(&yamlOutput, \"yaml\", \"y\", false, \"yaml output\")\n\treturn cmd\n}", "func (c OSClientBuildClient) List(namespace string, opts kapi.ListOptions) (*buildapi.BuildList, error) {\n\treturn c.Client.Builds(namespace).List(opts)\n}", "func NewListCmd(f *cmdutil.Factory) *cobra.Command {\n\tvar output string\n\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tAliases: []string{\"ls\"},\n\t\tShort: \"List available gitignores\",\n\t\tLong: cmdutil.LongDesc(`\n\t\t\tLists all gitignore templates available via the GitHub Gitignores API (https://docs.github.com/en/rest/reference/gitignore#get-all-gitignore-templates).`),\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient := gitignore.NewClient(f.HTTPClient())\n\n\t\t\tgitignores, err := client.ListTemplates(context.Background())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch output {\n\t\t\tcase \"name\":\n\t\t\t\tfor _, gitignore := range gitignores {\n\t\t\t\t\tfmt.Fprintln(f.IOStreams.Out, gitignore)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\ttw := cli.NewTableWriter(f.IOStreams.Out)\n\t\t\t\ttw.SetHeader(\"Name\")\n\n\t\t\t\tfor _, gitignore := range gitignores {\n\t\t\t\t\ttw.Append(gitignore)\n\t\t\t\t}\n\n\t\t\t\ttw.Render()\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmdutil.AddOutputFlag(cmd, &output, \"table\", \"name\")\n\n\treturn cmd\n}", "func BuildList(builds ...buildapi.Build) buildapi.BuildList {\n\treturn buildapi.BuildList{\n\t\tItems: builds,\n\t}\n}", "func NewListCommand(activityRepo core.ActivityRepository) *cobra.Command {\n\tlistCmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Lists all activities\",\n\t\tLong: \"Lists all the current registered activities in the system\",\n\t\tArgs: cobra.NoArgs,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tExitIfAppNotConfigured()\n\t\t\tactivities, err := activityRepo.List()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tfor _, act := range activities {\n\t\t\t\tfmt.Println(act.ToPrintableString())\n\t\t\t}\n\t\t},\n\t}\n\treturn listCmd\n}", "func NewListCommand(commonOpts *common.Options) (cmd *cobra.Command) {\n\tcmd = &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List all images of applications\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn fmt.Errorf(\"not support yet\")\n\t\t},\n\t}\n\treturn\n}", "func ListCommand(cli *cli.SensuCli) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"list extensions\",\n\t\tRunE: runList(cli.Config.Format(), cli.Client, cli.Config.Namespace(), cli.Config.Format()),\n\t}\n\n\thelpers.AddAllNamespace(cmd.Flags())\n\thelpers.AddFormatFlag(cmd.Flags())\n\thelpers.AddFieldSelectorFlag(cmd.Flags())\n\thelpers.AddLabelSelectorFlag(cmd.Flags())\n\thelpers.AddChunkSizeFlag(cmd.Flags())\n\n\treturn cmd\n}", "func BuildsList(quietList bool) error {\n\tcli, err := newBkCli()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cli.buildList(quietList)\n}", "func NewBuildCommand() Command {\n\treturn Command{\n\t\tname: \"build\",\n\t\tshortDesc: \"Build dependencies and push to chart museum\",\n\t\tlongDesc: \"Validate, build and push dependencies from stevedore manifest(s)\",\n\t}\n}", "func newCmdJobList(ctx api.Context) *cobra.Command {\n\tvar jsonOutput bool\n\tvar quietOutput bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Show all job definitions\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient, err := metronomeClient(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tjobs, err := client.Jobs(\n\t\t\t\tmetronome.EmbedActiveRun(),\n\t\t\t\tmetronome.EmbedSchedule(),\n\t\t\t\tmetronome.EmbedHistorySummary(),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif quietOutput {\n\t\t\t\tfor _, job := range jobs {\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), job.ID)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif jsonOutput {\n\t\t\t\tenc := json.NewEncoder(ctx.Out())\n\t\t\t\tenc.SetIndent(\"\", \" \")\n\t\t\t\treturn enc.Encode(jobs)\n\t\t\t}\n\n\t\t\ttable := cli.NewTable(ctx.Out(), []string{\"ID\", \"STATUS\", \"LAST RUN\"})\n\t\t\tfor _, job := range jobs {\n\t\t\t\ttable.Append([]string{job.ID, job.Status(), job.LastRunStatus()})\n\t\t\t}\n\t\t\ttable.Render()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(&jsonOutput, \"json\", false, \"Print in json format\")\n\tcmd.Flags().BoolVarP(&quietOutput, \"quiet\", \"q\", false, \"Print only IDs of listed jobs\")\n\treturn cmd\n}", "func NewListCommand(banzaiCli cli.Cli) *cobra.Command {\n\toptions := listOptions{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List secrets\",\n\t\tArgs: cobra.NoArgs,\n\t\tAliases: []string{\"l\", \"ls\"},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.format, _ = cmd.Flags().GetString(\"output\")\n\t\t\trunList(banzaiCli, options)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\n\tflags.StringVarP(&options.secretType, \"type\", \"t\", \"\", \"Filter list to the given type\")\n\n\treturn cmd\n}", "func executeListCmd(t *gotesting.T, stdout io.Writer, args []string, wrapper *stubRunWrapper) subcommands.ExitStatus {\n\ttd := testutil.TempDir(t)\n\tdefer os.RemoveAll(td)\n\n\tcmd := newListCmd(stdout, td)\n\tcmd.wrapper = wrapper\n\tflags := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\tcmd.SetFlags(flags)\n\tif err := flags.Parse(args); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tflags.Set(\"build\", \"false\") // DeriveDefaults fails if -build=true and bundle dirs are missing\n\treturn cmd.Execute(context.Background(), flags)\n}", "func NewListCommandWithEnv(env *commoncli.Env) cli.Command {\n\treturn util.AdaptCommand(env, &listCommand{env: env})\n}", "func ListBuilds(client *azuredevops.Client, opts ListOptions, w io.Writer) error {\n\tbuildDefOpts := azuredevops.BuildDefinitionsListOptions{Path: \"\\\\\" + viper.GetString(\"AZURE_DEVOPS_TEAM\")}\n\tdefinitions, err := client.BuildDefinitions.List(&buildDefOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresults := make(chan azuredevops.Build)\n\tvar wg sync.WaitGroup\n\twg.Add(len(definitions))\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(results)\n\t}()\n\n\tfor _, definition := range definitions {\n\t\tgo func(definition azuredevops.BuildDefinition) {\n\t\t\tdefer wg.Done()\n\n\t\t\tfor _, branchName := range strings.Split(opts.Branches, \",\") {\n\t\t\t\tbuilds, err := getBuildsForBranch(client, definition.ID, branchName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(w, \"unable to get builds for definition %s: %v\", definition.Name, err)\n\t\t\t\t}\n\t\t\t\tif len(builds) > 0 {\n\t\t\t\t\tresults <- builds[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}(definition)\n\t}\n\n\tvar builds []azuredevops.Build\n\tfor result := range results {\n\t\tbuilds = append(builds, result)\n\t}\n\n\tsort.Slice(builds, func(i, j int) bool { return builds[i].Definition.Name < builds[j].Definition.Name })\n\n\t// renderAzureDevOpsBuilds(builds, len(builds), \".*\")\n\ttr := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.FilterHTML)\n\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%s\\n\", \"\", \"Name\", \"Branch\", \"Build\", \"Finished\")\n\tfor index := 0; index < len(builds); index++ {\n\t\tbuild := builds[index]\n\t\tname := build.Definition.Name\n\t\tresult := build.Result\n\t\tstatus := build.Status\n\t\tbuildNo := build.BuildNumber\n\t\tbranch := build.Branch\n\n\t\t// Deal with date formatting for the finish time\n\t\tfinish, err := time.Parse(time.RFC3339, builds[index].FinishTime)\n\t\tfinishAt := finish.Format(ui.AppDateTimeFormat)\n\t\tif err != nil {\n\t\t\tfinishAt = builds[index].FinishTime\n\t\t}\n\n\t\t// Filter on branches\n\t\tmatched, _ := regexp.MatchString(\".*\"+opts.Branches+\".*\", branch)\n\t\tif matched == false {\n\t\t\tcontinue\n\t\t}\n\n\t\tif status == \"inProgress\" {\n\t\t\tresult = ui.AppProgress\n\t\t} else if status == \"notStarted\" {\n\t\t\tresult = ui.AppPending\n\t\t} else {\n\t\t\tif result == \"failed\" {\n\t\t\t\tresult = ui.AppFailure\n\t\t\t} else {\n\t\t\t\tresult = ui.AppSuccess\n\t\t\t}\n\t\t}\n\n\t\tfmt.Fprintf(tr, \"%s \\t%s\\t%s\\t%s\\t%s\\n\", result, name, branch, buildNo, finishAt)\n\t}\n\n\ttr.Flush()\n\n\treturn nil\n}", "func NewListCmd(f *cmdutil.Factory) *ListCmd {\n\tccmd := &ListCmd{\n\t\tfactory: f,\n\t}\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Get configuration collection\",\n\t\tLong: `Get a collection of configuration (managedObjects) based on filter parameters`,\n\t\tExample: heredoc.Doc(`\n$ c8y configuration list\nGet a list of configuration files\n `),\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\thandler := c8yquerycmd.NewInventoryQueryRunner(\n\t\t\t\tcmd,\n\t\t\t\targs,\n\t\t\t\tccmd.factory,\n\t\t\t\tflags.WithC8YQueryFixedString(\"(type eq 'c8y_ConfigurationDump')\"),\n\t\t\t\tflags.WithC8YQueryFormat(\"name\", \"(name eq '%s')\"),\n\t\t\t\tflags.WithC8YQueryFormat(\"deviceType\", \"(c8y_Filter.type eq '%s')\"),\n\t\t\t\tflags.WithC8YQueryFormat(\"description\", \"(description eq '%s')\"),\n\t\t\t)\n\t\t\treturn handler()\n\t\t},\n\t}\n\n\tcmd.SilenceUsage = true\n\n\tcmd.Flags().String(\"name\", \"\", \"Configuration name filter\")\n\tcmd.Flags().String(\"description\", \"\", \"Configuration description filter\")\n\tcmd.Flags().String(\"deviceType\", \"\", \"Configuration device type filter\")\n\n\tcompletion.WithOptions(\n\t\tcmd,\n\t)\n\n\tflags.WithOptions(\n\t\tcmd,\n\t\tflags.WithCommonCumulocityQueryOptions(),\n\t\tflags.WithExtendedPipelineSupport(\"query\", \"query\", false, \"c8y_DeviceQueryString\"),\n\t\tflags.WithCollectionProperty(\"managedObjects\"),\n\t)\n\n\t// Required flags\n\n\tccmd.SubCommand = subcommand.NewSubCommand(cmd)\n\n\treturn ccmd\n}", "func newManifestListCmd(manifestParams *manifestParameters) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List manifests from a repository\",\n\t\tLong: newManifestListCmdLongMessage,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tregistryName, err := manifestParams.GetRegistryName()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tloginURL := api.LoginURL(registryName)\n\t\t\t// An acrClient is created to make the http requests to the registry.\n\t\t\tacrClient, err := api.GetAcrCLIClientWithAuth(loginURL, manifestParams.username, manifestParams.password, manifestParams.configs)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctx := context.Background()\n\t\t\terr = listManifests(ctx, acrClient, loginURL, manifestParams.repoName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn cmd\n}", "func NewCreateListCommand(list string) *CreateListCommand {\n\tcommand := new(CreateListCommand)\n\n\tcommand.definition = \"goboom <list>\"\n\tcommand.description = \"Creates the specified list.\"\n\tcommand.List = list\n\n\treturn command\n}", "func newVersionCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Prints version information\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\t\t\treturn versionTemplate.Execute(os.Stdout, build.GetInfo())\n\t\t},\n\t}\n}", "func NewListBoardsCommand(client trello.API) *cobra.Command {\n\tvar opts ListBoardOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"boards\",\n\t\tShort: \"List all the boards\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.refs = args\n\t\t\treturn DisplayBoards(client, opts, os.Stdout)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.BoolVar(&opts.ShowClosed, \"show-closed\", false, \"Display closed boards?\")\n\n\treturn cmd\n}", "func NewCmdGetBuildLogs(commonOpts *opts.CommonOptions) *cobra.Command {\n\toptions := &GetBuildLogsOptions{\n\t\tGetOptions: GetOptions{\n\t\t\tCommonOptions: commonOpts,\n\t\t},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"log [flags]\",\n\t\tShort: \"Display a build log\",\n\t\tLong: get_build_log_long,\n\t\tExample: get_build_log_example,\n\t\tAliases: []string{\"logs\"},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.Cmd = cmd\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\thelper.CheckErr(err)\n\t\t},\n\t}\n\tcmd.Flags().BoolVarP(&options.Tail, \"tail\", \"t\", true, \"Tails the build log to the current terminal\")\n\tcmd.Flags().BoolVarP(&options.Wait, \"wait\", \"w\", false, \"Waits for the build to start before failing\")\n\tcmd.Flags().BoolVarP(&options.FailIfPodFails, \"fail-with-pod\", \"\", false, \"Return an error if the pod fails\")\n\tcmd.Flags().DurationVarP(&options.WaitForPipelineDuration, \"wait-duration\", \"d\", time.Minute*5, \"Timeout period waiting for the given pipeline to be created\")\n\tcmd.Flags().BoolVarP(&options.BuildFilter.Pending, \"pending\", \"p\", false, \"Only display logs which are currently pending to choose from if no build name is supplied\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Filter, \"filter\", \"f\", \"\", \"Filters all the available jobs by those that contain the given text\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Owner, \"owner\", \"o\", \"\", \"Filters the owner (person/organisation) of the repository\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Repository, \"repo\", \"r\", \"\", \"Filters the build repository\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Branch, \"branch\", \"\", \"\", \"Filters the branch\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Build, \"build\", \"\", \"\", \"The build number to view\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Pod, \"pod\", \"\", \"\", \"The pod name to view\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.GitURL, \"giturl\", \"g\", \"\", \"The git URL to filter on. If you specify a link to a github repository or PR we can filter the query of build pods accordingly\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Context, \"context\", \"\", \"\", \"Filters the context of the build\")\n\tcmd.Flags().BoolVarP(&options.CurrentFolder, \"current\", \"c\", false, \"Display logs using current folder as repo name, and parent folder as owner\")\n\toptions.AddBaseFlags(cmd)\n\n\treturn cmd\n}", "func NewTriggerListCommand(p *commands.KnParams) *cobra.Command {\n\ttriggerListFlags := flags.NewListPrintFlags(TriggerListHandlers)\n\n\ttriggerListCommand := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List triggers\",\n\t\tAliases: []string{\"ls\"},\n\t\tExample: `\n # List all triggers\n kn trigger list\n\n # List all triggers in JSON output format\n kn trigger list -o json`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tnamespace, err := p.GetNamespace(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tclient, err := p.NewEventingClient(namespace)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttriggerList, err := client.ListTriggers(cmd.Context())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !triggerListFlags.GenericPrintFlags.OutputFlagSpecified() && len(triggerList.Items) == 0 {\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"No triggers found.\\n\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// empty namespace indicates all-namespaces flag is specified\n\t\t\tif namespace == \"\" {\n\t\t\t\ttriggerListFlags.EnsureWithNamespace()\n\t\t\t}\n\n\t\t\terr = triggerListFlags.Print(triggerList, cmd.OutOrStdout())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcommands.AddNamespaceFlags(triggerListCommand.Flags(), true)\n\ttriggerListFlags.AddFlags(triggerListCommand)\n\treturn triggerListCommand\n}", "func NewRevisionListCommand(p *commands.KnParams) *cobra.Command {\n\trevisionListFlags := flags.NewListPrintFlags(RevisionListHandlers)\n\n\trevisionListCommand := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List revisions\",\n\t\tAliases: []string{\"ls\"},\n\t\tLong: \"List revisions for a given service.\",\n\t\tExample: `\n # List all revisions\n kn revision list\n\n # List revisions for a service 'svc1' in namespace 'myapp'\n kn revision list -s svc1 -n myapp\n\n # List all revisions in JSON output format\n kn revision list -o json\n\n # List revision 'web'\n kn revision list web`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tnamespace, err := p.GetNamespace(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tclient, err := p.NewServingClient(namespace)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Create list filters\n\t\t\tvar params []clientservingv1.ListConfig\n\t\t\tparams, err = appendServiceFilter(params, client, cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tparams, err = appendRevisionNameFilter(params, args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Query for list with filters\n\t\t\trevisionList, err := client.ListRevisions(cmd.Context(), params...)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Stop if nothing found\n\t\t\tif !revisionListFlags.GenericPrintFlags.OutputFlagSpecified() && len(revisionList.Items) == 0 {\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"No revisions found.\\n\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// Add namespace column if no namespace is given (i.e. \"--all-namespaces\" option is given)\n\t\t\tif namespace == \"\" {\n\t\t\t\trevisionListFlags.EnsureWithNamespace()\n\t\t\t}\n\n\t\t\t// Only add temporary annotations if human readable output is requested\n\t\t\tif !revisionListFlags.GenericPrintFlags.OutputFlagSpecified() {\n\t\t\t\terr = enrichRevisionAnnotationsWithServiceData(cmd.Context(), p.NewServingClient, revisionList)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Sort revisions by namespace, service, generation (in this order)\n\t\t\tsortRevisions(revisionList)\n\n\t\t\t// Print out infos via printer framework\n\t\t\treturn revisionListFlags.Print(revisionList, cmd.OutOrStdout())\n\t\t},\n\t}\n\tcommands.AddNamespaceFlags(revisionListCommand.Flags(), true)\n\trevisionListFlags.AddFlags(revisionListCommand)\n\trevisionListCommand.Flags().StringVarP(&serviceNameFilter, \"service\", \"s\", \"\", \"Service name\")\n\n\treturn revisionListCommand\n}", "func ListCommand() cli.Command {\n\treturn cli.Command{\n\t\tName: \"list\",\n\t\tAliases: []string{\"l\"},\n\t\tUsage: \"List all invoices.\",\n\t\tDescription: \"Gets all records of database and lists them.\",\n\t\tAction: listAction,\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"format,f\",\n\t\t\t\tUsage: `list format; \n\tformats: (defualt is \"simple\")\n\t\t\t\"simple\" (or \"s\") \"brief\" (or \"b\"), \"pretty(or \"p\")\"`,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewListCmd(f *cmdutil.Factory) *cobra.Command {\n\to := &ListOptions{\n\t\tIOStreams: f.IOStreams,\n\t\tRepository: f.Repository,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tAliases: []string{\"ls\"},\n\t\tShort: \"List available skeletons\",\n\t\tLong: cmdutil.LongDesc(`\n\t\t\tLists all skeletons available in the configured repositories.`),\n\t\tExample: cmdutil.Examples(`\n\t\t\t# List skeletons only from the \"myrepo\" repository\n\t\t\tkickoff skeleton list --repository myrepo`),\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn o.Run()\n\t\t},\n\t}\n\n\tcmdutil.AddOutputFlag(cmd, &o.Output, \"table\", \"wide\", \"name\")\n\tcmdutil.AddRepositoryFlag(cmd, f, &o.RepoNames)\n\n\treturn cmd\n}", "func newListCmd(clientFn func() (*fic.ServiceClient, error), out io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List ports\",\n\t\tExample: \"fic ports list\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient, err := clientFn()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating FIC client: %w\", err)\n\t\t\t}\n\n\t\t\tpages, err := ports.List(client, nil).AllPages()\n\t\t\tif err != nil {\n\t\t\t\tvar e *json.UnmarshalTypeError\n\t\t\t\tif errors.As(err, &e) {\n\t\t\t\t\treturn fmt.Errorf(\"extracting ports from API response: %w\", err)\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"calling List ports API: %w\", err)\n\t\t\t}\n\n\t\t\tps, _ := ports.ExtractPorts(pages)\n\n\t\t\tt := utils.NewTabby(out)\n\t\t\tt.AddHeader(\"id\", \"name\", \"operationStatus\", \"isActivated\", \"vlanRanges\", \"tenantID\", \"switchName\",\n\t\t\t\t\"portType\", \"location\", \"area\")\n\t\t\tfor _, p := range ps {\n\t\t\t\tt.AddLine(p.ID, p.Name, p.OperationStatus, p.IsActivated, p.VLANRanges, p.TenantID, p.SwitchName,\n\t\t\t\t\tp.PortType, p.Location, p.Area)\n\t\t\t}\n\t\t\tt.Print()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn cmd\n}", "func MachineListCommand(c *cli.Context, log logging.Logger, _ string) (int, error) {\n\topts := &machine.ListOptions{\n\t\tLog: log.New(\"machine:list\"),\n\t}\n\n\tinfos, err := machine.List(opts)\n\tif err != nil {\n\t\treturn 1, err\n\t}\n\n\ttabFormatter(os.Stdout, infos)\n\treturn 0, nil\n}", "func ProjectListFactory() (cli.Command, error) {\n\tcomm, err := newCommand(\"nerd project list\", \"List all your projects.\", \"\", nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create command\")\n\t}\n\tcmd := &ProjectList{\n\t\tcommand: comm,\n\t}\n\tcmd.runFunc = cmd.DoRun\n\n\treturn cmd, nil\n}", "func (w *Command) List() error {\n\tfmt.Println(\"Available bugs and their target versions:\")\n\treturn util.PrintList(w.NewGit, util.FixType, w.Short)\n}", "func (v *varnishClient) BuildCommand() (string, []string) {\n\targList := []string{\"-j\"}\n\targList = append(argList, \"-n\", v.cfg.CacheDir)\n\n\tcommand := varnishStat\n\tif v.cfg.ExecDir != \"\" {\n\t\tcommand = filepath.Join(v.cfg.ExecDir, command)\n\t}\n\treturn command, argList\n}", "func ListBuilds(db *sql.DB, builds chan<- BuildMetadata, componentID string) error {\n\tdefer close(builds)\n\n\tvar rows *sql.Rows\n\tvar err error\n\tif componentID != \"\" {\n\t\trows, err = db.Query(selectBuildsByComponentID, componentID)\n\t} else {\n\t\trows, err = db.Query(selectBuilds)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tvar id, rowComponentID string\n\tvar createdAt int64\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&id, &rowComponentID, &createdAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuilds <- BuildMetadata{\n\t\t\tID: id,\n\t\t\tComponentID: rowComponentID,\n\t\t\tCreatedAt: time.Unix(createdAt, 0),\n\t\t}\n\t}\n\n\treturn nil\n}", "func newVersion() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"show build version\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tfmt.Println(version)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn cmd\n}", "func (t Plan) BuildCommand() []string {\n\t// detailed exit code needed to better parse the plan\n\tcommand := []string{\"plan\", \"-detailed-exitcode\"}\n\n\tif t.CompactWarnings {\n\t\tcommand = append(command, \"-compact-warnings\")\n\t}\n\n\tif t.Destroy {\n\t\tcommand = append(command, \"-destroy\")\n\t}\n\n\tif !t.Input {\n\t\tcommand = append(command, \"-input=false\")\n\t}\n\n\tif t.LockTimeout.String() != \"0s\" {\n\t\tcommand = append(command, \"-lock-timeout=\"+t.LockTimeout.String())\n\t}\n\n\tif t.NoColor {\n\t\tcommand = append(command, \"-no-color\")\n\t}\n\n\tif t.Out != \"\" {\n\t\tcommand = append(command, \"-out=\"+t.Out)\n\t}\n\n\tif t.Parallelism != 10 {\n\t\tcommand = append(command, fmt.Sprintf(\"-parallelism=%d\", t.Parallelism))\n\t}\n\n\tif !t.Refresh {\n\t\tcommand = append(command, \"-refresh=false\")\n\t}\n\n\tif t.State != \"\" {\n\t\tcommand = append(command, \"-state=\"+t.State)\n\t}\n\n\tif !t.Targets.Empty() {\n\t\tfor _, v := range t.Targets.Options {\n\t\t\tcommand = append(command, \"-target=\"+v)\n\t\t}\n\t}\n\n\tif !t.Vars.Empty() {\n\t\tfor _, v := range t.Vars.Options {\n\t\t\tcommand = append(command, \"-var '\"+v+\"'\")\n\t\t}\n\t}\n\n\tif !t.VarFiles.Empty() {\n\t\tfor _, v := range t.VarFiles.Options {\n\t\t\tcommand = append(command, \"-var-file=\"+v)\n\t\t}\n\t}\n\n\treturn command\n}", "func listRun(cmd *cobra.Command, args []string) {\n\t\n\t// Items are read in using ReadItems; an example of stepwise refinement and procedural abstraction.\n\titems, err := todo.ReadItems(dataFile)\n\n\tvar data [][]string\n\n\t// Selection statement run to check if the To-Do list is empty\n\tif len(items) == 0 {\n\t\tlog.Println(\"No To-Do's in Your List - use the create command to get started!\")\n\t\treturn\n\t}\n\n\t// Selection statement run to check if there was an error from reading the data\n\tif err != nil {\n\t\tlog.Printf(\"%v\", err)\n\t} \n\n\t// Calls Sort method created in todo.go; an example of stepwise refinement\n\ttodo.Sort(items)\n\n\t// Iterative statement that appends all of the To-Dos in the list to a String array\n\t// Sequential statements are run within the FOR-EACH loop\n\tfor _, i := range items {\n\t\tvar temp []string\n\t\ttemp = append(temp, i.Label())\n\t\ttemp = append(temp, i.PrettyDone())\n\t\ttemp = append(temp, i.PrettyPrint())\n\t\ttemp = append(temp, i.Text)\n\t\tdata = append(data, temp)\n\t}\n\n\t\n\t/*\n\tSets the parameters for the To-Do list displayed as a table to the user. \n\tControls the appearence of the GUI.\n\t*/\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string {\"Position\", \"Done?\", \"Priority\", \"Task\"})\n\n\ttable.SetHeaderColor(tablewriter.Colors{tablewriter.Bold, tablewriter.BgHiBlueColor},\n\t\ttablewriter.Colors{tablewriter.FgWhiteColor, tablewriter.Bold, tablewriter.BgHiBlueColor},\n\t\ttablewriter.Colors{tablewriter.BgHiBlueColor, tablewriter.FgWhiteColor},\n\t\ttablewriter.Colors{tablewriter.BgHiBlueColor, tablewriter.FgWhiteColor})\n\n\ttable.SetColumnColor(tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiCyanColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgHiMagentaColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgBlackColor})\n\n\tw := tabwriter.NewWriter(os.Stdout, 3, 0, 1, ' ', 0)\n\n\t// Iterative statement that appends all To-Do items marked done based on the condition of if either the --all or --done flag is active.\n\tfor p, i := range data {\n\t\tif allFlag || items[p].Done == doneFlag {\n\t\t\ttable.Append(i)\n\t\t}\n\t}\n\n\t// Renders the table\n\ttable.Render()\n\n\t// Flushes the writer\n\tw.Flush()\n\n}", "func newCmdClusterList(ctx api.Context) *cobra.Command {\n\tvar attachedOnly bool\n\tvar jsonOutput bool\n\tvar names bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List the clusters configured and the ones linked to the current cluster\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif names {\n\t\t\t\tclusters, err := ctx.Clusters()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tfor _, cluster := range clusters {\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), cluster.Name())\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), cluster.ID())\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tvar filters []lister.Filter\n\t\t\tif attachedOnly {\n\t\t\t\tfilters = append(filters, lister.AttachedOnly())\n\t\t\t} else {\n\t\t\t\tfilters = append(filters, lister.Linked())\n\t\t\t}\n\n\t\t\tconfigManager, err := ctx.ConfigManager()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\titems := lister.New(configManager, ctx.Logger()).List(filters...)\n\t\t\tif attachedOnly && len(items) == 0 {\n\t\t\t\treturn errors.New(\"no cluster is attached. Please run `dcos cluster attach <cluster-name>`\")\n\t\t\t}\n\n\t\t\tif jsonOutput {\n\t\t\t\tenc := json.NewEncoder(ctx.Out())\n\t\t\t\tenc.SetIndent(\"\", \" \")\n\t\t\t\treturn enc.Encode(items)\n\t\t\t}\n\n\t\t\ttable := cli.NewTable(ctx.Out(), []string{\"\", \"NAME\", \"ID\", \"STATUS\", \"VERSION\", \"URL\"})\n\t\t\tfor _, item := range items {\n\t\t\t\tvar attached string\n\t\t\t\tif item.Attached {\n\t\t\t\t\tattached = \"*\"\n\t\t\t\t}\n\t\t\t\ttable.Append([]string{attached, item.Name, item.ID, item.Status, item.Version, item.URL})\n\t\t\t}\n\t\t\ttable.Render()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(&attachedOnly, \"attached\", false, \"returns attached cluster only\")\n\tcmd.Flags().BoolVar(&jsonOutput, \"json\", false, \"returns clusters in json format\")\n\tcmd.Flags().BoolVar(&names, \"names\", false, \"print out a list of cluster names and IDs\")\n\tcmd.Flags().MarkHidden(\"names\")\n\treturn cmd\n}", "func NewBuild(\n\tui cli.Ui,\n\tgocmd gocmd.Command,\n\tworkspace deptfile.Workspacer,\n\ttoolcacher toolcacher.Cacher,\n) cli.Command {\n\treturn &buildCommand{\n\t\tf: newBuildFlagSet(),\n\t\tui: ui,\n\t\tgocmd: gocmd,\n\t\tworkspace: workspace,\n\t\ttoolcacher: toolcacher,\n\t}\n}", "func NewListCmd(f *cmdutil.Factory) *ListCmd {\n\tccmd := &ListCmd{\n\t\tfactory: f,\n\t}\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Get managed object collection\",\n\t\tLong: `Get a collection of managedObjects based on filter parameters`,\n\t\tExample: heredoc.Doc(`\n$ c8y inventory list\nGet a list of managed objects\n\n$ c8y inventory list --ids 1111,2222\nGet a list of managed objects by ids\n\n$ echo 'myType' | c8y inventory list\nSearch by type using pipeline. piped input will be mapped to type parameter\n\n$ c8y inventory get --id 1234 | c8y inventory list\nGet managed objects which have the same type as the managed object id=1234. piped input will be mapped to type parameter\n `),\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: ccmd.RunE,\n\t}\n\n\tcmd.SilenceUsage = true\n\n\tcmd.Flags().StringSlice(\"ids\", []string{\"\"}, \"List of ids.\")\n\tcmd.Flags().String(\"type\", \"\", \"ManagedObject type. (accepts pipeline)\")\n\tcmd.Flags().String(\"fragmentType\", \"\", \"ManagedObject fragment type.\")\n\tcmd.Flags().String(\"text\", \"\", \"managed objects containing a text value starting with the given text (placeholder {text}). Text value is any alphanumeric string starting with a latin letter (A-Z or a-z).\")\n\tcmd.Flags().Bool(\"withParents\", false, \"include a flat list of all parents and grandparents of the given object\")\n\tcmd.Flags().Bool(\"skipChildrenNames\", false, \"Don't include the child devices names in the response. This can improve the API response because the names don't need to be retrieved\")\n\n\tcompletion.WithOptions(\n\t\tcmd,\n\t)\n\n\tflags.WithOptions(\n\t\tcmd,\n\n\t\tflags.WithExtendedPipelineSupport(\"type\", \"type\", false, \"type\"),\n\t\tflags.WithCollectionProperty(\"managedObjects\"),\n\t)\n\n\t// Required flags\n\n\tccmd.SubCommand = subcommand.NewSubCommand(cmd)\n\n\treturn ccmd\n}", "func NewCommandList() *CommandList {\n\tlist := new(CommandList)\n\tlist.commands = []Command{}\n\treturn list\n}", "func BuildCommand(c *cli.Context) error {\n\n\tprod := getProduction(c)\n\n\tbuild, err := client.Build(prod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintMsg(messagedef.MsgBuildSuccess, prod, build.FeedAliasURL)\n\treturn nil\n}", "func newStatus() *cobra.Command {\n\tvar cluster []string\n\tvar timeout time.Duration\n\n\tcmd := &cobra.Command{\n\t\tUse: \"status\",\n\t\tShort: \"display cluster nodes.\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\t\t\treturn clusterShow(ctx, &globalKeys, cluster...)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.DurationVarP(&timeout, \"timeout\", \"t\", time.Second*60, \"time to wait for connection to complete\")\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\n\treturn cmd\n}", "func buildCLICommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"run\",\n\t\t\tUsage: \"runs your test suites\",\n\t\t\tAction: runAction,\n\t\t},\n\t\t{\n\t\t\tName: \"verify\",\n\t\t\tUsage: \"verify an api-check file\",\n\t\t\tAction: verifyAction,\n\t\t},\n\t\t{\n\t\t\tName: \"generate\",\n\t\t\tAliases: []string{\"gen\"},\n\t\t\tUsage: \"generate a skeleton api-check file\",\n\t\t\tAction: generateAction,\n\t\t},\n\t}\n}", "func NewCommandImageList() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tArgs: cobra.NoArgs,\n\t\tShort: \"Display Docker image on registry\",\n\t\tLong: `Display Docker image list on private registry`,\n\t\tRun: imgListMain,\n\t}\n\n\t//set local flag\n\tutils.AddImageFlag(cmd)\n\n\t//add subcommand\n\treturn cmd\n}", "func (client *BuildServiceClient) listBuildsCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, options *BuildServiceClientListBuildsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif buildServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildServiceName}\", url.PathEscape(buildServiceName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func NewBuildCommand(reportLocation string, containerized bool) *BuildCommand {\n\tcmd := &BuildCommand{\n\t\tCommand: Command{\n\t\t\treportLocation: reportLocation,\n\t\t\tVersion: OVBuildCommand, //build command 'results' version (report and artifacts)\n\t\t\tType: command.Build,\n\t\t\tState: command.StateUnknown,\n\t\t},\n\t}\n\n\tcmd.Command.init(containerized)\n\treturn cmd\n}", "func getBuildList(build model.Build, cs *cloudbuild.Service) model.Build {\n\n\tprojectId := build.ProjectID\n\trespBuildList, err := cs.Projects.Builds.List(projectId).Do()\n\tif err != nil {\n\t\tfmt.Printf(\"error: \" + err.Error())\n\t}\n\tfor i := 0; i < len(respBuildList.Builds); i++ {\n\t\t//fmt.Println(respBuildList.Builds[i].SourceProvenance.ResolvedRepoSource.CommitSha)\n\t\tif respBuildList.Builds[i].SourceProvenance.ResolvedRepoSource.CommitSha == build.CommitID {\n\t\t\tbuild.BuildID = respBuildList.Builds[i].Id\n\t\t\tbuild.BuildStatus = respBuildList.Builds[i].Status\n\t\t\tbuild.ImageID = respBuildList.Builds[i].Artifacts.Images[0]\n\t\t\treturn build\n\t\t}\n\t}\n\tfmt.Println(\"Build Details Not Found\")\n\tbuild.BuildID = \"0\"\n\treturn build\n}", "func ListCommand(c *cli.Context, log logging.Logger, _ string) int {\n\tif len(c.Args()) != 0 {\n\t\tcli.ShowCommandHelp(c, \"list\")\n\t\treturn 1\n\t}\n\n\tshowAll := c.Bool(\"all\")\n\n\tk, err := klient.CreateKlientWithDefaultOpts()\n\tif err != nil {\n\t\tlog.Error(\"Error creating klient client. err:%s\", err)\n\t\tfmt.Println(defaultHealthChecker.CheckAllFailureOrMessagef(GenericInternalError))\n\t\treturn 1\n\t}\n\n\tif err := k.Dial(); err != nil {\n\t\tlog.Error(\"Error dialing klient client. err:%s\", err)\n\t\tfmt.Println(defaultHealthChecker.CheckAllFailureOrMessagef(GenericInternalError))\n\t\treturn 1\n\t}\n\n\tinfos, err := getListOfMachines(k)\n\tif err != nil {\n\t\tlog.Error(\"Error listing machines. err:%s\", err)\n\t\tfmt.Println(getListErrRes(err, defaultHealthChecker))\n\t\treturn 1\n\t}\n\n\t// Sort our infos\n\tsort.Sort(infos)\n\n\t// Filter out infos for listing and json.\n\tfor i := 0; i < len(infos); i++ {\n\t\tinfo := &infos[i]\n\n\t\tonlineRecently := time.Since(info.OnlineAt) <= 24*time.Hour\n\t\thasMounts := len(info.Mounts) > 0\n\t\t// Do not show machines that have been offline for more than 24h,\n\t\t// but only if the machine doesn't have any mounts and we aren't using the --all\n\t\t// flag.\n\t\tif !hasMounts && !showAll && !onlineRecently {\n\t\t\t// Remove this element from the slice, because we're not showing it as\n\t\t\t// described above.\n\t\t\tinfos = append(infos[:i], infos[i+1:]...)\n\t\t\t// Decrement the index, since we're removing the item from the slice.\n\t\t\ti--\n\t\t\tcontinue\n\t\t}\n\n\t\t// For a more clear UX, replace the team name of the default Koding team,\n\t\t// with Koding.com\n\t\tfor i, team := range info.Teams {\n\t\t\tif team == \"Koding\" {\n\t\t\t\tinfo.Teams[i] = \"koding.com\"\n\t\t\t}\n\t\t}\n\n\t\tswitch info.MachineStatus {\n\t\tcase machine.MachineOffline:\n\t\t\tinfo.MachineStatusName = \"offline\"\n\t\tcase machine.MachineOnline:\n\t\t\tinfo.MachineStatusName = \"online\"\n\t\tcase machine.MachineDisconnected:\n\t\t\tinfo.MachineStatusName = \"disconnected\"\n\t\tcase machine.MachineConnected:\n\t\t\tinfo.MachineStatusName = \"connected\"\n\t\tcase machine.MachineError:\n\t\t\tinfo.MachineStatusName = \"error\"\n\t\tcase machine.MachineRemounting:\n\t\t\tinfo.MachineStatusName = \"remounting\"\n\t\tdefault:\n\t\t\tinfo.MachineStatusName = \"unknown\"\n\t\t}\n\t}\n\n\tif c.Bool(\"json\") {\n\t\tjsonBytes, err := json.MarshalIndent(infos, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Error(\"Marshalling infos to json failed. err:%s\", err)\n\t\t\tfmt.Println(GenericInternalError)\n\t\t\treturn 1\n\t\t}\n\n\t\tfmt.Println(string(jsonBytes))\n\t\treturn 0\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)\n\tfmt.Fprintf(w, \"\\tTEAM\\tLABEL\\tIP\\tALIAS\\tSTATUS\\tMOUNTED PATHS\\n\")\n\tfor i, info := range infos {\n\t\t// Join multiple teams into a single identifier\n\t\tteam := strings.Join(info.Teams, \",\")\n\n\t\tvar formattedMount string\n\t\tif len(info.Mounts) > 0 {\n\t\t\tformattedMount += fmt.Sprintf(\n\t\t\t\t\"%s -> %s\",\n\t\t\t\tshortenPath(info.Mounts[0].LocalPath),\n\t\t\t\tshortenPath(info.Mounts[0].RemotePath),\n\t\t\t)\n\t\t}\n\n\t\t// Currently we are displaying the status message over the formattedMount,\n\t\t// if it exists.\n\t\tif info.StatusMessage != \"\" {\n\t\t\tformattedMount = info.StatusMessage\n\t\t}\n\n\t\tfmt.Fprintf(w, \" %d.\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\",\n\t\t\ti+1, team, info.MachineLabel, info.IP, info.VMName, info.MachineStatusName,\n\t\t\tformattedMount,\n\t\t)\n\t}\n\tw.Flush()\n\n\treturn 0\n}", "func addNewBuilds(ctx context.Context, activationInfo specificActivationInfo, v *Version, p *Project,\n\ttasks TaskVariantPairs, syncAtEndOpts patch.SyncAtEndOptions, projectRef *ProjectRef, generatedBy string) ([]string, error) {\n\n\ttaskIdTables, err := getTaskIdTables(v, p, tasks, projectRef.Identifier)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to make task ID table\")\n\t}\n\n\tnewBuildIds := make([]string, 0)\n\tnewActivatedTaskIds := make([]string, 0)\n\tnewBuildStatuses := make([]VersionBuildStatus, 0)\n\n\texistingBuilds, err := build.Find(build.ByVersion(v.Id).WithFields(build.BuildVariantKey, build.IdKey))\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tvariantsProcessed := map[string]bool{}\n\tfor _, b := range existingBuilds {\n\t\tvariantsProcessed[b.BuildVariant] = true\n\t}\n\n\tcreateTime, err := getTaskCreateTime(p.Identifier, v)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"can't get create time for tasks\")\n\t}\n\tbatchTimeCatcher := grip.NewBasicCatcher()\n\tfor _, pair := range tasks.ExecTasks {\n\t\tif _, ok := variantsProcessed[pair.Variant]; ok { // skip variant that was already processed\n\t\t\tcontinue\n\t\t}\n\t\tvariantsProcessed[pair.Variant] = true\n\t\t// Extract the unique set of task names for the variant we're about to create\n\t\ttaskNames := tasks.ExecTasks.TaskNames(pair.Variant)\n\t\tdisplayNames := tasks.DisplayTasks.TaskNames(pair.Variant)\n\t\tactivateVariant := !activationInfo.variantHasSpecificActivation(pair.Variant)\n\t\tbuildArgs := BuildCreateArgs{\n\t\t\tProject: *p,\n\t\t\tVersion: *v,\n\t\t\tTaskIDs: taskIdTables,\n\t\t\tBuildName: pair.Variant,\n\t\t\tActivateBuild: activateVariant,\n\t\t\tTaskNames: taskNames,\n\t\t\tDisplayNames: displayNames,\n\t\t\tActivationInfo: activationInfo,\n\t\t\tGeneratedBy: generatedBy,\n\t\t\tTaskCreateTime: createTime,\n\t\t\tSyncAtEndOpts: syncAtEndOpts,\n\t\t\tProjectIdentifier: projectRef.Identifier,\n\t\t}\n\n\t\tgrip.Info(message.Fields{\n\t\t\t\"op\": \"creating build for version\",\n\t\t\t\"variant\": pair.Variant,\n\t\t\t\"activated\": activateVariant,\n\t\t\t\"version\": v.Id,\n\t\t})\n\t\tbuild, tasks, err := CreateBuildFromVersionNoInsert(buildArgs)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tif len(tasks) == 0 {\n\t\t\tgrip.Info(message.Fields{\n\t\t\t\t\"op\": \"skipping empty build for version\",\n\t\t\t\t\"variant\": pair.Variant,\n\t\t\t\t\"activated\": activateVariant,\n\t\t\t\t\"version\": v.Id,\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tif err = build.Insert(); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"error inserting build %s\", build.Id)\n\t\t}\n\t\tif err = tasks.InsertUnordered(ctx); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"error inserting tasks for build %s\", build.Id)\n\t\t}\n\t\tnewBuildIds = append(newBuildIds, build.Id)\n\n\t\tbatchTimeTasksToIds := map[string]string{}\n\t\tfor _, t := range tasks {\n\t\t\tif t.Activated {\n\t\t\t\tnewActivatedTaskIds = append(newActivatedTaskIds, t.Id)\n\t\t\t}\n\t\t\tif activationInfo.taskHasSpecificActivation(t.BuildVariant, t.DisplayName) {\n\t\t\t\tbatchTimeTasksToIds[t.DisplayName] = t.Id\n\t\t\t}\n\t\t}\n\n\t\tvar activateVariantAt time.Time\n\t\tbatchTimeTaskStatuses := []BatchTimeTaskStatus{}\n\t\tif !activateVariant {\n\t\t\tactivateVariantAt, err = projectRef.GetActivationTimeForVariant(p.FindBuildVariant(pair.Variant))\n\t\t\tbatchTimeCatcher.Add(errors.Wrapf(err, \"unable to get activation time for variant '%s'\", pair.Variant))\n\t\t}\n\t\tfor taskName, id := range batchTimeTasksToIds {\n\t\t\tactivateTaskAt, err := projectRef.GetActivationTimeForTask(p.FindTaskForVariant(taskName, pair.Variant))\n\t\t\tbatchTimeCatcher.Add(errors.Wrapf(err, \"unable to get activation time for task '%s' (variant '%s')\", taskName, pair.Variant))\n\t\t\tbatchTimeTaskStatuses = append(batchTimeTaskStatuses, BatchTimeTaskStatus{\n\t\t\t\tTaskId: id,\n\t\t\t\tTaskName: taskName,\n\t\t\t\tActivationStatus: ActivationStatus{\n\t\t\t\t\tActivateAt: activateTaskAt,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tnewBuildStatuses = append(newBuildStatuses,\n\t\t\tVersionBuildStatus{\n\t\t\t\tBuildVariant: pair.Variant,\n\t\t\t\tBuildId: build.Id,\n\t\t\t\tBatchTimeTasks: batchTimeTaskStatuses,\n\t\t\t\tActivationStatus: ActivationStatus{\n\t\t\t\t\tActivated: activateVariant,\n\t\t\t\t\tActivateAt: activateVariantAt,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\tgrip.Error(message.WrapError(batchTimeCatcher.Resolve(), message.Fields{\n\t\t\"message\": \"unable to get all activation times\",\n\t\t\"runner\": \"addNewBuilds\",\n\t\t\"version\": v.Id,\n\t}))\n\n\treturn newActivatedTaskIds, errors.WithStack(VersionUpdateOne(\n\t\tbson.M{VersionIdKey: v.Id},\n\t\tbson.M{\n\t\t\t\"$push\": bson.M{\n\t\t\t\tVersionBuildIdsKey: bson.M{\"$each\": newBuildIds},\n\t\t\t\tVersionBuildVariantsKey: bson.M{\"$each\": newBuildStatuses},\n\t\t\t},\n\t\t},\n\t))\n}", "func registerCommandList(progname string) {\n\tlog.Printf(\"Entering repo::registerCommandList(%s)\", progname)\n\tdefer log.Println(\"Exiting repo::registerCommandList\")\n\n\tcmdOptions.listCmd = flag.NewFlagSet(progname+\" list\", flag.PanicOnError)\n\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.productVersion,\n\t\t\"product-version\",\n\t\t\"\",\n\t\t\"Version that a software should be compatibile with.\"+\n\t\t\t\" (I.e., product-version)\",\n\t)\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.softwareName,\n\t\t\"filename\",\n\t\t\"\",\n\t\t\"File name of the software.\",\n\t)\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.softwareRepo,\n\t\t\"repo\",\n\t\tSoftwareRepoPath,\n\t\t\"Path of the software repository.\",\n\t)\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.softwareType,\n\t\t\"type\",\n\t\t\"\",\n\t\t\"Type of the software.\",\n\t)\n\toutput.RegisterCommandOptions(cmdOptions.listCmd,\n\t\tmap[string]string{\"output-format\": \"yaml\"})\n}", "func MakeCommand(globalParamsGetter func() GlobalParams) *cobra.Command {\n\tcliParams := &cliParams{}\n\n\tworkloadListCommand := &cobra.Command{\n\t\tUse: \"workload-list\",\n\t\tShort: \"Print the workload content of a running agent\",\n\t\tLong: ``,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tglobalParams := globalParamsGetter()\n\n\t\t\tcliParams.GlobalParams = globalParams\n\n\t\t\treturn fxutil.OneShot(workloadList,\n\t\t\t\tfx.Supply(cliParams),\n\t\t\t\tfx.Supply(core.BundleParams{\n\t\t\t\t\tConfigParams: config.NewAgentParamsWithoutSecrets(\n\t\t\t\t\t\tglobalParams.ConfFilePath,\n\t\t\t\t\t\tconfig.WithConfigName(globalParams.ConfigName),\n\t\t\t\t\t),\n\t\t\t\t\tLogParams: log.LogForOneShot(globalParams.LoggerName, \"off\", true)}),\n\t\t\t\tcore.Bundle,\n\t\t\t)\n\t\t},\n\t}\n\n\tworkloadListCommand.Flags().BoolVarP(&cliParams.verboseList, \"verbose\", \"v\", false, \"print out a full dump of the workload store\")\n\n\treturn workloadListCommand\n}", "func New(b BuildInfo) *Command {\n\tfs := flag.NewFlagSet(\"changelog\", flag.ExitOnError)\n\n\treturn &Command{\n\t\tfs: fs,\n\t\tb: b,\n\t\tfile: fs.String(fileOptName, dfltChangelogFile, \"changelog file name\"),\n\t\tdebug: fs.Bool(debugOptName, false, \"log debug information\"),\n\t\ttoStdOut: fs.Bool(stdOutOptName, false, \"output changelog to stdout instead to file\"),\n\t\thistory: fs.Bool(historyOptName, false, \"create history of old versions tags (output is always stdout)\"),\n\t\tignore: fs.Bool(ignoreOptName, false, \"ignore parsing errors of invalid (not conventional) commit messages\"),\n\t\tsinceTag: fs.String(sinceTagOptName, \"\", fmt.Sprintf(\"in combination with -%s: if a tag is specified, the changelog will be created from that tag on\", historyOptName)),\n\t\tinitConfig: fs.Bool(initDfltConfigOptName, false, fmt.Sprintf(\"initialize a default changelog configuration '%s'\", config.FileName)),\n\t\tnoPrompt: fs.Bool(noPromptOptName, false, \"do not prompt for next version\"),\n\t\tversion: fs.Bool(versionOptName, false, \"show program version information\"),\n\t\tnum: fs.Int(numOptName, 0, fmt.Sprintf(\"in combination with -%s: the number of tags to go back\", historyOptName)),\n\t}\n}", "func (st *buildStatus) distTestList() (names []distTestName, remoteErr, err error) {\n\tworkDir, err := st.bc.WorkDir(st.ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"distTestList, WorkDir: %v\", err)\n\t\treturn\n\t}\n\tgoroot := st.conf.FilePathJoin(workDir, \"go\")\n\n\targs := []string{\"tool\", \"dist\", \"test\", \"--no-rebuild\", \"--list\"}\n\tif st.conf.IsRace() {\n\t\targs = append(args, \"--race\")\n\t}\n\tif st.conf.CompileOnly {\n\t\targs = append(args, \"--compile-only\")\n\t}\n\tvar buf bytes.Buffer\n\tremoteErr, err = st.bc.Exec(st.ctx, \"./go/bin/go\", buildlet.ExecOpts{\n\t\tOutput: &buf,\n\t\tExtraEnv: append(st.conf.Env(), \"GOROOT=\"+goroot),\n\t\tOnStartExec: func() { st.LogEventTime(\"discovering_tests\") },\n\t\tPath: []string{st.conf.FilePathJoin(\"$WORKDIR\", \"go\", \"bin\"), \"$PATH\"},\n\t\tArgs: args,\n\t})\n\tif remoteErr != nil {\n\t\tremoteErr = fmt.Errorf(\"Remote error: %v, %s\", remoteErr, buf.Bytes())\n\t\terr = nil\n\t\treturn\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Exec error: %v, %s\", err, buf.Bytes())\n\t\treturn\n\t}\n\t// To avoid needing to update all the existing dist test adjust policies,\n\t// it's easier to remap new dist test names in \"<pkg>[:<variant>]\" format\n\t// to ones used in Go 1.20 and prior. Do that for now.\n\tfor _, test := range go120DistTestNames(strings.Fields(buf.String())) {\n\t\tisNormalTry := st.isTry() && !st.isSlowBot()\n\t\tif !st.conf.ShouldRunDistTest(test.Old, isNormalTry) {\n\t\t\tcontinue\n\t\t}\n\t\tnames = append(names, test)\n\t}\n\treturn names, nil, nil\n}", "func NewCmdControllerBuild(commonOpts *opts.CommonOptions) *cobra.Command {\n\toptions := &ControllerBuildOptions{\n\t\tControllerOptions: ControllerOptions{\n\t\t\tCommonOptions: commonOpts,\n\t\t},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"build\",\n\t\tShort: \"Runs the build controller\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.Cmd = cmd\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\thelper.CheckErr(err)\n\t\t},\n\t\tAliases: []string{\"builds\"},\n\t}\n\n\tcmd.Flags().StringVarP(&options.Namespace, \"namespace\", \"n\", \"\", \"The namespace to watch or defaults to the current namespace\")\n\tcmd.Flags().BoolVarP(&options.InitGitCredentials, \"git-credentials\", \"\", false, \"If enable then lets run the 'jx step git credentials' step to initialise git credentials\")\n\tcmd.Flags().BoolVarP(&options.FailIfNoGitProvider, \"fail-on-git-provider-error\", \"\", false, \"If enable then lets terminate quickly if we cannot create a git provider\")\n\n\t// optional git reporting flags\n\tcmd.Flags().StringVarP(&options.TargetURLTemplate, \"target-url-template\", \"\", \"\", \"The Go template for generating the target URL of pipeline logs/views if git reporting is enabled. If unspecified, a default will be used based on `--job-url-base`.\")\n\tcmd.Flags().BoolVarP(&options.GitReporting, \"git-reporting\", \"\", false, \"If enabled then lets report pipeline success/failures to the git provider. Note this is purely tactical until we can do this natively inside tekton\")\n\tcmd.Flags().StringVarP(&options.JobURLBase, \"job-url-base\", \"\", \"\", \"The base URL, such as 'https://dashboard.jenkins-x.live', for generating the target URL for pipeline logs if git reporting is enabled.\")\n\treturn cmd\n}", "func listCommandFunc(cmd *cobra.Command, args []string) {\n\turl := fmt.Sprintf(\"http://%s%s\", Global.Endpoints, proxy.APIProxies)\n\tcli := &http.Client{}\n\trsp, err := cli.Get(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tdefer rsp.Body.Close()\n\t\tdata, err := ioutil.ReadAll(rsp.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\\n\", data)\n\t\t}\n\t}\n}", "func NewCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Returns a list of device profiles\",\n\t\tLong: `Returns the list of device profiles currently in the core-metadata database.`,\n\t\tRunE: listHandler,\n\t}\n\treturn cmd\n}", "func NewConfigPluginListCmd(opt *common.CommonOption) (cmd *cobra.Command) {\n\tconfigPluginListCmd := configPluginListCmd{\n\t\tCommonOption: opt,\n\t}\n\n\tcmd = &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"list all installed plugins\",\n\t\tLong: \"list all installed plugins\",\n\t\tRunE: configPluginListCmd.RunE,\n\t\tAnnotations: map[string]string{\n\t\t\tcommon.Since: common.VersionSince0028,\n\t\t},\n\t}\n\n\tconfigPluginListCmd.SetFlagWithHeaders(cmd, \"Use,Version,DownloadLink\")\n\treturn\n}", "func NewListCmd(f *cmdutil.Factory) *ListCmd {\n\tccmd := &ListCmd{\n\t\tfactory: f,\n\t}\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List smart group collection\",\n\t\tLong: `Get a collection of smart groups based on filter parameters`,\n\t\tExample: heredoc.Doc(`\n\t\t\t$ c8y smartgroups list\n\t\t\tGet a list of smart groups\n\n\t\t\t$ c8y smartgroups list --name \"myText*\"\n\t\t\tGet a list of smart groups with the names starting with 'myText'\n\n\t\t\t$ c8y smartgroups list --name \"myText*\" | c8y devices list\n\t\t\tGet a list of smart groups with their names starting with \"myText\", then get the devices from the smart groups\n `),\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: ccmd.RunE,\n\t}\n\n\tcmd.SilenceUsage = true\n\n\tcmd.Flags().String(\"name\", \"\", \"Filter by name\")\n\tcmd.Flags().String(\"fragmentType\", \"\", \"Filter by fragment type\")\n\tcmd.Flags().String(\"owner\", \"\", \"Filter by owner\")\n\tcmd.Flags().String(\"deviceQuery\", \"\", \"Filter by device query\")\n\tcmd.Flags().String(\"query\", \"\", \"Additional query filter (accepts pipeline)\")\n\tcmd.Flags().String(\"queryTemplate\", \"\", \"String template to be used when applying the given query. Use %s to reference the query/pipeline input\")\n\tcmd.Flags().String(\"orderBy\", \"name\", \"Order by. e.g. _id asc or name asc or creationTime.date desc\")\n\tcmd.Flags().Bool(\"onlyInvisible\", false, \"Only include invisible smart groups\")\n\tcmd.Flags().Bool(\"onlyVisible\", false, \"Only include visible smart groups\")\n\tcmd.Flags().Bool(\"withParents\", false, \"Include a flat list of all parents and grandparents of the given object\")\n\n\tflags.WithOptions(\n\t\tcmd,\n\t\tflags.WithExtendedPipelineSupport(\"query\", \"query\", false, \"c8y_DeviceQueryString\"),\n\t)\n\n\t// Required flags\n\tccmd.SubCommand = subcommand.NewSubCommand(cmd)\n\n\treturn ccmd\n}", "func NewPluginListCommand(p *commands.KnParams) *cobra.Command {\n\tpluginFlags := PluginFlags{\n\t\tIOStreams: genericclioptions.IOStreams{\n\t\t\tIn: os.Stdin,\n\t\t\tOut: os.Stdout,\n\t\t\tErrOut: os.Stderr,\n\t\t},\n\t}\n\n\tpluginListCommand := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List all visible plugin executables\",\n\t\tLong: `List all visible plugin executables.\n\nAvailable plugin files are those that are:\n- executable\n- begin with \"kn-\n- anywhere on the path specified in Kn's config pluginDir variable, which:\n * can be overridden with the --plugin-dir flag`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := pluginFlags.complete(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = pluginFlags.run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tAddPluginFlags(pluginListCommand)\n\tBindPluginsFlagToViper(pluginListCommand)\n\n\tpluginFlags.AddPluginFlags(pluginListCommand)\n\n\treturn pluginListCommand\n}", "func newToDoList() toDoList {\n\treturn toDoList{}\n}", "func newListCmd(out io.Writer, errOut io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Lists various entities managed by the Ziti Edge Controller\",\n\t\tLong: \"Lists various entities managed by the Ziti Edge Controller\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := cmd.Help()\n\t\t\tcmdhelper.CheckErr(err)\n\t\t},\n\t}\n\n\tnewOptions := func() *edgeOptions {\n\t\treturn &edgeOptions{\n\t\t\tCommonOptions: common.CommonOptions{Out: out, Err: errOut},\n\t\t}\n\t}\n\n\tcmd.AddCommand(newListCmdForEntityType(\"api-sessions\", runListApiSessions, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"cas\", runListCAs, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"config-types\", runListConfigTypes, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"configs\", runListConfigs, newOptions()))\n\tcmd.AddCommand(newListEdgeRoutersCmd(newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"edge-router-policies\", runListEdgeRouterPolicies, newOptions(), \"erps\"))\n\tcmd.AddCommand(newListCmdForEntityType(\"terminators\", runListTerminators, newOptions()))\n\tcmd.AddCommand(newListIdentitiesCmd(newOptions()))\n\tcmd.AddCommand(newListServicesCmd(newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"service-edge-router-policies\", runListServiceEdgeRouterPolices, newOptions(), \"serps\"))\n\tcmd.AddCommand(newListCmdForEntityType(\"service-policies\", runListServicePolices, newOptions(), \"sps\"))\n\tcmd.AddCommand(newListCmdForEntityType(\"sessions\", runListSessions, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"transit-routers\", runListTransitRouters, newOptions()))\n\n\tcmd.AddCommand(newListCmdForEntityType(\"edge-router-role-attributes\", runListEdgeRouterRoleAttributes, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"identity-role-attributes\", runListIdentityRoleAttributes, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"service-role-attributes\", runListServiceRoleAttributes, newOptions()))\n\n\tcmd.AddCommand(newListCmdForEntityType(\"posture-checks\", runListPostureChecks, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"posture-check-types\", runListPostureCheckTypes, newOptions()))\n\n\tconfigTypeListRootCmd := newEntityListRootCmd(\"config-type\")\n\tconfigTypeListRootCmd.AddCommand(newSubListCmdForEntityType(\"config-type\", \"configs\", outputConfigs, newOptions()))\n\n\tedgeRouterListRootCmd := newEntityListRootCmd(\"edge-router\", \"er\")\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"edge-router-policies\", outputEdgeRouterPolicies, newOptions()))\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"service-edge-router-policies\", outputServiceEdgeRouterPolicies, newOptions()))\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"identities\", outputIdentities, newOptions()))\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"services\", outputServices, newOptions()))\n\n\tedgeRouterPolicyListRootCmd := newEntityListRootCmd(\"edge-router-policy\", \"erp\")\n\tedgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-router-policies\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\tedgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-router-policies\", \"identities\", outputIdentities, newOptions()))\n\n\tidentityListRootCmd := newEntityListRootCmd(\"identity\")\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"edge-router-policies\", outputEdgeRouterPolicies, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"service-policies\", outputServicePolicies, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"services\", outputServices, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"service-configs\", outputServiceConfigs, newOptions()))\n\n\tserviceListRootCmd := newEntityListRootCmd(\"service\")\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"configs\", outputConfigs, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"service-policies\", outputServicePolicies, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"service-edge-router-policies\", outputServiceEdgeRouterPolicies, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"terminators\", outputTerminators, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"identities\", outputIdentities, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\n\tserviceEdgeRouterPolicyListRootCmd := newEntityListRootCmd(\"service-edge-router-policy\", \"serp\")\n\tserviceEdgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-edge-router-policies\", \"services\", outputServices, newOptions()))\n\tserviceEdgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-edge-router-policies\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\n\tservicePolicyListRootCmd := newEntityListRootCmd(\"service-policy\", \"sp\")\n\tservicePolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-policies\", \"services\", outputServices, newOptions()))\n\tservicePolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-policies\", \"identities\", outputIdentities, newOptions()))\n\tservicePolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-policies\", \"posture-checks\", outputPostureChecks, newOptions()))\n\n\tcmd.AddCommand(newListCmdForEntityType(\"summary\", runListSummary, newOptions()))\n\n\tcmd.AddCommand(configTypeListRootCmd,\n\t\tedgeRouterListRootCmd,\n\t\tedgeRouterPolicyListRootCmd,\n\t\tidentityListRootCmd,\n\t\tserviceEdgeRouterPolicyListRootCmd,\n\t\tserviceListRootCmd,\n\t\tservicePolicyListRootCmd,\n\t)\n\n\treturn cmd\n}", "func (c *CodeShipProvider) GetBuildsList(uuid string) ([]Build, error) {\n\tres, _, err := c.API.ListBuilds(c.Context, uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar builds []Build\n\tfor _, build := range res.Builds {\n\t\tcommitMessage := build.CommitMessage\n\t\tif len(commitMessage) > 70 {\n\t\t\tcommitMessage = build.CommitMessage[:70]\n\t\t}\n\n\t\tstatus := fmt.Sprintf(\"[%s](fg-cyan)\", build.Status)\n\t\tif strings.Contains(build.Status, \"success\") {\n\t\t\tstatus = fmt.Sprintf(\"[%s](fg-green)\", build.Status)\n\t\t}\n\t\tif strings.Contains(build.Status, \"error\") {\n\t\t\tstatus = fmt.Sprintf(\"[%s](fg-red)\", \"failed\")\n\t\t}\n\n\t\tbuilds = append(builds, Build{\n\t\t\tStartedAt: build.AllocatedAt.Format(\"02/01/06 03:04:05\"),\n\t\t\tFinishedAt: build.FinishedAt.Format(\"02/01/06 03:04:05\"),\n\t\t\tCommitMessage: commitMessage,\n\t\t\tStatus: status,\n\t\t\tUsername: build.Username,\n\t\t})\n\t}\n\n\treturn builds, nil\n}", "func NewCredentialListCommand(io ui.IO, newClient newClientFunc) *CredentialListCommand {\n\treturn &CredentialListCommand{\n\t\tio: io,\n\t\tnewClient: newClient,\n\t}\n}", "func (c *Cluster) buildCommand(command []string, verbose bool) []string {\n\toptions := []string{}\n\tif c.KubeconfigFile != \"\" {\n\t\toptions = append(options, \"--kubeconfig\", c.KubeconfigFile)\n\t}\n\tif c.Context.ContextName != \"\" {\n\t\toptions = append(options, \"--context\", c.Context.ContextName)\n\t}\n\toptions = append(options, command...)\n\treturn options\n}", "func main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"golist\"\n\tapp.Usage = \"List Go project resources (built with Go ???)\"\n\tapp.Version = \"0.0.1\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringSliceFlag{\"ignore-dir, d\", nil, \"Directory to ignore\", \"\", false},\n\t\tcli.StringSliceFlag{\"ignore-tree, t\", nil, \"Directory tree to ignore\", \"\", false},\n\t\tcli.StringSliceFlag{\"ignore-regex, r\", nil, \"Regex specified files/dirs to ignore\", \"\", false},\n\t\tcli.StringFlag{\"package-path\", \"\", \"Package entry point\", \"\", nil, false},\n\t\tcli.BoolFlag{\"all-deps\", \"List imported packages including stdlib\", \"\", nil, false},\n\t\tcli.BoolFlag{\"provided\", \"List provided packages\", \"\", nil, false},\n\t\tcli.BoolFlag{\"imported\", \"List imported packages\", \"\", nil, false},\n\t\tcli.BoolFlag{\"skip-self\", \"Skip imported packages with the same --package-path\", \"\", nil, false},\n\t\tcli.BoolFlag{\"tests\", \"Apply the listing options over tests\", \"\", nil, false},\n\t\tcli.BoolFlag{\"show-main\", \"Including main files in listings\", \"\", nil, false},\n\t\tcli.BoolFlag{\"to-install\", \"List all resources recognized as essential part of the Go project\", \"\", nil, false},\n\t\tcli.StringSliceFlag{\"include-extension, e\", nil, \"Include all files with the extension in the recognized resources, e.g. .proto, .tmpl\", \"\", false},\n\t\tcli.BoolFlag{\"json\", \"Output as JSON artefact\", \"\", nil, false},\n\t}\n\n\tapp.Action = func(c *cli.Context) error {\n\n\t\tif c.String(\"package-path\") == \"\" {\n\t\t\treturn fmt.Errorf(\"--package-path is not set\")\n\t\t}\n\n\t\tif !c.Bool(\"provided\") && !c.Bool(\"imported\") && !c.Bool(\"to-install\") && !c.Bool(\"json\") {\n\t\t\treturn fmt.Errorf(\"At least one of --provided, --imported, --to-install or --json must be set\")\n\t\t}\n\n\t\tignore := &util.Ignore{}\n\n\t\tfor _, dir := range c.StringSlice(\"ignore-tree\") {\n\t\t\t// skip all ignored dirs that are prefixes of the package-path\n\t\t\tif strings.HasPrefix(c.String(\"package-path\"), dir) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tignore.Trees = append(ignore.Trees, dir)\n\t\t}\n\n\t\tfor _, dir := range c.StringSlice(\"ignore-dir\") {\n\t\t\t// skip all ignored dirs that are prefixes of the package-path\n\t\t\tif strings.HasPrefix(c.String(\"package-path\"), dir) && c.String(\"package-path\") != dir {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tignore.Dirs = append(ignore.Dirs, dir)\n\t\t}\n\n\t\tfor _, dir := range c.StringSlice(\"ignore-regex\") {\n\t\t\tignore.Regexes = append(ignore.Regexes, regexp.MustCompile(dir))\n\t\t}\n\n\t\tcollector := util.NewPackageInfoCollector(ignore, c.StringSlice(\"include-extension\"))\n\t\tif err := collector.CollectPackageInfos(c.String(\"package-path\")); err != nil {\n\t\t\treturn err\n\n\t\t}\n\n\t\tif c.Bool(\"json\") {\n\t\t\t// Collect everything\n\t\t\tartifact, _ := collector.BuildArtifact()\n\t\t\tstr, _ := json.Marshal(artifact)\n\t\t\tfmt.Printf(\"%v\\n\", string(str))\n\t\t\treturn nil\n\t\t}\n\n\t\tif c.Bool(\"provided\") {\n\t\t\tpkgs, err := collector.BuildPackageTree(c.Bool(\"show-main\"), c.Bool(\"tests\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsort.Strings(pkgs)\n\t\t\tfor _, item := range pkgs {\n\t\t\t\tfmt.Println(item)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif c.Bool(\"imported\") {\n\t\t\tpkgs, err := collector.CollectProjectDeps(c.Bool(\"all-deps\"), c.Bool(\"skip-self\"), c.Bool(\"tests\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsort.Strings(pkgs)\n\t\t\tfor _, item := range pkgs {\n\t\t\t\tfmt.Println(item)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif c.Bool(\"to-install\") {\n\t\t\tpkgs, err := collector.CollectInstalledResources()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsort.Strings(pkgs)\n\t\t\tfor _, item := range pkgs {\n\t\t\t\tfmt.Println(item)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n}", "func CommandList() error {\n\tcommon.LogInfo2Quiet(\"My Apps\")\n\tapps, err := common.DokkuApps()\n\tif err != nil {\n\t\tcommon.LogWarn(err.Error())\n\t\treturn nil\n\t}\n\n\tfor _, appName := range apps {\n\t\tcommon.Log(appName)\n\t}\n\n\treturn nil\n}", "func List(ctx *cli.Context) error {\n\tm := task.NewFileManager()\n\ttasks := m.GetAllOpenTasks()\n\n\ttasks = sortTasks(ctx.String(\"sort\"), tasks)\n\n\tfor _, v := range tasks {\n\t\tfmt.Println(v.String())\n\t}\n\treturn nil\n}", "func TestCmdList(t *testing.T) {\n\tassert := asrt.New(t)\n\torigDir, _ := os.Getwd()\n\n\tsite := TestSites[0]\n\terr := os.Chdir(site.Dir)\n\n\tglobalconfig.DdevGlobalConfig.SimpleFormatting = true\n\t_ = globalconfig.WriteGlobalConfig(globalconfig.DdevGlobalConfig)\n\n\tt.Cleanup(func() {\n\t\terr = os.Chdir(origDir)\n\t\tassert.NoError(err)\n\t\tglobalconfig.DdevGlobalConfig.SimpleFormatting = false\n\t\t_ = globalconfig.WriteGlobalConfig(globalconfig.DdevGlobalConfig)\n\t})\n\t// This gratuitous ddev start -a repopulates the ~/.ddev/global_config.yaml\n\t// project list, which has been damaged by other tests which use\n\t// direct app techniques.\n\t_, err = exec.RunHostCommand(DdevBin, \"start\", \"-a\", \"-y\")\n\tassert.NoError(err)\n\n\t// Execute \"ddev list\" and harvest plain text output.\n\tout, err := exec.RunHostCommand(DdevBin, \"list\", \"-W\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", out)\n\n\t// Execute \"ddev list -j\" and harvest the json output\n\tjsonOut, err := exec.RunHostCommand(DdevBin, \"list\", \"-j\")\n\tassert.NoError(err, \"error running ddev list -j: %v, output=%s\", jsonOut)\n\n\tsiteList := getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(len(TestSites), len(siteList), \"didn't find expected number of sites in list: %v\", siteList)\n\n\tfor _, v := range TestSites {\n\t\tapp, err := ddevapp.GetActiveApp(v.Name)\n\t\tassert.NoError(err)\n\n\t\t// Look for standard items in the regular ddev list output\n\t\tassert.Contains(string(out), v.Name)\n\t\ttestURL := app.GetHTTPSURL()\n\t\tif globalconfig.GetCAROOT() == \"\" {\n\t\t\ttestURL = app.GetHTTPURL()\n\t\t}\n\t\tassert.Contains(string(out), testURL)\n\t\tassert.Contains(string(out), app.GetType())\n\t\tassert.Contains(string(out), ddevapp.RenderHomeRootedDir(app.GetAppRoot()))\n\n\t\t// Look through list results in json for this site.\n\t\tfound := false\n\t\tfor _, listitem := range siteList {\n\t\t\titem, ok := listitem.(map[string]interface{})\n\t\t\tassert.True(ok)\n\t\t\t// Check to see that we can find our item\n\t\t\tif item[\"name\"] == v.Name {\n\t\t\t\tfound = true\n\t\t\t\tassert.Equal(app.GetHTTPURL(), item[\"httpurl\"])\n\t\t\t\tassert.Equal(app.GetHTTPSURL(), item[\"httpsurl\"])\n\t\t\t\tassert.Equal(app.Name, item[\"name\"])\n\t\t\t\tassert.Equal(app.GetType(), item[\"type\"])\n\t\t\t\tassert.EqualValues(ddevapp.RenderHomeRootedDir(app.GetAppRoot()), item[\"shortroot\"])\n\t\t\t\tassert.EqualValues(app.GetAppRoot(), item[\"approot\"])\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tassert.True(found, \"Failed to find project %s in ddev list -j\", v.Name)\n\n\t}\n\n\t// Now filter the list by the type of the first running test app\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-j\", \"--type\", TestSites[0].Type)\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, out)\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.GreaterOrEqual(len(siteList), 1)\n\n\t// Now filter the list by a not existing type\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-j\", \"--type\", \"not-existing-type\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, out)\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(0, len(siteList))\n\n\t// Stop the first app\n\tout, err = exec.RunHostCommand(DdevBin, \"stop\", TestSites[0].Name)\n\tassert.NoError(err, \"error running ddev stop %v: %v output=%s\", TestSites[0].Name, err, out)\n\n\t// Execute \"ddev list\" and harvest json output.\n\t// Now there should be one less active project in list\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-jA\", \"-W\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, jsonOut)\n\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(len(TestSites)-1, len(siteList))\n\n\t// Now list without -A, make sure we show all projects\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-j\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, out)\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(len(TestSites), len(siteList))\n\n\t// Leave firstApp running for other tests\n\tout, err = exec.RunHostCommand(DdevBin, \"start\", \"-y\", TestSites[0].Name)\n\tassert.NoError(err, \"error running ddev start: %v output=%s\", err, out)\n}", "func NewCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"The version of matryoshka\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tfmt.Println(BuildCommit)\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func newVersionCommands(globalOpts *globalOptions) *cobra.Command {\n\toptions := &versionOptions{\n\t\tglobalOptions: globalOpts,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print the CLI version information\",\n\t\tLong: versionDesc,\n\t\tExample: versionExample,\n\t\tArgs: cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn options.run()\n\t\t},\n\t}\n\n\toptions.addVersionFlags(cmd)\n\n\treturn cmd\n}", "func newWatchCommand(c *cli.Context) (Command, error) {\n\trepo, err := newRepositoryRequestInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &watchCommand{repo: repo, jsonPaths: c.StringSlice(\"jsonpath\"), streaming: c.Bool(\"streaming\")}, nil\n}", "func NewTasksCommand() *cobra.Command {\n\tcommand := &cobra.Command{\n\t\tUse: \"tasks\",\n\t\tShort: \"Task related option\",\n\t\tLong: \"Task related option, e.g. list tasks\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Usage()\n\t\t},\n\t}\n\n\tcommand.AddCommand(listTasksCommand())\n\n\treturn command\n}", "func NewCommand(ctx api.Context) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"node\",\n\t\tShort: \"Display DC/OS node information\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t_, ok := ctx.EnvLookup(cli.EnvStrictDeprecations)\n\t\t\tif !ok {\n\t\t\t\tctx.Deprecated(\"Getting the list of nodes from `dcos node` is deprecated. Please use `dcos node list`.\")\n\t\t\t\tlistCmd := newCmdNodeList(ctx)\n\t\t\t\t// Execute by default would use os.Args[1:], which is everything after `dcos ...`.\n\t\t\t\t// We need all command line arguments after `dcos node ...`.\n\t\t\t\tlistCmd.SetArgs(ctx.Args()[2:])\n\t\t\t\tlistCmd.SilenceErrors = true\n\t\t\t\tlistCmd.SilenceUsage = true\n\t\t\t\treturn listCmd.Execute()\n\t\t\t}\n\t\t\treturn cmd.Help()\n\t\t},\n\t}\n\tcmd.Flags().Bool(\"json\", false, \"Print in json format\")\n\tcmd.Flags().StringArray(\"field\", nil, \"Name of extra field to include in the output of `dcos node`. Can be repeated multiple times to add several fields.\")\n\n\tcmd.AddCommand(\n\t\tnewCmdNodeDecommission(ctx),\n\t\tnewCmdNodeDiagnostics(ctx),\n\t\tnewCmdNodeDNS(ctx),\n\t\tnewCmdNodeList(ctx),\n\t\tnewCmdNodeListComponents(ctx),\n\t\tnewCmdNodeLog(ctx),\n\t\tnewCmdNodeMetrics(ctx),\n\t\tnewCmdNodeSSH(ctx),\n\t)\n\treturn cmd\n}", "func (cli *bkCli) projectList(quietList bool) error {\n\n\tt := time.Now()\n\n\tprojects, err := cli.listProjects()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif quietList {\n\t\tfor _, proj := range projects {\n\t\t\tfmt.Printf(\"%-36s\\n\", *proj.ID)\n\t\t}\n\t\treturn nil // we are done\n\t}\n\n\ttb := table.New(projectColumns)\n\tvals := make(map[string]interface{})\n\n\tfor _, proj := range projects {\n\t\tif proj.FeaturedBuild != nil {\n\t\t\tfb := proj.FeaturedBuild\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, *fb.Number, toString(fb.Branch), toString(fb.Message), toString(fb.State), valString(fb.FinishedAt)})\n\t\t} else {\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, 0, \"\", \"\", \"\", \"\"})\n\t\t}\n\t\ttb.AddRow(vals)\n\t}\n\ttb.Markdown = true\n\ttb.Print()\n\n\tfmt.Printf(\"\\nTime taken: %s\\n\", time.Now().Sub(t))\n\n\treturn err\n}", "func NewVersionCommand(version string, buildDate string, out io.Writer) *cobra.Command {\n\tversionCmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"display the current version\",\n\t\tLong: \"display the current version\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Fprintf(out, \"Primes Worker:\\n\")\n\t\t\tfmt.Fprintf(out, \" Version: %s\\n\", version)\n\t\t\tfmt.Fprintf(out, \" Built: %s\\n\", buildDate)\n\t\t\tfmt.Fprintf(out, \" Go Version: %s\\n\", runtime.Version())\n\t\t},\n\t}\n\n\treturn versionCmd\n}", "func NewIOCStreamListCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tAliases: []string{\"il\"},\n\t\tUse: \"list\",\n\t\tShort: \"List IoCs from notifications\",\n\t\tExample: iocStreamListCmdExamples,\n\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tp, err := NewPrinter(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn p.PrintCollection(vt.URL(\"ioc_stream\"))\n\t\t},\n\t}\n\n\taddIncludeExcludeFlags(cmd.Flags())\n\taddIDOnlyFlag(cmd.Flags())\n\taddFilterFlag(cmd.Flags())\n\taddLimitFlag(cmd.Flags())\n\taddCursorFlag(cmd.Flags())\n\n\treturn cmd\n}", "func buildQueue(c *cli.Context) error {\n\n\tclient, err := newClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilds, err := client.BuildQueue()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(builds) == 0 {\n\t\tfmt.Println(\"there are no pending or running builds\")\n\t\treturn nil\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, build := range builds {\n\t\ttmpl.Execute(os.Stdout, build)\n\t}\n\treturn nil\n}", "func (o ClusterBuildStrategySpecBuildStepsOutput) Command() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildSteps) []string { return v.Command }).(pulumi.StringArrayOutput)\n}", "func NewBuildCommand() *Command {\n\treturn &Command{\n\t\tGetManifest: model.GetManifestV2,\n\t\tBuilder: &build.OktetoBuilder{},\n\t\tRegistry: registry.NewOktetoRegistry(okteto.Config{}),\n\t}\n}", "func NewVersionCommand(streams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print the version information for kubectl trace\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\t\t\tfmt.Fprintln(streams.Out, version.String())\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn cmd\n}", "func List(ctx *cli.Context) error {\n\targs := &listArgs{}\n\targs.Parse(ctx)\n\n\tmanager := yata.NewTaskManager()\n\ttasks, err := manager.GetAll()\n\thandleError(err)\n\n\tif args.showTags {\n\t\treturn displayTags(tasks)\n\t}\n\n\ttasks = yata.FilterTasks(tasks, func(t yata.Task) bool {\n\t\treturn (args.tag == \"\" || sliceContains(t.Tags, args.tag)) &&\n\t\t\t(args.description == \"\" || strings.Contains(t.Description, args.description)) &&\n\t\t\t(args.all || !t.Completed)\n\t})\n\n\tsortTasks(args.sort, &tasks)\n\n\tfor _, v := range tasks {\n\t\tstringer := yata.NewTaskStringer(v, taskStringer(args.format))\n\t\tswitch v.Priority {\n\t\tcase yata.LowPriority:\n\t\t\tyata.PrintlnColor(\"cyan+h\", stringer.String())\n\t\tcase yata.HighPriority:\n\t\t\tyata.PrintlnColor(\"red+h\", stringer.String())\n\t\tdefault:\n\t\t\tyata.Println(stringer.String())\n\t\t}\n\t}\n\n\treturn nil\n}", "func newCoverageList(name string) *CoverageList {\n\treturn &CoverageList{\n\t\tCoverage: &Coverage{Name: name},\n\t\tGroup: []Coverage{},\n\t}\n}", "func NewCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Version for apisix-mesh-agent\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Println(version.String())\n\t\t},\n\t}\n\treturn cmd\n}", "func (*ListCmd) Name() string { return \"list\" }", "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 RunGoList(cwd string, goExec string) (*GoListCmd, error) {\n\t/*\tcmd, err := GetGoExecutable()\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Msg(\"`which go` failed\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdefer cmd.ReadCloser().Close()\n\t\tbuf := new(bytes.Buffer)\n\t\tbuf.ReadFrom(cmd.ReadCloser())\n\t\ts := strings.TrimSpace(buf.String())\n\t\tlog.Info().Msg(\"Found go executable \" + s)\n\n\t\t// Wait for the `go list` command to complete.\n\t\t//if err := cmd.Wait(); err != nil {\n\t\t//\treturn nil, fmt.Errorf(\"%v: `go list` failed, use `go mod tidy` to known more\", err)\n\t\t//}\n\t*/\n\tgoList := exec.Command(goExec, \"list\", \"-json\", \"-deps\", \"-mod=readonly\", \"./...\")\n\tgoList.Dir = cwd\n\toutput, err := goList.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = goList.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GoListCmd{cmd: goList, output: output}, nil\n}", "func (c *Client) BuildListRequest(ctx context.Context, v interface{}) (*http.Request, error) {\n\tu := &url.URL{Scheme: c.scheme, Host: c.host, Path: ListLogPath()}\n\treq, err := http.NewRequest(\"POST\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, goahttp.ErrInvalidURL(\"log\", \"list\", u.String(), err)\n\t}\n\tif ctx != nil {\n\t\treq = req.WithContext(ctx)\n\t}\n\n\treturn req, nil\n}", "func buildCommand() *command {\n\n\tres := &command{\n\t\tType: \"\",\n\t\tArgs: make([]string,0),\n\t}\n\tvar tmpCount = 0\n\n\tfor _, p := range os.Args {\n\t\t// Remove the empty args (I have no idea why they appear)\n\t\tpTrim := strings.Trim(p, \" \")\n\t\tif pTrim != \"\" {\n\t\t\tif tmpCount==1 {\n\t\t\t\tres.Type = pTrim\n\t\t\t} else if tmpCount > 1 {\n\t\t\t\tres.Args = append(res.Args, pTrim)\n\t\t\t}\n\t\t\ttmpCount += 1\n\t\t}\n\n\t}\n\treturn res\n}", "func newLogsCommand(dockerCli *command.DockerCli) *cobra.Command {\n\tvar opts logsOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"logs [OPTIONS] SERVICE|TASK\",\n\t\tShort: \"Fetch the logs of a service or task\",\n\t\tArgs: cli.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.target = args[0]\n\t\t\treturn runLogs(dockerCli, &opts)\n\t\t},\n\t\tTags: map[string]string{\"version\": \"1.29\"},\n\t}\n\n\tflags := cmd.Flags()\n\t// options specific to service logs\n\tflags.BoolVar(&opts.noResolve, \"no-resolve\", false, \"Do not map IDs to Names in output\")\n\tflags.BoolVar(&opts.noTrunc, \"no-trunc\", false, \"Do not truncate output\")\n\tflags.BoolVar(&opts.noTaskIDs, \"no-task-ids\", false, \"Do not include task IDs in output\")\n\t// options identical to container logs\n\tflags.BoolVarP(&opts.follow, \"follow\", \"f\", false, \"Follow log output\")\n\tflags.StringVar(&opts.since, \"since\", \"\", \"Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)\")\n\tflags.BoolVarP(&opts.timestamps, \"timestamps\", \"t\", false, \"Show timestamps\")\n\tflags.StringVar(&opts.tail, \"tail\", \"all\", \"Number of lines to show from the end of the logs\")\n\treturn cmd\n}", "func (r *ConfigAuditReportReconciler) buildCommand(workloadInfo string) string {\n\tworkloadInfos := strings.Split(workloadInfo, \"|\")\n\tworkloadType := workloadInfos[0]\n\tworkloadName := workloadInfos[1]\n\n\treturn \"starboard -n \" + r.NamespaceWatched + \" get report \" + workloadType + \"/\" + workloadName + \" > \" + buildReportName(workloadType, workloadName)\n}", "func List(g *types.Cmd) {\n\tg.AddOptions(\"list\")\n}", "func NewVersionCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Prints out build version information\",\n\t\tLong: \"Prints out build version information\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Printf(`Version: %v\nGitRevision: %v\nGolangVersion: %v\n`,\n\t\t\t\tversion.VelaVersion,\n\t\t\t\tversion.GitRevision,\n\t\t\t\truntime.Version())\n\t\t},\n\t\tAnnotations: map[string]string{\n\t\t\ttypes.TagCommandType: types.TypePlugin,\n\t\t},\n\t}\n}" ]
[ "0.7019383", "0.6365712", "0.62861466", "0.62341", "0.61762345", "0.61427575", "0.61323035", "0.6077577", "0.5928921", "0.5884531", "0.5867837", "0.58048195", "0.57902944", "0.5639388", "0.56278795", "0.5610364", "0.5604566", "0.5572504", "0.5563013", "0.5516337", "0.5463784", "0.53819853", "0.5374539", "0.5358723", "0.5335075", "0.5335038", "0.53340995", "0.5330123", "0.53161705", "0.53125745", "0.53116715", "0.5279986", "0.5258267", "0.52562475", "0.52452123", "0.5242123", "0.52360404", "0.522759", "0.51760197", "0.5172501", "0.51219815", "0.5116296", "0.51076245", "0.50990605", "0.5092991", "0.5085276", "0.5081948", "0.50472045", "0.50470734", "0.5016907", "0.50108117", "0.4986524", "0.49763098", "0.4968389", "0.49600077", "0.4940333", "0.49158987", "0.49150267", "0.49126428", "0.49066848", "0.49010822", "0.48973688", "0.48954648", "0.48804632", "0.48656738", "0.48655567", "0.48426756", "0.4831766", "0.48285446", "0.48267525", "0.48182085", "0.48180008", "0.48157522", "0.48048842", "0.4797872", "0.47942373", "0.47834358", "0.4781776", "0.47800523", "0.4774863", "0.4770705", "0.47676185", "0.47654304", "0.47442225", "0.47384718", "0.47345516", "0.47259223", "0.4700326", "0.46934322", "0.4691185", "0.46907145", "0.46883285", "0.46854192", "0.4680708", "0.46730512", "0.46463877", "0.4645619", "0.46405783", "0.46384573", "0.46337977" ]
0.8401678
0
Bind a `RunnableWithContext` to this runner. WARNING: invoking it when state is StateRunning may cause blocked.
Привяжите `RunnableWithContext` к этому запускатору. ВАЖНО: вызов при состоянии StateRunning может привести к блокировке.
func (s *DeterminationWithContext) Bind(ctx context.Context, runnable RunnableWithContext) *DeterminationWithContext { defer s.lock.Unlock() /*_*/ s.lock.Lock() s.rctx = ctx s.runn = runnable return s }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (tx *WriteTx) RunWithContext(ctx context.Context) error {\n\tif tx.err != nil {\n\t\treturn tx.err\n\t}\n\tinput, err := tx.input()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = retry(ctx, func() error {\n\t\tout, err := tx.db.client.TransactWriteItemsWithContext(ctx, input)\n\t\tif tx.cc != nil && out != nil {\n\t\t\tfor _, cc := range out.ConsumedCapacity {\n\t\t\t\taddConsumedCapacity(tx.cc, cc)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\treturn err\n}", "func (r *Retry) RunWithContext(\n\tctx context.Context, funcToRetry func(context.Context) (interface{}, error),\n) (interface{}, error) {\n\t// create a random source which is used in setting the jitter\n\n\tattempts := 0\n\tfor {\n\t\t// run the function\n\t\tresult, err := funcToRetry(ctx)\n\t\t// no error, then we are done!\n\t\tif err == nil {\n\t\t\treturn result, nil\n\t\t}\n\t\t// max retries is reached return the error\n\t\tattempts++\n\t\tif attempts == r.maxTries {\n\t\t\treturn nil, err\n\t\t}\n\t\t// wait for the next duration or context canceled|time out, whichever comes first\n\t\tt := time.NewTimer(getNextBackoff(attempts, r.initialDelay, r.maxDelay))\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\t// nothing to be done as the timer is killed\n\t\tcase <-ctx.Done():\n\t\t\t// context cancelled, kill the timer if it is not killed, and return the last error\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t}\n}", "func (e *executor) RunWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\tvar out bytes.Buffer\n\n\tprefix := color.BlueString(cmd.Args[0])\n\tlogger := e.logger.WithContext(log.ContextWithPrefix(prefix))\n\n\tcmd.Stdout = io.MultiWriter(&out, log.LineWriter(logger.Info))\n\tcmd.Stderr = io.MultiWriter(&out, log.LineWriter(logger.Error))\n\n\treturn e.run(ctx, &out, cmd)\n}", "func runWithContext(fun func(ctx context.Context) error) (context.CancelFunc, chan error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(done)\n\t\tdone <- fun(ctx)\n\t}()\n\n\treturn cancel, done\n}", "func RunWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\treturn DefaultExecutor.RunWithContext(ctx, cmd)\n}", "func (ttl *UpdateTTL) RunWithContext(ctx context.Context) error {\n\tinput := ttl.input()\n\n\terr := retry(ctx, func() error {\n\t\t_, err := ttl.table.db.client.UpdateTimeToLiveWithContext(ctx, input)\n\t\treturn err\n\t})\n\treturn err\n}", "func (m *MinikubeRunner) RunWithContext(ctx context.Context, cmdStr string, wait ...bool) (string, string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s \", m.Profile)\n\tcmdStr = profileArg + cmdStr\n\tcmdArgs := strings.Split(cmdStr, \" \")\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.CommandContext(ctx, path, cmdArgs...)\n\tLogf(\"RunWithContext: %s\", cmd.Args)\n\treturn m.teeRun(cmd, wait...)\n}", "func (dtw *describeTTLWrap) RunWithContext(ctx aws.Context) (dynamo.TTLDescription, error) {\n\treturn dtw.describeTTL.RunWithContext(ctx)\n}", "func (p *Pipeline) RunWithContext(ctx context.Context, cancel context.CancelFunc) {\n\tif p.err != nil {\n\t\treturn\n\t}\n\tp.ctx, p.cancel = ctx, cancel\n\tdataSize := p.source.Prepare(p.ctx)\n\tfilteredSize := dataSize\n\tfor index := 0; index < len(p.nodes); {\n\t\tif p.nodes[index].Begin(p, index, &filteredSize) {\n\t\t\tindex++\n\t\t} else {\n\t\t\tp.nodes = append(p.nodes[:index], p.nodes[index+1:]...)\n\t\t}\n\t}\n\tif p.err != nil {\n\t\treturn\n\t}\n\tif len(p.nodes) > 0 {\n\t\tfor index := 0; index < len(p.nodes)-1; {\n\t\t\tif p.nodes[index].TryMerge(p.nodes[index+1]) {\n\t\t\t\tp.nodes = append(p.nodes[:index+1], p.nodes[index+2:]...)\n\t\t\t} else {\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t\tfor index := len(p.nodes) - 1; index >= 0; index-- {\n\t\t\tif _, ok := p.nodes[index].(*strictordnode); ok {\n\t\t\t\tfor index = index - 1; index >= 0; index-- {\n\t\t\t\t\tswitch node := p.nodes[index].(type) {\n\t\t\t\t\tcase *seqnode:\n\t\t\t\t\t\tnode.kind = Ordered\n\t\t\t\t\tcase *lparnode:\n\t\t\t\t\t\tnode.makeOrdered()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif dataSize < 0 {\n\t\t\tp.finalizeVariableBatchSize()\n\t\t\tfor seqNo, batchSize := 0, p.batchInc; p.source.Fetch(batchSize) > 0; seqNo, batchSize = seqNo+1, p.nextBatchSize(batchSize) {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tbatchSize := ((dataSize - 1) / p.NofBatches(0)) + 1\n\t\t\tif batchSize == 0 {\n\t\t\t\tbatchSize = 1\n\t\t\t}\n\t\t\tfor seqNo := 0; p.source.Fetch(batchSize) > 0; seqNo++ {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range p.nodes {\n\t\tnode.End()\n\t}\n\tif p.err == nil {\n\t\tp.err = p.source.Err()\n\t}\n}", "func withContext(borrower ContextBorrower, worker Worker) Worker {\n\n\treturn func(t *T, _ Context) {\n\n\t\tif t.Failed() {\n\t\t\treturn\n\t\t}\n\n\t\tctx, release, err := borrower.Borrow()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s\", err)\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tdefer release()\n\t\tworkerRunner(nil, worker, t, ctx)\n\t}\n}", "func (h *Handler) BindContext(ctx context.Context, server core.Server) {\n\tswitch s := server.(type) {\n\tcase *http.Server:\n\t\ts.Handler = h\n\t\ts.BaseContext = func(l net.Listener) context.Context {\n\t\t\treturn ctx\n\t\t}\n\tcase *fasthttp.Server:\n\t\ts.Handler = h.ServeFastHTTP\n\t}\n}", "func (c *Consumer) ListenWithContext(ctx context.Context, fn MessageProcessor) {\n\tc.consume(ctx)\n\tvar wg sync.WaitGroup\n\tdefer wg.Wait()\n\n\tfor {\n\t\tmsg, ok := <-c.messages\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tc.Stats.AddDelivered(1)\n\t\t// For simplicity, did not do the pipe of death here. If POD is received, we may deliver a\n\t\t// couple more messages (especially since select is random in which channel is read from).\n\t\tc.concurrencySem <- empty{}\n\t\twg.Add(1)\n\t\tgo func(msg *Message) {\n\t\t\tdefer func() {\n\t\t\t\t<-c.concurrencySem\n\t\t\t}()\n\t\t\tstart := time.Now()\n\t\t\tfn(msg)\n\t\t\tc.Stats.UpdateProcessedDuration(time.Since(start))\n\t\t\tc.Stats.AddProcessed(1)\n\t\t\twg.Done()\n\t\t}(msg)\n\t}\n}", "func AddServantWithContext(v dispatch, f interface{}, obj string) {\n\taddServantCommon(v, f, obj, true)\n}", "func (p *Pipeline) RunWithContext(ctx context.Context, cancel context.CancelFunc) {\n\tif p.err != nil {\n\t\treturn\n\t}\n\tp.ctx, p.cancel = ctx, cancel\n\tdataSize := p.source.Prepare(p.ctx)\n\tfilteredSize := dataSize\n\tfor index := 0; index < len(p.nodes); {\n\t\tif p.nodes[index].Begin(p, index, &filteredSize) {\n\t\t\tindex++\n\t\t} else {\n\t\t\tp.nodes = append(p.nodes[:index], p.nodes[index+1:]...)\n\t\t}\n\t}\n\tif p.err != nil {\n\t\treturn\n\t}\n\tif len(p.nodes) > 0 {\n\t\tfor index := 0; index < len(p.nodes)-1; {\n\t\t\tif p.nodes[index].TryMerge(p.nodes[index+1]) {\n\t\t\t\tp.nodes = append(p.nodes[:index+1], p.nodes[index+2:]...)\n\t\t\t} else {\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t\tif dataSize < 0 {\n\t\t\tfor seqNo, batchSize := 0, batchInc; p.source.Fetch(batchSize) > 0; seqNo, batchSize = seqNo+1, nextBatchSize(batchSize) {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tbatchSize := ((dataSize - 1) / p.NofBatches(0)) + 1\n\t\t\tif batchSize == 0 {\n\t\t\t\tbatchSize = 1\n\t\t\t}\n\t\t\tfor seqNo := 0; p.source.Fetch(batchSize) > 0; seqNo++ {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range p.nodes {\n\t\tnode.End()\n\t}\n}", "func (s *Stmt) BindContext(ctx context.Context, args ...interface{}) *Query {\n\treturn &Query{\n\t\tctx: ctx,\n\t\texecer: s.middleware(stmtExecer{s.stmt}),\n\t\tquery: s.sql,\n\t\targs: args,\n\t}\n}", "func NewServerWithContext(ctx context.Context) *Server {\n\treturn &Server{\n\t\tctx: ctx,\n\t\tmaxIdleConns: 1024,\n\t\terrHandler: ignoreErrorHandler,\n\t}\n}", "func (s *SizedWaitGroup) AddWithContext(ctx context.Context) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase s.current <- struct{}{}:\n\t\tbreak\n\t}\n\ts.wg.Add(1)\n\treturn nil\n}", "func CrtlnWithContext(ctx context.Context, args ...interface{}) {\n\ts := fmt.Sprintln(args...)\n\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tcreticaldeps(hub.CaptureMessage, 3, s)\n\t\treturn\n\t}\n\n\tcreticaldeps(sentry.CaptureMessage, 3, s)\n}", "func (s *Supervisor) StartWithContext(ctx context.Context) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\tgo func() {\n\t\t<-s.shutdown\n\t\ts.logger(Info, nil, \"supervisor ordered to shutdown\")\n\t\tcancel()\n\t}()\n\n\terrChan := make(chan error)\n\twg := sync.WaitGroup{}\n\tfor name := range s.processes {\n\t\twg.Add(1)\n\n\t\tprocess := s.processes[name]\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\ts.logger(Warn, loggerData{\"cause\": err, \"name\": process.Name()}, \"runner terminated due a panic\")\n\t\t\t\t}\n\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t\tif err := process.Run(ctx); err != nil {\n\t\t\t\terrChan <- err\n\t\t\t}\n\t\t}()\n\t}\n\n\tgo func() {\n\t\tfor range errChan {\n\t\t\tswitch s.policy.Failure.Policy {\n\t\t\tcase shutdown:\n\t\t\t\ts.logger(Warn, nil, \"under configured failure policy, supervisor will shutdown\")\n\t\t\t\tcancel()\n\t\t\tcase ignore:\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}", "func BindContext(hndl http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tprint(\"Binding context\\n\")\n\t\tctx := OpenCtx(req)\n\t\tprint(\"BindContext: \", ctx, \"\\n\")\n\n\t\tdefer closeCtx(req)\n\t\thndl.ServeHTTP(w, req)\n\t})\n}", "func PerformWithContext(ctx context.Context, input *PerformInput) (*PerformOutput, error) {\n\toutput := make(chan *PerformOutput)\n\n\tnewCtx := withContext(ctx)\n\n\tgo run(newCtx, input, output)\n\n\tfor {\n\t\tselect {\n\t\tcase out := <-output:\n\t\t\treturn out, nil\n\t\tcase <-newCtx.Done():\n\t\t\treturn nil, newCtx.Err()\n\t\t}\n\t}\n}", "func (tx *GetTx) RunWithContext(ctx context.Context) error {\n\tinput, err := tx.input()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar resp *dynamodb.TransactGetItemsOutput\n\terr = retry(ctx, func() error {\n\t\tvar err error\n\t\tresp, err = tx.db.client.TransactGetItemsWithContext(ctx, input)\n\t\tif tx.cc != nil && resp != nil {\n\t\t\tfor _, cc := range resp.ConsumedCapacity {\n\t\t\t\taddConsumedCapacity(tx.cc, cc)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isResponsesEmpty(resp.Responses) {\n\t\treturn ErrNotFound\n\t}\n\treturn tx.unmarshal(resp)\n}", "func CrtlfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tcreticaldeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\tcreticaldeps(sentry.CaptureMessage, 3, format, args...)\n}", "func RunContext(ctx context.Context, routine func(context.Context)) {\n\tdoRun(ctx, routine)\n}", "func (e *executor) RunSilentlyWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\tvar buf bytes.Buffer\n\n\tcmd.Stdout = &buf\n\tcmd.Stderr = &buf\n\n\treturn e.run(ctx, &buf, cmd)\n}", "func RunContext(h http.Handler, ctx context.Context) {\n\tsrv := createServer(h)\n\tgo gracefullyShutDownOnSignal(srv, ctx)\n\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\tlog.Fatalf(\"Unable to to start server: %v\", err)\n\t}\n}", "func (s *DeterminationWithContext) Run() (err error) {\n\treturn s.run(s.prepare, s.booting, s.running, s.trigger, s.closing)\n}", "func WarnfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\twarndeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\twarndeps(sentry.CaptureMessage, 3, format, args...)\n}", "func ExecuteWithContext(ctx context.Context, eval Evaluator) (interface{}, error) {\n\ttype Result struct {\n\t\tI interface{}\n\t\tE error\n\t}\n\tch := make(chan Result, 1)\n\tgo func() {\n\t\ti, e := eval(ctx)\n\t\tch <- Result{I: i, E: e}\n\t\tclose(ch)\n\t}()\n\tselect {\n\tcase r := <-ch:\n\t\treturn r.I, r.E\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}", "func (d *DescribeTTL) RunWithContext(ctx context.Context) (TTLDescription, error) {\n\tinput := d.input()\n\n\tvar result *dynamodb.DescribeTimeToLiveOutput\n\terr := retry(ctx, func() error {\n\t\tvar err error\n\t\tresult, err = d.table.db.client.DescribeTimeToLiveWithContext(ctx, input)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn TTLDescription{}, err\n\t}\n\n\tdesc := TTLDescription{\n\t\tStatus: TTLDisabled,\n\t}\n\tif result.TimeToLiveDescription.TimeToLiveStatus != nil {\n\t\tdesc.Status = TTLStatus(*result.TimeToLiveDescription.TimeToLiveStatus)\n\t}\n\tif result.TimeToLiveDescription.AttributeName != nil {\n\t\tdesc.Attribute = *result.TimeToLiveDescription.AttributeName\n\t}\n\treturn desc, nil\n}", "func (s *Service) BindContext(ctx context.Context, server Server) error {\n\tserverType := reflect.TypeOf(server)\n\tif value, ok := serverTypes.Load(serverType); ok {\n\t\tnames := value.([]string)\n\t\tfor _, name := range names {\n\t\t\ts.handlers[name].BindContext(ctx, server)\n\t\t}\n\t\treturn nil\n\t}\n\treturn UnsupportedServerTypeError{serverType}\n}", "func runWithContextCheck(ctx context.Context, action func(ctx context.Context) error) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\terr := action(ctx)\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\treturn err\n}", "func ExecuteWithContext(ctx context.Context, s string, obj interface{}, settings ...SettingsFunc) *exec.Cmd {\n\tr := DefaultRunner()\n\treturn r.ExecuteWithContext(ctx, s, obj, settings...)\n}", "func NewAgentRunEWithContext(initialize InitializeFunc, cmd *cobra.Command, ctx context.Context) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\n\t\tcfg, err := NewAgentConfig(cmd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsensuAgent, err := initialize(ctx, cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn sensuAgent.Run(ctx)\n\t}\n}", "func SetTimeoutWithContext(ctx context.Context, callback func(), delay time.Duration) func() {\n\tchildCtx, cancel := context.WithCancel(ctx)\n\ttimer := time.NewTimer(delay)\n\tgo func(f func()) {\n\t\tselect {\n\t\tcase <-childCtx.Done():\n\t\t\treturn\n\t\tcase <-timer.C:\n\t\t\tf()\n\t\t}\n\t}(callback)\n\treturn cancel\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func runSonobuoyCommandWithContext(ctx context.Context, t *testing.T, args string) (error, bytes.Buffer, bytes.Buffer) {\n\tvar stdout, stderr bytes.Buffer\n\n\tcommand := exec.CommandContext(ctx, sonobuoy, strings.Fields(args)...)\n\tcommand.Stdout = &stdout\n\tcommand.Stderr = &stderr\n\n\tt.Logf(\"Running %q\\n\", command.String())\n\n\treturn command.Run(), stdout, stderr\n}", "func (obj *ConfigWriter) AddServantWithContext(imp impConfigWriterWithContext, objStr string) {\n\ttars.AddServantWithContext(obj, imp, objStr)\n}", "func (c *Context) Bind(out interface{}) error {\n\tif err := c.Context.Bind(out); err != nil {\n\t\tc.JSON400Msg(400, fmt.Sprintf(\"invalid request parameters, details: \\n%v\", err))\n\t\treturn err\n\t}\n\treturn nil\n}", "func RunSilentlyWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\treturn DefaultExecutor.RunSilentlyWithContext(ctx, cmd)\n}", "func NewWithContext(ctx context.Context) (interfaces.AsyncWork, error) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\taw := &asyncWorkImpl{\n\t\tqueue: queue.New(),\n\t\tqueueMutex: &sync.RWMutex{},\n\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\n\t\tevent: syncevent.NewSyncEvent(false),\n\n\t\terrorChs: []chan error{},\n\t\terrorChsMutex: &sync.RWMutex{},\n\n\t\tlastExecutionMap: map[string]time.Time{},\n\t\tlastExecutionMapMutex: &sync.RWMutex{},\n\n\t\tthrottleLastMap: map[string]*jobImpl{},\n\t\tthrottleLastMapMutex: &sync.RWMutex{},\n\t}\n\n\treturn aw, nil\n}", "func (blk *Block) DrawWithContext(d Drawable, ctx DrawContext) error {\n\tblocks, _, err := d.GeneratePageBlocks(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(blocks) != 1 {\n\t\treturn errors.New(\"too many output blocks\")\n\t}\n\n\tfor _, newBlock := range blocks {\n\t\tif err := blk.mergeBlocks(newBlock); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func WarningfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\twarndeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\twarndeps(sentry.CaptureMessage, 3, format, args...)\n}", "func (_obj *DataService) AddServantWithContext(imp _impDataServiceWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func InfolnWithContext(ctx context.Context, args ...interface{}) {\n\ts := fmt.Sprintln(args...)\n\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tinfodeps(hub.CaptureMessage, 3, s)\n\t\treturn\n\t}\n\n\tinfodeps(sentry.CaptureMessage, 3, s)\n}", "func ErrfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\terrdeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\terrdeps(sentry.CaptureMessage, 3, format, args...)\n}", "func RawWithContext(ctx context.Context, cmd string, options ...types.Option) (string, error) {\n\treturn command(ctx, cmd, options...)\n}", "func (_obj *LacService) AddServantWithContext(imp _impLacServiceWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func NewWithContext(ctx context.Context, workers, capacity int) (Interface, context.Context) {\n\tctx, cancel := context.WithCancel(ctx)\n\ti := &impl{\n\t\tcancel: cancel,\n\t\tworkCh: make(chan func() error, capacity),\n\t}\n\n\t// Start a go routine for each worker, which:\n\t// 1. reads off of the work channel,\n\t// 2. (optionally) sets the error as the result,\n\t// 3. marks work as done in our sync.WaitGroup.\n\tfor idx := 0; idx < workers; idx++ {\n\t\tgo func() {\n\t\t\tfor work := range i.workCh {\n\t\t\t\ti.exec(work)\n\t\t\t}\n\t\t}()\n\t}\n\treturn i, ctx\n}", "func retryWithContext(ctx context.Context, targetFunc retryableFunc, delay time.Duration) error {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t\tcontinueRetrying, err := targetFunc()\n\t\t\tif !continueRetrying {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttime.Sleep(delay) //delay between retries\n\t\t}\n\t}\n}", "func (c *Client) SubscribeRawWithContext(ctx context.Context, handler func(msg *Event)) error {\n\treturn c.SubscribeWithContext(ctx, \"\", handler)\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBSnapshotAttributeWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBSnapshotAttributeWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBSnapshotAttributeWithContext), varargs...)\n}", "func (_obj *Apichannels) AddServantWithContext(imp _impApichannelsWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func (bf *BuiltInFunc) Bind(instance *LoxInstance) Callable {\n\tbf.instance = instance\n\t// return itself.\n\treturn bf\n}", "func (_obj *Apilangpack) AddServantWithContext(imp _impApilangpackWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func NewTickerWithContext(ctx context.Context, d time.Duration) *Ticker {\n\tt := NewTicker(d)\n\tif ctx.Done() != nil {\n\t\tgo func() {\n\t\t\t<-ctx.Done()\n\t\t\tt.Stop()\n\t\t}()\n\t}\n\treturn t\n}", "func (r *StreamingRuntime) ExecWithContext(\n\tctx context.Context,\n\tcontainerID string,\n\tcmd []string,\n\tin io.Reader,\n\tout, errw io.WriteCloser,\n\ttty bool,\n\tresize <-chan remotecommand.TerminalSize,\n\ttimeout time.Duration,\n) error {\n\tcontainer, err := libdocker.CheckContainerStatus(r.Client, containerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn r.ExecHandler.ExecInContainer(\n\t\tctx,\n\t\tr.Client,\n\t\tcontainer,\n\t\tcmd,\n\t\tin,\n\t\tout,\n\t\terrw,\n\t\ttty,\n\t\tresize,\n\t\ttimeout,\n\t)\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBInstanceWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBInstanceWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBInstanceWithContext), varargs...)\n}", "func ForWithContext(c context.Context, begin int, end int, f ForLoop) {\n\tlength := end - begin\n\n\tif length > 0 {\n\t\tctx, cacnel := context.WithCancel(c)\n\t\tgo doLoop(cacnel, begin, end, f)\n\t\t<-ctx.Done()\n\t}\n}", "func WithEvalContext[T any](ctx context.Context, state T, f func(ctx context.Context, state T) error) error {\r\n\t_, ok := ctxutil.Value(ctx, (*exprEvaluator)(nil)).(*exprEvaluator)\r\n\tif !ok {\r\n\t\teev := exprEvaluators.Get()\r\n\t\tdefer exprEvaluators.Put(eev)\r\n\t\tee := eev.(*exprEvaluator)\r\n\t\tctx = ctxutil.WithValue(ctx, ee.ContextKey(), eev)\r\n\t}\r\n\treturn f(ctx, state)\r\n}", "func PipeWithContext(\n\tctx context.Context,\n\tsamplesPerSecond uint,\n\tformat SampleFormat,\n) (PipeReader, PipeWriter) {\n\tctx, cancel := context.WithCancel(ctx)\n\tp := &pipe{\n\t\tcontext: ctx,\n\t\tcancel: cancel,\n\t\tformat: format,\n\t\tsamplesPerSecond: samplesPerSecond,\n\t\tsamplesCh: make(chan Samples),\n\t\treadSamplesCh: make(chan int),\n\t}\n\treturn p, p\n}", "func (ctx *Context) BindWith(obj interface{}, b binder.Binder) (err error) {\n\tif err = b.Bind(ctx.Request, obj); err != nil {\n\t\treturn\n\t}\n\tif validator := ctx.Validator; validator != nil {\n\t\treturn validator.ValidateStruct(obj)\n\t}\n\treturn\n}", "func (d *DefaultContext) Bind(value interface{}) error {\n\treturn binding.Exec(d.Request(), value)\n}", "func ListenContext(ctx context.Context, laddr net.Addr, raddr string, config *Config) (net.Listener, <-chan error, error) {\n\tlistener, err := net.Listen(laddr.Network(), laddr.String())\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"listen on %s://%s: %v\", laddr.Network(), laddr.String(), err)\n\t}\n\tlistenerConnsCh, _ := listenerConns(ctx, listener)\n\ttunnelConn := func(ctx context.Context) (net.Conn, <-chan error, error) {\n\t\treturn DialContext(ctx, raddr, config)\n\t}\n\terrCh := make(chan error, 1)\n\thandleListenerConn := func(listenerConn net.Conn) {\n\t\tctxConn, cancel := context.WithCancel(ctx)\n\t\tdefer listenerConn.Close()\n\t\tdefer cancel()\n\t\ttunnelConn, tunnelConnErrCh, err := tunnelConn(ctxConn)\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tpipeDone := make(chan bool, 1)\n\t\tgo func() {\n\t\t\tconnpipe.Run(ctxConn, tunnelConn, listenerConn)\n\t\t\tpipeDone <- true\n\t\t}()\n\t\tselect {\n\t\tcase <-pipeDone:\n\t\t\treturn\n\t\tcase err, ok := <-tunnelConnErrCh:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terrCh <- err\n\t\tcase <-ctx.Done():\n\t\t\terrCh <- ctx.Err()\n\t\t}\n\t}\n\tgo func() {\n\t\tdefer listener.Close()\n\t\tdefer close(errCh)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\terrCh <- ctx.Err()\n\t\t\t\treturn\n\t\t\tcase listenerConn, ok := <-listenerConnsCh:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tgo handleListenerConn(listenerConn)\n\t\t\t}\n\t\t}\n\t}()\n\treturn listener, errCh, err\n}", "func (r RunFunc) Run(ctx context.Context) {\n\tr(ctx)\n}", "func (c *Client) PostWithContext(ctx context.Context, url string, reqBody, resType interface{}) error {\n\treturn c.CallAPIWithContext(ctx, \"POST\", url, reqBody, resType, true)\n}", "func (r *Reconciler) bind(\n\tlogger *log.Log,\n\tbm *ServiceBinder,\n\tsbrStatus *v1alpha1.ServiceBindingRequestStatus,\n) (\n\treconcile.Result,\n\terror,\n) {\n\tlogger = logger.WithName(\"bind\")\n\n\tlogger.Info(\"Binding applications with intermediary secret...\")\n\treturn bm.Bind()\n}", "func PrintfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tprintdeps(hub.CaptureMessage, 3, fmt.Sprintf(format, args...))\n\t\treturn\n\t}\n\n\tprintdeps(sentry.CaptureMessage, 3, fmt.Sprintf(format, args...))\n}", "func NewWithContext(ctx context.Context, fn func() error) func() error {\n\treturn NewFactory(WithContext(ctx))(fn)\n}", "func WithRunActionsCtx(ctx context.Context, ra RunActionsCtx) context.Context {\n\treturn context.WithValue(ctx, runActionsCtxKey{}, ra)\n}", "func PanicfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tpanicdeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\tpanicdeps(sentry.CaptureMessage, 3, format, args...)\n}", "func Bind(req *http.Request) *http.Request {\n // Reuse context if already binded\n if _, ok := req.Context().Value(Key).(Store); ok {\n return req\n }\n // Create new context store\n ctx := context.WithValue(req.Context(), Key, Store{})\n return req.WithContext(ctx)\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBSubnetGroupWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBSubnetGroupWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBSubnetGroupWithContext), varargs...)\n}", "func (m *Manager) Run(ctx context.Context, run func() error) (err error) {\n\t// Acquire mutex lock\n\tm.mux.Lock()\n\t// Defer the release of mutex lock\n\tdefer m.mux.Unlock()\n\t// Call internal run func\n\treturn m.run(ctx, run)\n}", "func (r *Retrier) RunContext(ctx context.Context, funcToRetry func(context.Context) error) error {\n\tmaxTries := r.maxTries\n\tinitialDelay := r.initialDelay\n\tmaxDelay := r.maxDelay\n\tif maxTries <= 0 {\n\t\tmaxTries = DefaultMaxTries\n\t}\n\tif initialDelay <= 0 {\n\t\tinitialDelay = DefaultInitialDelay\n\t}\n\tif maxDelay <= 0 {\n\t\tmaxDelay = DefaultMaxDelay\n\t}\n\trandSource := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tattempts := 0\n\tfor {\n\t\t// Attempt to run the function\n\t\terr := funcToRetry(ctx)\n\t\t// If there's no error, we're done!\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tattempts++\n\t\t// If we've just run our last attempt, return the error we got\n\t\tif attempts == maxTries {\n\t\t\treturn err\n\t\t}\n\n\t\t// Check if the error is a terminal error. If so, stop!\n\t\tswitch v := err.(type) {\n\t\tcase terminalError:\n\t\t\treturn v.e\n\t\t}\n\t\t// Otherwise wait for the next duration or until the context is done,\n\t\t// whichever comes first\n\t\tt := time.NewTimer(getnextBackoff(attempts, initialDelay, maxDelay, randSource))\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\t// duration elapsed, loop\n\t\tcase <-ctx.Done():\n\t\t\t// context cancelled, kill the timer if it hasn't fired, and return\n\t\t\t// the last error we got\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (s *Service) Bind(ctx context.Context, address string) error {\n\ts.mutex.Lock()\n\tif s.running {\n\t\ts.mutex.Unlock()\n\t\treturn fmt.Errorf(\"Init(): already running\")\n\t}\n\ts.mutex.Unlock()\n\n\ts.parseAddress(address)\n\n\terr := s.setListener(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBSnapshotWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBSnapshotWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBSnapshotWithContext), varargs...)\n}", "func (p fullProvider) FetchDSNWithContext(_ context.Context, dsn string) (string, error) {\n\treturn p.FetchDSN(dsn)\n}", "func CreticalfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tcreticaldeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\tcreticaldeps(sentry.CaptureMessage, 3, format, args...)\n}", "func AllWithContext(ctx context.Context, functions ...TaskFunc) {\n\tForWithContext(ctx, 0, len(functions), func(i int) {\n\t\tfunctions[i]()\n\t})\n}", "func (_m *EventBus) Run(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func (o *LoggingBindParams) WithContext(ctx context.Context) *LoggingBindParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (c *icecontext) Bind(i interface{}) error {\n\treturn protocol.Unpack(c.Request().GetFormat(),\n\t\tc.Request().GetBody(), i)\n}", "func DoWithContext(ctx context.Context, do func(ctx context.Context) error, fallback func(err error)) (err error) {\n\terrorChannel := make(chan error)\n\tvar contextHasBeenDone = false\n\tgo func() {\n\t\terr := do(ctx)\n\t\tif contextHasBeenDone {\n\t\t\tif fallback != nil {\n\t\t\t\tfallback(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terrorChannel <- err\n\t}()\n\tselect {\n\tcase err = <-errorChannel:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tcontextHasBeenDone = true\n\t\treturn ctx.Err()\n\t}\n}", "func wrapContext(ctx context.Context, adapter Adapter) contextWrapper {\n\treturn contextWrapper{\n\t\tctx: context.WithValue(ctx, ctxKey, adapter),\n\t\tadapter: adapter,\n\t}\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBClusterSnapshotAttributeWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBClusterSnapshotAttributeWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBClusterSnapshotAttributeWithContext), varargs...)\n}", "func WithRunner(runner func(context.Context) error) CollectorIntegrationConfig {\n\treturn func(i *CollectorIntegration) {\n\t\ti.runner = runner\n\t}\n}", "func (b ExponentialBackOff) RetryWithContext(ctx context.Context, operation func() error) error {\n\tb.Reset()\n\tfor {\n\t\terr := operation()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tnext := b.NextBackOff()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"%v with last error: %v\", context.DeadlineExceeded, err)\n\t\tcase <-time.After(next):\n\t\t}\n\t}\n}", "func (API) Context(s *api.State, thread uint64) api.Context {\n\treturn nil\n}", "func ExecuteEWithContext(ctx context.Context, s string, obj interface{}, settings ...SettingsFunc) (*exec.Cmd, error) {\n\tr := DefaultRunner()\n\treturn r.ExecuteEWithContext(ctx, s, obj, settings...)\n}", "func (b *Builder) Run(r *Runner) {\n\tr.Run()\n\tb.mu.Lock()\n\tdelete(b.running, r)\n\tb.mu.Unlock()\n}", "func (mr *MockRDSAPIMockRecorder) WaitUntilDBSnapshotAvailableWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitUntilDBSnapshotAvailableWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).WaitUntilDBSnapshotAvailableWithContext), varargs...)\n}", "func (o *OutputState) ApplyIntPtrWithContext(ctx context.Context, applier interface{}) IntPtrOutput {\n\treturn o.ApplyTWithContext(ctx, applier).(IntPtrOutput)\n}", "func WrapContextForServer(ctx context.Context) context.Context {\n\tif v := ctx.Value(serverPayloadKey); v != nil {\n\t\treturn ctx\n\t}\n\n\treturn context.WithValue(ctx, serverPayloadKey, serverPayload{\n\t\tm: make(map[string]interface{}),\n\t})\n}", "func (mr *MockRDSAPIMockRecorder) WaitUntilDBInstanceAvailableWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitUntilDBInstanceAvailableWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).WaitUntilDBInstanceAvailableWithContext), varargs...)\n}", "func (s *StubSentry) WrapContext(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, stubSentryKey, s)\n}", "func (m *MQTT) WriteWithContext(ctx context.Context, msg *message.Batch) error {\n\treturn m.Write(msg)\n}" ]
[ "0.6004581", "0.5999245", "0.59970725", "0.5727529", "0.56164736", "0.55119467", "0.5381095", "0.5210632", "0.52035266", "0.5194531", "0.5181738", "0.51611114", "0.5145714", "0.5078032", "0.50537634", "0.5029204", "0.5004192", "0.49929345", "0.4977733", "0.49630624", "0.49399602", "0.49342173", "0.49006084", "0.4874898", "0.48338205", "0.48226637", "0.4812495", "0.47725084", "0.4769671", "0.476642", "0.47219515", "0.47141433", "0.4713416", "0.47040948", "0.47017372", "0.46720192", "0.46720192", "0.46720192", "0.46720192", "0.46612304", "0.46570274", "0.46450475", "0.46406668", "0.4625494", "0.46254826", "0.46101275", "0.4588602", "0.45847958", "0.4562158", "0.45567486", "0.45388055", "0.4522944", "0.45094544", "0.45054305", "0.45026252", "0.44876415", "0.44576338", "0.44498038", "0.4422623", "0.4418043", "0.44168568", "0.44085318", "0.4408354", "0.4404763", "0.44005406", "0.43981755", "0.43907925", "0.4388614", "0.4370541", "0.43539342", "0.4341735", "0.43398854", "0.43278286", "0.4322912", "0.4317141", "0.4315656", "0.43132195", "0.42949426", "0.42782596", "0.42741978", "0.4269806", "0.4261499", "0.42593953", "0.42429602", "0.42428055", "0.42398685", "0.42390805", "0.4231867", "0.42297134", "0.42288148", "0.42276946", "0.42264536", "0.42249712", "0.4218942", "0.421638", "0.4215314", "0.4203425", "0.42011997", "0.41990155", "0.4190176" ]
0.7612144
0
WhileRunning do something if it is running. It provides a context o check if it stops.
Пока выполняется, выполняйте что-то, если она запущена. Она предоставляет контекст для проверки, остановлена ли она.
func (s *DeterminationWithContext) WhileRunning(do func(context.Context) error) error { return s.whilerunning(func() error { select { case <-s.sctx.Done(): return ErrRunnerIsClosing default: return do(s.sctx) } }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Manager) WaitUntilRunning() {\n\tfor {\n\t\tm.mu.Lock()\n\n\t\tif m.ctx != nil {\n\t\t\tm.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tstarted := m.started\n\t\tm.mu.Unlock()\n\n\t\t// Block until we have been started.\n\t\t<-started\n\t}\n}", "func (s *Stopwatch) isRunning() bool {\n\treturn !s.refTime.IsZero()\n}", "func (w *watcher) checkLoop(ctx context.Context) {\n\tfor atomic.LoadInt32(&w.state) == isRunning {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tw.Close()\n\t\t\tw.dispose()\n\t\t\treturn\n\t\tdefault:\n\t\t\tw.check(ctx)\n\t\t\ttime.Sleep(w.interval)\n\t\t}\n\t}\n}", "func (w *worker) isRunning() bool {\n\treturn atomic.LoadInt32(&w.running) == 1\n}", "func (f *flushDaemon) isRunning() bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\treturn f.stopC != nil\n}", "func runWhileFilesystemLives(f func() error, label string, filesystemId string, errorBackoff, successBackoff time.Duration) {\n\tdeathChan := make(chan interface{})\n\tdeathObserver.Subscribe(filesystemId, deathChan)\n\tstillAlive := true\n\tfor stillAlive {\n\t\tselect {\n\t\tcase _ = <-deathChan:\n\t\t\tstillAlive = false\n\t\tdefault:\n\t\t\terr := f()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\n\t\t\t\t\t\"Error in runWhileFilesystemLives(%s@%s), retrying in %s: %s\",\n\t\t\t\t\tlabel, filesystemId, errorBackoff, err)\n\t\t\t\ttime.Sleep(errorBackoff)\n\t\t\t} else {\n\t\t\t\ttime.Sleep(successBackoff)\n\t\t\t}\n\t\t}\n\t}\n\tdeathObserver.Unsubscribe(filesystemId, deathChan)\n}", "func (m *WebsocketRoutineManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.state) == readyState\n}", "func (p *adapter) Running() bool {\n\tif p.cmd == nil || p.cmd.Process == nil || p.cmd.Process.Pid == 0 || p.state() != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func running() bool {\n\treturn runCalled.Load() != 0\n}", "func (i *info) IsRunning() bool {\n\t_, ok := i.driver.activeContainers[i.ID]\n\treturn ok\n}", "func (b *Backtest) IsRunning() (ret bool) {\n\treturn b.running\n}", "func (b *base) IsRunning() bool {\n\treturn b.isRunning\n}", "func (h *Module) IsRunning()bool{\n\treturn h.running\n}", "func (p *AbstractRunProvider) IsRunning() bool {\n\treturn p.running\n}", "func (s *Stopwatch) IsRunning() bool {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.isRunning()\n}", "func (t *task) IsRunning() bool {\n\treturn t.running\n}", "func (folderWatcher *FolderWatcher) IsRunning() bool {\n\treturn folderWatcher.running\n}", "func isRunning(on_node, operation, rcCode string) bool {\n\treturn on_node != \"\" && (operation == \"start\" || (operation == \"monitor\" && rcCode == \"0\"))\n}", "func (sc *ConditionsScraper) Running() bool {\n\treturn sc.running\n}", "func (s *Scanner) IsRunning() bool {\n\treturn s.state == running\n}", "func (p *procBase) Running() bool {\n\treturn p.cmd != nil\n}", "func (r *Router) IsRunning() bool {\n\tselect {\n\tcase <-r.running:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (ss sservice) IsRunning(status string) bool {\n\tre := regexp.MustCompile(`is running`)\n\treturn re.Match([]byte(status))\n}", "func (r *Runner) IsRunning(id string) bool {\n\tr.rw.RLock()\n\tdefer r.rw.RUnlock()\n\t_, ok := r.jobsCancel[id]\n\n\treturn ok\n}", "func (i *Interval) IsRunning() bool {\n\treturn i.latch.IsRunning()\n}", "func (pb *PhilosopherBase) Runnable() bool {\n\treturn pb.State != philstate.Stopped\n}", "func (m *DataHistoryManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.started) == 1\n}", "func (m *DataHistoryManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.started) == 1\n}", "func (bc *BotCommand) isRunning() bool {\n\tbc.Lock()\n\tdefer bc.Unlock()\n\treturn bc.running\n}", "func (m *ntpManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.started) == 1\n}", "func (a *Recorder) IsRunning() bool {\n\treturn atomic.LoadUint32(&a.isRunning) != 0\n}", "func (tr *TestRunner) isStopped() bool {\n\tselect {\n\tcase <-tr.stop:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func checkForExit(ctx context.Context, client *docker.Client, containerID string) error {\n\tticker := time.NewTicker(2 * time.Second)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tinspectCtx, cancelInspect := xcontext.KeepAlive(ctx, 30*time.Second)\n\t\tisRunning, err := IsRunning(inspectCtx, client, containerID)\n\t\tcancelInspect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !isRunning {\n\t\t\toutput := new(strings.Builder)\n\t\t\tclient.Logs(docker.LogsOptions{\n\t\t\t\tContext: ctx,\n\t\t\t\tContainer: containerID,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tOutputStream: output,\n\t\t\t\tErrorStream: output,\n\t\t\t})\n\t\t\tif output.Len() == 0 {\n\t\t\t\treturn fmt.Errorf(\"container %s stopped running\", containerID)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"container %s stopped running:\\n%s\", containerID, strings.TrimSuffix(output.String(), \"\\n\"))\n\t\t}\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (s *Server) IsRunning() bool { return s.running }", "func (e *executor) isRunning(file string) *runInfo {\n\te.mRun.Lock()\n\tdefer e.mRun.Unlock()\n\treturn e.running[file]\n}", "func (c *Consumer) IsRunning() bool {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.running\n}", "func (dw *DoWhileTaskBehavior) evaluateCondition(ctx model.TaskContext, condition expression.Expr) (evalResult model.EvalResult, err error) {\n\tif t, ok := ctx.(*instance.TaskInst); ok {\n\t\tresult, err := condition.Eval(getScope(ctx, t))\n\t\tif err != nil {\n\t\t\treturn model.EvalFail, err\n\t\t}\n\t\tif result.(bool) {\n\t\t\tdelay := ctx.Task().LoopConfig().Delay()\n\t\t\tif delay > 0 {\n\t\t\t\tctx.FlowLogger().Infof(\"Dowhile Task[%s] execution delaying for %d milliseconds...\", ctx.Task().ID(), delay)\n\t\t\t\ttime.Sleep(time.Duration(delay) * time.Millisecond)\n\t\t\t}\n\t\t\tctx.FlowLogger().Infof(\"Task[%s] repeating as doWhile condition evaluated to true\", ctx.Task().ID())\n\t\t\treturn model.EvalRepeat, nil\n\t\t}\n\t\tctx.FlowLogger().Infof(\"Task[%s] doWhile condition evaluated to false\", ctx.Task().ID())\n\t}\n\treturn model.EvalDone, nil\n}", "func (l *List) IsRunning() bool {\n\treturn l.list.IsRunning()\n}", "func (p *Poller) IsStopped() bool {\n\treturn p.isStopped\n}", "func (i *Inbound) IsRunning() bool {\n\treturn i.once.IsRunning()\n}", "func (i *Intel8080) Running() bool {\n\treturn !i.halted\n}", "func WaitUntilRunning(service Service, timeout time.Duration) error {\n\treturn WaitUntil(service, true, timeout)\n}", "func (n *Ncd) IsRunning() bool {\n\treturn n.rtconf.Running\n}", "func (b *Build) IsRunning() bool {\n\treturn (b.Status == StatusStarted || b.Status == StatusEnqueue)\n}", "func LoopContext(ctx context.Context, interval time.Duration, loopFn, cleanupFn func()) {\n\tdefer cleanupFn()\n\n\tfor !ContextDone(ctx) {\n\t\tloopFn()\n\t\tif !DelayContext(ctx, interval) {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (t *DeferredRecordingTaskImpl) IsRunning() bool {\n\treturn t.task.IsRunning()\n}", "func (s *SegmentUpdateWorker) IsRunning() bool {\n\treturn s.lifecycle.IsRunning()\n}", "func (scheduler *Scheduler) IsRunning() bool {\n\treturn atomic.LoadInt32(&scheduler.isRunning) == 1\n}", "func (nl *Logger) Running() bool {\n\tnl.mu.Lock()\n\tdefer nl.mu.Unlock()\n\treturn nl.logger != nil\n}", "func (c *TestController) IsRunning(id TestID) bool {\n\treturn c.lookupJob(id) != nil\n}", "func (n *notifier) serviceLoop() {\n\tn.lock.Lock()\n\tdefer n.lock.Unlock()\n\tfor {\n\t\tfor n.desired == n.current {\n\t\t\tn.cond.Wait()\n\t\t}\n\t\tif n.current != n.id && n.desired == n.id {\n\t\t\tn.service.Validate(n.desired, n.current)\n\t\t\tn.service.Start()\n\t\t} else if n.current == n.id && n.desired != n.id {\n\t\t\tn.service.Stop()\n\t\t}\n\t\tn.current = n.desired\n\t}\n}", "func (s *Service) Running() bool {\n\tif m := s.mgr; m == nil {\n\t\treturn false\n\t} else {\n\t\tm.lock()\n\t\trv := s.running && !s.stopping\n\t\tm.unlock()\n\t\treturn rv\n\t}\n}", "func (m *Monitor) run(ctx context.Context) {\n\tdefer close(m.stopCh)\n\tdefer close(m.events)\n\tdefer m.log.Info(\"event loop stopped\")\n\tf := filters.NewArgs()\n\tf.Add(\"event\", \"start\")\n\tf.Add(\"event\", \"die\")\n\toptions := types.EventsOptions{Filters: f}\n\tfor {\n\t\terr := func() error {\n\t\t\tm.log.Info(\"processing existing containers\")\n\t\t\tif err := m.processContainers(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.log.Info(\"starting event loop\")\n\t\t\tmsgChan, errChan := m.client.Events(ctx, options)\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg := <-msgChan:\n\t\t\t\t\tif err := m.processMessage(ctx, msg); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\tcase err := <-errChan:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tif err == context.Canceled {\n\t\t\treturn\n\t\t}\n\t\tm.log.Error(err)\n\t\tm.log.Info(\"reconnecting in 30 seconds\")\n\t\tselect {\n\t\tcase <-time.After(30 * time.Second):\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c Container) IsRunning() bool {\n\treturn c.containerInfo.State.Running\n}", "func (c *D) IsRunning() bool {\n\tif c.cmd == nil {\n\t\treturn false\n\t}\n\tif c.cmd.Process == nil {\n\t\treturn false\n\t}\n\tprocess, err := ps.FindProcess(c.cmd.Process.Pid)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif process == nil && err == nil {\n\t\t// not found\n\t\treturn false\n\t}\n\treturn true\n}", "func (app *frame) IsStopped() bool {\n\treturn app.isStopped\n}", "func (c *Consumer) loop() {\n\tvar stop bool\n\tfor !stop {\n\t\tselect {\n\t\tcase <-c.status: // ...\n\t\tcase <-c.pause: // ...\n\t\tcase <-c.resume: // ...\n\t\tcase <-c.stop: // ...\n\t\tcase resp := <-c.pausedQuery: // ...\n\t\tcase <-c.exit:\n\t\t\tstop = true\n\t\t}\n\t}\n}", "func (s *scheduler) IsRunning() bool {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.isRunning\n}", "func (s *server) Running() bool {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn (s.state != Stopped && s.state != Initialized)\n}", "func (jbobject *TaskContext) RunningLocally() bool {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"runningLocally\", javabind.Boolean)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(bool)\n}", "func IsRunning() bool {\n\treturn defaultDaemon.IsRunning()\n}", "func (h *EventHandler) Run() {\n\tticker := time.NewTicker(2 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif !h.needHandle || h.isDoing {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\th.needHandle = false\n\t\t\th.isDoing = true\n\t\t\t// if has error\n\t\t\tif h.doHandle() {\n\t\t\t\th.needHandle = true\n\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t}\n\t\t\th.isDoing = false\n\t\tcase <-h.ctx.Done():\n\t\t\tblog.Infof(\"EventHandler for %s run loop exit\", h.lbID)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *Streamer) IsRunning() bool {\n\ts.mu.Lock()\n\tisRunning := s.state == stateRunning\n\ts.mu.Unlock()\n\n\treturn isRunning\n}", "func skipIfStillRunning(name string, t Task) Task {\n\tvar ch = make(chan struct{}, 1)\n\tch <- struct{}{}\n\n\treturn TaskFunc(func() {\n\t\tselect {\n\t\tcase v := <-ch:\n\t\t\tt.Run()\n\t\t\tch <- v\n\t\tdefault:\n\t\t\tlog.Warn(\"scheduler: skipping task\").String(\"name\", name).Log()\n\t\t}\n\t})\n}", "func (c *cephStatusChecker) checkCephStatus(stopCh chan struct{}) {\n\t// check the status immediately before starting the loop\n\tc.checkStatus()\n\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\tlogger.Infof(\"Stopping monitoring of ceph status\")\n\t\t\treturn\n\n\t\tcase <-time.After(c.interval):\n\t\t\tc.checkStatus()\n\t\t}\n\t}\n}", "func (m *Manager) Run(ctx context.Context) error {\n\ts := <-m.status\n\tswitch s {\n\tcase StatusShutdown:\n\t\tm.status <- s\n\t\treturn ErrShutdown\n\tcase StatusUnknown:\n\t\t// ok\n\tdefault:\n\t\tm.status <- s\n\t\treturn ErrAlreadyStarted\n\t}\n\n\tstartCtx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tm.startupCancel = cancel\n\tstartupFunc := m.startupFunc\n\tm.status <- StatusStarting\n\n\tif startupFunc != nil {\n\t\tm.startupErr = startupFunc(startCtx)\n\t}\n\tcancel()\n\n\ts = <-m.status\n\n\tswitch s {\n\tcase StatusShutdown:\n\t\tm.status <- s\n\t\t// no error on shutdown while starting\n\t\treturn nil\n\tcase StatusStarting:\n\t\tif m.startupErr != nil {\n\t\t\tm.status <- s\n\t\t\tclose(m.startupDone)\n\t\t\treturn m.startupErr\n\t\t}\n\t\t// ok\n\tdefault:\n\t\tm.status <- s\n\t\tpanic(\"unexpected lifecycle state\")\n\t}\n\n\tctx, m.runCancel = context.WithCancel(ctx)\n\tclose(m.startupDone)\n\tm.status <- StatusReady\n\n\terr := m.runFunc(ctx)\n\tclose(m.runDone)\n\t<-m.shutdownDone\n\treturn err\n}", "func (transmuxer *Transmuxer) IsRunning() bool {\n\treturn transmuxer.running\n}", "func (s *status) stopping() error { return s.set(\"stopping\", \"STOPPING=1\") }", "func (o *Outbound) IsRunning() bool {\n\treturn o.once.IsRunning()\n}", "func (wf *Workflow) IsRunning() bool {\n\treturn wf.running\n}", "func IsWatchRunning() error {\n\t// This is connecting locally and it is very unlikely watch is overloaded,\n\t// set the timeout *super* short to make it easier on the users when they\n\t// forgot to start watch.\n\twithTimeout, _ := context.WithTimeout(context.TODO(), 100*time.Millisecond)\n\n\tconn, err := grpc.DialContext(\n\t\twithTimeout,\n\t\tfmt.Sprintf(\"127.0.0.1:%d\", viper.GetInt(\"port\")),\n\t\t[]grpc.DialOption{\n\t\t\tgrpc.WithBlock(),\n\t\t\tgrpc.WithInsecure(),\n\t\t}...)\n\n\tif err != nil {\n\t\t// The assumption is that the only real error here is because watch isn't\n\t\t// running\n\t\tlog.Debug(err)\n\t\treturn errWatchNotRunning\n\t}\n\n\tclient := pb.NewKsyncClient(conn)\n\talive, err := client.IsAlive(context.Background(), &empty.Empty{})\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn errWatchNotResponding\n\t}\n\n\tif !alive.Alive {\n\t\treturn errSyncthingNotRunning\n\t}\n\n\tif err := conn.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *WhileStmt) isDone(env *Env) (done bool) { //todo\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tswitch e.(type) { // error type case\n\t\t\tcase ContinueErr:\n\t\t\t\tdone = false\n\t\t\t\treturn\n\t\t\tcase BreakErr:\n\t\t\t\tdone = true\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t}\n\t}()\n\tfor isTruthy(s.condition.eval(env)) {\n\t\ts.body.execute(env)\n\t}\n\treturn true\n}", "func (e *Engine) Running() bool {\n\treturn e.running\n}", "func (o *ChannelOutbound) IsRunning() bool {\n\treturn o.once.IsRunning()\n}", "func Stop() {\n\tstopRunning <- true\n\n}", "func (s *TimeSwitch) Run(stopCh <-chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-s.Clock.After(s.secondsUntilNextMinute()):\n\t\t\ts.check()\n\t\tcase <-stopCh:\n\t\t\tlog.Info(\"shutting down time switch\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (sw *streamWatcher) stopping() bool {\n\tsw.Lock()\n\tdefer sw.Unlock()\n\treturn sw.stopped\n}", "func (w *WatchManager) run() {\n\tw.pollUpdatesInWasp() // initial pull from WASP\n\trunning := true\n\tfor running {\n\t\tselect {\n\t\tcase <-time.After(1 * time.Minute):\n\t\t\tw.pollUpdatesInWasp()\n\n\t\tcase <-w.stopChannel:\n\t\t\trunning = false\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func (s *Session) IsRunning() bool {\n\tstatus, err := s.status()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn status == \"Running\"\n}", "func (jbobject *TaskContext) IsRunningLocally() bool {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"isRunningLocally\", javabind.Boolean)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(bool)\n}", "func (t ResolvedPipelineRunTask) IsRunning() bool {\n\tif t.IsCustomTask() {\n\t\tif t.Run == nil {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tif t.TaskRun == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn !t.IsSuccessful() && !t.IsFailure() && !t.IsCancelled()\n}", "func (j *JournalTailer) IsRunning() bool {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn j.running\n}", "func (s *Stopper) IsStopped() <-chan struct{} {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn s.stopped\n}", "func (s *Stopper) IsStopped() <-chan struct{} {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn s.stopped\n}", "func (e *BackgroundTask) Run(m libkb.MetaContext) (err error) {\n\tdefer m.Trace(e.Name(), &err)()\n\n\t// use a new background context with a saved cancel function\n\tvar cancel func()\n\tm, cancel = m.BackgroundWithCancel()\n\n\te.Lock()\n\tdefer e.Unlock()\n\n\te.shutdownFunc = cancel\n\tif e.shutdown {\n\t\t// Shutdown before started\n\t\tcancel()\n\t\te.meta(\"early-shutdown\")\n\t\treturn nil\n\t}\n\n\t// start the loop and return\n\tgo func() {\n\t\terr := e.loop(m)\n\t\tif err != nil {\n\t\t\te.log(m, \"loop error: %s\", err)\n\t\t}\n\t\tcancel()\n\t\te.meta(\"loop-exit\")\n\t}()\n\n\treturn nil\n}", "func (s *GrpcServer) IsRunning() bool {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\treturn s.running\n}", "func (p *Provider) CheckStopped() {\n\tp.t.Helper()\n\n\tif !p.stopped {\n\t\tp.t.Fatal(\"provider is not stopped\")\n\t}\n}", "func (c *ContextCollector) Run() {\n\tif !c.Running {\n\t\tc.StopChan = make(chan bool)\n\t\tc.StopCounterChan = make(chan bool)\n\t\tc.StoppedCounterChan = make(chan bool)\n\t\tgo c.runCounter()\n\t\tc.Running = true\n\t}\n}", "func (timer *Timer) IsRunning() bool {\n\tif timer == nil {\n\t\treturn false\n\t}\n\n\treturn timer.running\n}", "func (s *Stopwatch) active() bool {\n\treturn s.stop.IsZero()\n}", "func (s *OpenHackSimulator) IsRunning() bool {\n\ts.isRunningMutex.Lock()\n\tdefer s.isRunningMutex.Unlock()\n\treturn s.isRunning\n}", "func (s *Scheduler) Running() bool {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn s.running\n}", "func (w *worker) stop() {\n\tatomic.StoreInt32(&w.running, 0)\n}", "func (s *Server) stopRunning() bool {\n\ts.rl.Lock()\n\tdefer s.rl.Unlock()\n\treturn s.doClose\n}", "func sleepUntilCtxDone(d time.Duration, ctx context.Context) (abort bool) {\n\tif ctx == nil {\n\t\ttime.Sleep(d)\n\t\treturn false\n\t}\n\n\tselect {\n\tcase <-time.After(d):\n\t\treturn false\n\tcase <-ctx.Done():\n\t\treturn true\n\t}\n}", "func running(args ...string) (found bool) {\n found = false\n cmd := exec.Command(\"docker\", \"ps\", \"--no-trunc\")\n\n stdout, err := cmd.StdoutPipe()\n if err != nil {\n logger.Log(fmt.Sprintln(err))\n }\n\n _, err = cmd.StderrPipe()\n if err != nil {\n logger.Log(fmt.Sprintln(err))\n }\n\n err = cmd.Start()\n if err != nil {\n logger.Log(fmt.Sprintln(err))\n }\n\n buf := new(bytes.Buffer)\n buf.ReadFrom(stdout)\n s := buf.String()\n\n cmd.Wait()\n\n for _, id := range pids() {\n if len(id) > 0 && !found {\n found = strings.Contains(s, id[:5])\n }\n }\n\n return\n}", "func (b *T) Run(name string, f func(t *T)) bool {\n\tsuccess := true\n\tif b.tracker.Active() {\n\t\tsuccess = success && b.t.Run(name, func(t *testing.T) {\n\t\t\tf(&T{t, t, b.tracker.SubTracker()})\n\t\t})\n\t}\n\treturn success\n}", "func isStepRunning(index int, stageSteps []v1.CoreActivityStep) bool {\n\tif len(stageSteps) > 0 {\n\t\tpreviousStep := stageSteps[index-1]\n\t\treturn previousStep.CompletedTimestamp != nil\n\t}\n\treturn true\n}", "func (m *TimerMutation) IsRunning() (r bool, exists bool) {\n\tv := m._IsRunning\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o *observer) run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\twg := sync.WaitGroup{}\n\n\t// Run healthcheck loop\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.runHealthcheckLoopFn(ctx)\n\t}()\n\n\t// Continuously sync worker pods\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.syncWorkerPodsFn(ctx)\n\t}()\n\n\t// Continuously sync job pods\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.syncJobPodsFn(ctx)\n\t}()\n\n\t// Wait for an error or a completed context\n\tvar err error\n\tselect {\n\t// In essence, this comprises the Observer's \"healthcheck\" logic.\n\t// Whenever we receive an error on this channel, we cancel the context and\n\t// shut down. E.g., if one loop fails, everything fails.\n\t// This includes:\n\t// 1. an error pinging the Brigade API server endpoint\n\t// (Observer <-> API comms)\n\t// 2. an error pinging the K8s API server endpoint\n\t// (Observer <-> K8s comms)\n\t//\n\t// Note: Currently, errors updating or cleaning up worker or job statuses\n\t// are handled by o.errFn, which currently simply logs the error\n\tcase err = <-o.errCh:\n\t\tcancel() // Shut it all down\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\t}\n\n\t// Adapt wg to a channel that can be used in a select\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\t\twg.Wait()\n\t}()\n\n\tselect {\n\tcase <-doneCh:\n\tcase <-time.After(3 * time.Second):\n\t\t// Probably doesn't matter that this is hardcoded. Relatively speaking, 3\n\t\t// seconds is a lot of time for things to wrap up.\n\t}\n\n\treturn err\n}" ]
[ "0.622798", "0.61385405", "0.6091839", "0.5883035", "0.58240783", "0.57762426", "0.56919473", "0.5631193", "0.56184846", "0.5609338", "0.5568484", "0.55551463", "0.5537527", "0.55302274", "0.5524895", "0.5518544", "0.549713", "0.544841", "0.54235667", "0.5421718", "0.53941876", "0.5375202", "0.5368934", "0.53635347", "0.53493935", "0.53449667", "0.53417933", "0.53417933", "0.5337958", "0.5304802", "0.52992415", "0.52891773", "0.5262416", "0.5259816", "0.52530366", "0.52466345", "0.52401537", "0.5235107", "0.52290845", "0.5221592", "0.52213985", "0.5207853", "0.5184785", "0.51645744", "0.5163141", "0.51541877", "0.51534766", "0.51524717", "0.51341546", "0.51315475", "0.5126247", "0.5121419", "0.5118825", "0.5111056", "0.5090381", "0.508878", "0.5088245", "0.50843483", "0.5083389", "0.5079202", "0.5056837", "0.505399", "0.50512284", "0.50496376", "0.50486255", "0.50470626", "0.5033762", "0.5019976", "0.5001165", "0.49986905", "0.4993433", "0.49842313", "0.49789205", "0.4971221", "0.49712038", "0.49629048", "0.49608135", "0.4945123", "0.49306354", "0.49115154", "0.49101612", "0.49047863", "0.48982757", "0.48982757", "0.4896024", "0.489523", "0.48806238", "0.48796958", "0.48782972", "0.4862897", "0.48609594", "0.485429", "0.48416066", "0.48380643", "0.483792", "0.4828252", "0.48274276", "0.48058105", "0.4805196", "0.47942477" ]
0.7218582
0
RecordReqDuration records the duration of given operation in metrics system
RecordReqDuration записывает продолжительность заданной операции в систему метрик
func (pr PrometheusRecorder) RecordReqDuration(jenkinsService, operation string, code int, elapsedTime float64) { reportRequestDuration(jenkinsService, operation, code, elapsedTime) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func recordDuration(name string, hostname string, path string, method string, duration float64) {\n\trequestDurations.WithLabelValues(name, hostname, path, method).Observe(duration)\n}", "func (me *Metrics) RecordRequestTime(labels Labels, length time.Duration) {\n\t// Only record times for successful requests, as we don't have labels to screen out bad requests.\n\tif labels.RequestStatus == RequestStatusOK {\n\t\tme.RequestTimer.Update(length)\n\t}\n}", "func PromAddRequestDuration(sc int, m string, d time.Duration) {\n\tRequestDuration.With(prometheus.Labels{\"code\": fmt.Sprintf(\"%v\", sc), \"method\": m}).Set(d.Seconds())\n}", "func (me *Metrics) RecordRequest(labels Labels) {\n\tme.RequestStatuses[labels.RType][labels.RequestStatus].Mark(1)\n\tif labels.Source == DemandApp {\n\t\tme.AppRequestMeter.Mark(1)\n\t} else {\n\t\tif labels.CookieFlag == CookieFlagNo {\n\t\t\t// NOTE: Old behavior was log me.AMPNoCookieMeter here for AMP requests.\n\t\t\t// AMP is still new and OpenRTB does not do this, so changing to match\n\t\t\t// OpenRTB endpoint\n\t\t\tme.NoCookieMeter.Mark(1)\n\t\t}\n\t}\n\n\t// Handle the account metrics now.\n\tam := me.getAccountMetrics(labels.PubID)\n\tam.requestMeter.Mark(1)\n}", "func recordRequest(name string, hostname string, path string, method string) {\n\trequestsProcessed.WithLabelValues(name, hostname, path, method).Inc()\n}", "func observeRequestSimDuration(jobName string, extJobID uuid.UUID, vrfVersion vrfcommon.Version, pendingReqs []pendingRequest) {\n\tnow := time.Now().UTC()\n\tfor _, request := range pendingReqs {\n\t\t// First time around lastTry will be zero because the request has not been\n\t\t// simulated yet. It will be updated every time the request is simulated (in the event\n\t\t// the request is simulated multiple times, due to it being underfunded).\n\t\tif request.lastTry.IsZero() {\n\t\t\tvrfcommon.MetricTimeUntilInitialSim.\n\t\t\t\tWithLabelValues(jobName, extJobID.String(), string(vrfVersion)).\n\t\t\t\tObserve(float64(now.Sub(request.utcTimestamp)))\n\t\t} else {\n\t\t\tvrfcommon.MetricTimeBetweenSims.\n\t\t\t\tWithLabelValues(jobName, extJobID.String(), string(vrfVersion)).\n\t\t\t\tObserve(float64(now.Sub(request.lastTry)))\n\t\t}\n\t}\n}", "func (m *metricsReporter) ReportRequest(_ context.Context, startTime time.Time, action string, err error) {\n\tm.requestDurationMetric.With(kitmetrics.Field{Key: \"action\", Value: action}).Observe(time.Since(startTime))\n\tm.requestCounterMetric.With(kitmetrics.Field{Key: \"action\", Value: action}).Add(1)\n\tif err != nil {\n\t\tm.errorCounterMetric.With(kitmetrics.Field{Key: \"action\", Value: action}).Add(1)\n\t}\n}", "func (m *MetricsProvider) AddOperationTime(value time.Duration) {\n}", "func ReportLibRequestMetric(system, handler, method, status string, started time.Time) {\n\trequestsTotalLib.WithLabelValues(system, handler, method, status).Inc()\n\trequestLatencyLib.WithLabelValues(system, handler, method, status).Observe(time.Since(started).Seconds())\n}", "func RecordKMSOperationLatency(providerName, methodName string, duration time.Duration, err error) {\n\tKMSOperationsLatencyMetric.WithLabelValues(providerName, methodName, getErrorCode(err)).Observe(duration.Seconds())\n}", "func BenchmarkRecordReqCommand(b *testing.B) {\n\tw := newWorker()\n\n\tregister := &registerViewReq{views: []*View{view}, err: make(chan error, 1)}\n\tregister.handleCommand(w)\n\tif err := <-register.err; err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tconst tagCount = 10\n\tctxs := make([]context.Context, 0, tagCount)\n\tfor i := 0; i < tagCount; i++ {\n\t\tctx, _ := tag.New(context.Background(),\n\t\t\ttag.Upsert(k1, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k2, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k3, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k4, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k5, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k6, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k7, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k8, fmt.Sprintf(\"v%d\", i)),\n\t\t)\n\t\tctxs = append(ctxs, ctx)\n\t}\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\trecord := &recordReq{\n\t\t\tms: []stats.Measurement{\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t},\n\t\t\ttm: tag.FromContext(ctxs[i%len(ctxs)]),\n\t\t}\n\t\trecord.handleCommand(w)\n\t}\n}", "func (tr *customTransport) Duration() time.Duration {\n\treturn tr.reqEnd.Sub(tr.reqStart)\n}", "func RecordLatency(seconds float64) RecordOption {\n\treturn func(r *RecordStream) {\n\t\tr.createRequest.BufferFragSize = uint32(seconds*float64(r.createRequest.Rate)) * uint32(r.createRequest.Channels) * uint32(r.bytesPerSample)\n\t\tr.createRequest.BufferMaxLength = 2 * r.createRequest.BufferFragSize\n\t\tr.createRequest.AdjustLatency = true\n\t}\n}", "func ReportAPIRequestMetric(handler, method, status string, started time.Time) {\n\trequestsTotalAPI.WithLabelValues(handler, method, status).Inc()\n\trequestLatencyAPI.WithLabelValues(handler, method, status).Observe(time.Since(started).Seconds())\n}", "func (*Client) RequestDuration() map[float64]float64 {\n\trequestDuration.Write(m)\n\tresult := make(map[float64]float64, len(m.Summary.Quantile))\n\tfor _, v := range m.Summary.Quantile {\n\t\tresult[*v.Quantile] = *v.Value\n\t}\n\n\treturn result\n}", "func RecordVolumeOperationMetric(pluginName, opName string, timeTaken float64, err error) {\n\tif pluginName == \"\" {\n\t\tpluginName = \"N/A\"\n\t}\n\tif err != nil {\n\t\tvolumeOperationErrorsMetric.WithLabelValues(pluginName, opName).Inc()\n\t\treturn\n\t}\n\tvolumeOperationMetric.WithLabelValues(pluginName, opName).Observe(timeTaken)\n}", "func (dc *deviceContext) computeTime(req *Request) time.Duration {\n\trequestDuration := time.Duration(0)\n\n\tswitch req.Type {\n\t// Handle metadata requests, plus metadata requests that have been factored out because we\n\t// need separate handling for them.\n\tcase MetadataRequest, CloseRequest:\n\t\trequestDuration = dc.deviceConfig.MetadataOpTime\n\tcase AllocateRequest:\n\t\trequestDuration = dc.computeSeekTime(req) + dc.deviceConfig.AllocateTime(req.Size)\n\tcase ReadRequest:\n\t\trequestDuration = dc.computeSeekTime(req) + dc.deviceConfig.ReadTime(req.Size)\n\tcase WriteRequest:\n\t\tswitch dc.deviceConfig.WriteStrategy {\n\t\tcase slowfs.FastWrite:\n\t\t\t// Leave at 0 seconds.\n\t\tcase slowfs.SimulateWrite:\n\t\t\trequestDuration = dc.computeSeekTime(req) + dc.deviceConfig.WriteTime(req.Size)\n\t\t}\n\tcase FsyncRequest:\n\t\tswitch dc.deviceConfig.FsyncStrategy {\n\t\tcase slowfs.DumbFsync:\n\t\t\trequestDuration = dc.deviceConfig.SeekTime * 10\n\t\tcase slowfs.WriteBackCachedFsync:\n\t\t\trequestDuration = dc.deviceConfig.SeekTime + dc.deviceConfig.WriteTime(dc.writeBackCache.getUnwrittenBytes(req.Path))\n\t\t}\n\tdefault:\n\t\tdc.logger.Printf(\"unknown request type for %+v\\n\", req)\n\t}\n\n\treturn latestTime(dc.busyUntil, req.Timestamp).Add(requestDuration).Sub(req.Timestamp)\n}", "func (nsc *NilConsumerStatsCollector) UpdateGetRecordsDuration(time.Duration) {}", "func TimeLog(nextHandler http.Handler) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// log.Debugf(\"Request received : %v\", r)\n\t\tstart := time.Now()\n\n\t\t// make the call\n\t\tv := capturewriter.CaptureWriter{ResponseWriter: w, StatusCode: 0}\n\t\tctx := context.Background()\n\t\tnextHandler.ServeHTTP(&v, r.WithContext(ctx))\n\n\t\t// Stop timer\n\t\tend := time.Now()\n\n\t\tgo func() {\n\t\t\tlatency := end.Sub(start)\n\t\t\treq++\n\t\t\tavgLatency = avgLatency + ((int64(latency) - avgLatency) / req)\n\t\t\t// log.Debugf(\"Request handled successfully: %v\", v.GetStatusCode())\n\t\t\tvar statusCode = v.GetStatusCode()\n\n\t\t\tpath := r.URL.Path\n\t\t\thost := r.Host\n\t\t\treferer := r.Header.Get(\"Referer\")\n\t\t\tclientIP := r.RemoteAddr\n\t\t\tmethod := r.Method\n\n\t\t\tlog.Infow(fmt.Sprintf(\"|%d| %10v %s\", statusCode, time.Duration(latency), path),\n\t\t\t\t\"statusCode\", statusCode,\n\t\t\t\t\"request\", req,\n\t\t\t\t\"latency\", time.Duration(latency),\n\t\t\t\t\"avgLatency\", time.Duration(avgLatency),\n\t\t\t\t\"ipPort\", clientIP,\n\t\t\t\t\"method\", method,\n\t\t\t\t\"host\", host,\n\t\t\t\t\"path\", path,\n\t\t\t\t\"referer\", referer,\n\t\t\t)\n\t\t}()\n\n\t}\n}", "func TrackRequest(method string, uri string) *DurationTrace {\n\ttraces := make([]*DurationTrace, 0)\n\n\tif traceListeners != nil {\n\t\tfor _, tl := range traceListeners {\n\t\t\ttraces = append(traces, (*tl).TrackRequest(method, uri))\n\t\t}\n\t}\n\n\tdt := newAggregateDurationTrace(traces)\n\treturn &dt\n}", "func (m *Measurement) Record(name string, duration time.Duration) {\n\tr := m.Result(name)\n\tr.Durations = append(r.Durations, duration)\n}", "func (r *Recorder) Record(ctx context.Context, outDir string) error {\n\tvs, err := r.timeline.StopRecording(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to stop timeline\")\n\t}\n\n\tpv := perf.NewValues()\n\ttimeElapsed := time.Since(r.startTime)\n\tpv.Set(perf.Metric{\n\t\tName: \"Recorder.ElapsedTime\",\n\t\tUnit: \"s\",\n\t\tDirection: perf.SmallerIsBetter,\n\t}, float64(timeElapsed.Seconds()))\n\tpv.Merge(vs)\n\n\treturn pv.Save(outDir)\n}", "func (r *Reporter) ReportIMDSOperationDuration(operation string, duration time.Duration) error {\n\treturn r.ReportOperation(operation, ImdsOperationsDurationM.M(duration.Seconds()))\n}", "func Record(ctx context.Context, ms ...Measurement) {\n\treq := &recordReq{\n\t\tnow: time.Now(),\n\t\ttm: tag.FromContext(ctx),\n\t\tms: ms,\n\t}\n\tdefaultWorker.c <- req\n}", "func (t *testMetricsBackend) AddDuration(l metricsLabels, f float64) {\n\tt.Lock()\n\tt.durations[l] = append(t.durations[l], f)\n\tt.Unlock()\n}", "func (nsc *NilConsumerStatsCollector) UpdateGetRecordsReadResponseDuration(time.Duration) {}", "func (s Broker) TimingDuration(name string, duration time.Duration) {\n\ttimeMillis := int(duration.Nanoseconds() / 1000000)\n\ts.Timing(name, timeMillis)\n}", "func testOperationDurationMetric(t *testing.T, reporter *Reporter, m *stats.Float64Measure) {\n\tminimumDuration := float64(2)\n\tmaximumDuration := float64(4)\n\ttestOperationKey := \"test\"\n\terr := reporter.ReportOperation(testOperationKey, m.M(minimumDuration))\n\tif err != nil {\n\t\tt.Errorf(\"Error when reporting metrics: %v from %v\", err, m.Name())\n\t}\n\terr = reporter.ReportOperation(testOperationKey, m.M(maximumDuration))\n\tif err != nil {\n\t\tt.Errorf(\"Error when reporting metrics: %v from %v\", err, m.Name())\n\t}\n\n\trow, err := view.RetrieveData(m.Name())\n\tif err != nil {\n\t\tt.Errorf(\"Error when retrieving data: %v from %v\", err, m.Name())\n\t}\n\n\tduration, ok := row[0].Data.(*view.DistributionData)\n\tif !ok {\n\t\tt.Error(\"DistributionData missing\")\n\t}\n\n\ttag := row[0].Tags[0]\n\tif tag.Key.Name() != operationTypeKey.Name() && tag.Value != testOperationKey {\n\t\tt.Errorf(\"Tag does not match for %v\", operationTypeKey.Name())\n\t}\n\tif duration.Min != minimumDuration {\n\t\tt.Errorf(\"Metric: %v - Expected %v, got %v. \", m.Name(), duration.Min, minimumDuration)\n\t}\n\tif duration.Max != maximumDuration {\n\t\tt.Errorf(\"Metric: %v - Expected %v, got %v. \", m.Name(), duration.Max, maximumDuration)\n\t}\n}", "func (me *Metrics) RecordPrebidCacheRequestTime(success bool, length time.Duration) {\n\tif success {\n\t\tme.PrebidCacheRequestTimerSuccess.Update(length)\n\t} else {\n\t\tme.PrebidCacheRequestTimerError.Update(length)\n\t}\n}", "func requestMetrics(l *log.Logger) service {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstart := time.Now()\n\t\t\th.ServeHTTP(w, r)\n\t\t\tl.Printf(\"%s request to %s took %vns.\", r.Method, r.URL.Path, time.Since(start).Nanoseconds())\n\t\t})\n\t}\n}", "func RecordControllerPolicyExecTime(timer *Timer, op OperationKind, hadError bool) {\n\tif op == CreateOp {\n\t\ttimer.stopAndRecordExecTimeWithError(addPolicyExecTime, hadError)\n\t} else {\n\t\ttimer.stopAndRecordCRUDExecTime(controllerPolicyExecTime, op, hadError)\n\t}\n}", "func (client PrimitiveClient) PutDurationResponder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func Timing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tnext.ServeHTTP(w, r)\n\t\td := time.Since(start)\n\t\tlogrus.WithField(\"duration\", d).\n\t\t\tWithField(\"request_id\", GetRequestID(r.Context())).\n\t\t\tDebug(\"Request timing\")\n\t})\n}", "func recordGCDuration(duration time.Duration) {\n\tstorage.PromGCDurationMilliseconds.Observe(float64(duration.Nanoseconds()) / float64(time.Millisecond))\n}", "func RequestTimer(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tmillis := int64((time.Now().Sub(start)) / time.Millisecond)\n\t\t\tlog.Printf(\"severity=INFO RequestId=%v, Duration_ms=%v\", context.MustGetRequestId(r), millis)\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundTripper) promhttp.RoundTripperFunc {\n\treturn promhttp.RoundTripperFunc(func(r *http.Request) (*http.Response, error) {\n\t\tstart := time.Now()\n\t\tresp, err := next.RoundTrip(r)\n\t\tif err == nil {\n\t\t\tobs.With(\n\t\t\t\tprometheus.Labels{\n\t\t\t\t\t\"code\": resp.Status,\n\t\t\t\t\t\"method\": r.Method,\n\t\t\t\t\t\"host\": r.URL.Host,\n\t\t\t\t},\n\t\t\t).Observe(time.Since(start).Seconds())\n\t\t}\n\t\treturn resp, err\n\t})\n}", "func (r *receiveMessageRequestRecorder) Record(req *sqs.ReceiveMessageInput) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tr.requests = append(r.requests, req)\n}", "func (c *Prometheus) TrackRequest(r *http.Request, t timer.Timer, success bool) Client {\n\tb := bucket.NewHTTPRequest(c.httpRequestSection, r, success, c.httpMetricCallback, c.unicode)\n\tmetric := b.Metric()\n\tmetricTotal := b.MetricTotal()\n\n\tmetric = strings.Replace(metric, \"-.\", \"\", -1)\n\tmetric = strings.Replace(metric, \".-\", \"\", -1)\n\tmetric = strings.Replace(metric, \"-\", \"\", -1)\n\tmetric = strings.Replace(metric, \".\", \"_\", -1)\n\n\tmetricTotal = strings.Replace(metricTotal, \"-.\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \".-\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \"-\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \".\", \"_\", -1)\n\n\tmetricInc := c.getIncrementer(metric)\n\tmetricTotalInc := c.getIncrementer(metricTotal)\n\n\tlabels := map[string]string{\"success\": strconv.FormatBool(success), \"action\": r.Method}\n\n\tmetric = c.prepareMetric(metric)\n\tmetricTotal = c.prepareMetric(metricTotal)\n\tmetricInc.Increment(metric, labels)\n\tmetricTotalInc.Increment(metricTotal, labels)\n\n\treturn c\n}", "func (m *MockMetricsProvider) ObserveHTTPRequestDuration(method, handler, statusCode string, elapsed float64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"ObserveHTTPRequestDuration\", method, handler, statusCode, elapsed)\n}", "func sendLatency(\n\tscope tally.Scope,\n\ttable, operation string,\n\td time.Duration,\n) {\n\ts := scope.Tagged(map[string]string{\n\t\t\"table\": table,\n\t\t\"operation\": operation,\n\t})\n\ts.Timer(\"execute_latency\").Record(d)\n}", "func StatRequest(rpc string, errcode string, inTime, outTime time.Time) int64 {\n\treqCounter.With(prometheus.Labels{\n\t\t\"rpc\": rpc,\n\t\t\"errcode\": errcode,\n\t}).Inc()\n\n\tcost := toMSTimestamp(outTime) - toMSTimestamp(inTime)\n\trespTimeSummary.With(prometheus.Labels{\"rpc\": rpc}).Observe(float64(cost))\n\n\treturn cost\n}", "func (i *TelemetryStorage) RecordLatency(method string, latency time.Duration) {\n\tbucket := constants.Bucket(latency.Milliseconds())\n\tswitch method {\n\tcase constants.Treatment:\n\t\ti.latencies.treatment.Incr(bucket)\n\tcase constants.Treatments:\n\t\ti.latencies.treatments.Incr(bucket)\n\tcase constants.TreatmentWithConfig:\n\t\ti.latencies.treatmentWithConfig.Incr(bucket)\n\tcase constants.TreatmentsWithConfig:\n\t\ti.latencies.treatmentsWithConfig.Incr(bucket)\n\tcase constants.Track:\n\t\ti.latencies.track.Incr(bucket)\n\t}\n}", "func (r *RedisStorage) CountRequest(key string, requestTs time.Time, windowDuration time.Duration) (*WindowInfo, error) {\n\tcn := r.p.Get()\n\tdefer cn.Close()\n\n\tredisKey := r.getRedisKey(key)\n\tcn.Send(\"MULTI\")\n\tcn.Send(\"HINCRBY\", redisKey, noCallsField, 1)\n\tcn.Send(\"HSETNX\", redisKey, windowStartField, requestTs.UnixNano())\n\tcn.Send(\"HGET\", redisKey, windowStartField)\n\n\tvalues, err := redis.Values(cn.Do(\"EXEC\"))\n\tif err != nil {\n\t\t// in case of error happen, try to delete the key\n\t\tr.deleteKey(redisKey, cn)\n\t\treturn nil, err\n\t}\n\n\tcalls, _ := redis.Int(values[0], nil)\n\tsetStartTimeSuccess, _ := redis.Bool(values[1], nil)\n\tstartTs, _ := redis.Int64(values[2], nil)\n\n\t// if start time is set, it means the rate limit does not exist, hence set expiry time\n\tif setStartTimeSuccess {\n\t\t_, err = cn.Do(\"PEXPIREAT\", redisKey, r.keyExpiredAtInMilliSeconds(requestTs, windowDuration))\n\t\tif err != nil {\n\t\t\t// in case of error happen, try to delete the key\n\t\t\tr.deleteKey(redisKey, cn)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tinfo := &WindowInfo{\n\t\tCalls: calls,\n\t\tStartTimestamp: time.Unix(0, startTs),\n\t}\n\n\treturn info, nil\n}", "func requestSize(req *logging.WriteLogEntriesRequest) (int, error) {\n\tb, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(b), nil\n}", "func (d TestSink) Timing(c *telemetry.Context, stat string, value float64) {\n\td[stat] = TestMetric{\"Timing\", value, c.Tags()}\n}", "func (c *Client) Duration(stat string, duration time.Duration, rate float64) error {\n\treturn c.send(stat, rate, \"%d|ms\", millisecond(duration))\n}", "func (c *Stats) RecordRes(_time uint64, method string, worker_id int) {\n\tif _stats_use_channel {\n\t\tc.C_response <- _time\n\t} else {\n\t\tatomic.AddUint64(&c.totalResp, STAT_BATCH_SIZE)\n\t\tatomic.AddUint64(&c.totalRespTime, _time)\n\t}\n\n\t// if longer that 200ms, it is a slow response\n\tif _time > slowThreshold*1000000 {\n\t\tatomic.AddUint64(&c.totalResSlow, 1)\n\t}\n\n\t// record percentile\n\t//c.mu.Lock()\n\t//c.quants.Insert(float64(_time))\n\t//c.mu.Unlock()\n}", "func ReqLogger(rw *http.ResponseWriter, responseStatus *int, URL *url.URL, Method string, start *time.Time) {\n\tif *responseStatus != 200 && *responseStatus != 308 {\n\t\t(*rw).WriteHeader(*responseStatus)\n\t}\n\tlog.Printf(\"%s %s %d %s\\n\", Method, URL, *responseStatus, time.Since(*start))\n}", "func Record(h http.Handler, method, url string, headers map[string]string, payload string) *httptest.ResponseRecorder {\n\t// prepare body\n\tvar body io.Reader\n\tif payload != \"\" {\n\t\tbody = strings.NewReader(payload)\n\t}\n\n\t// create request and recorder\n\tr := httptest.NewRequest(method, url, body)\n\tw := httptest.NewRecorder()\n\n\t// set headers\n\tfor k, v := range headers {\n\t\tr.Header.Set(k, v)\n\t}\n\n\t// call handler\n\th.ServeHTTP(w, r)\n\n\treturn w\n}", "func (b *Benchttp) SendDuration(d time.Duration) *Report {\n\tb.targetDuration = d\n\treturn b.do()\n}", "func (sw *Stopwatch) Record() time.Duration {\n\td := sw.Elapsed()\n\tsw.timer.record(d)\n\treturn d\n}", "func (l *LogRequest) SetDuration(duration int64) {\n\tl.Duration = duration\n}", "func (client PrimitiveClient) PutDurationSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (zr *ZRequest) Duration() time.Duration {\n\tif zr.endTime.IsZero() {\n\t\treturn 0\n\t}\n\treturn zr.endTime.Sub(zr.startTime)\n}", "func (c *Client) RecordRequest(peerID peer.ID, req *RecordRequest) (interface{}, error) {\n\tif req == nil {\n\t\treq = &RecordRequest{\n\t\t\tRecordName: defaultRecordName,\n\t\t\tUserName: defaultRecordUserName,\n\t\t}\n\t}\n\tmarshaledData, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.GenerateStreamAndWrite(\n\t\tcontext.Background(), peerID, \"record-request\", c.IPFSAPI, marshaledData,\n\t)\n}", "func (m *MetricsProvider) ProcessDIDTime(value time.Duration) {\n}", "func (manager *Manager) RecordTime(t interface{}) {\n\tmanager.metaWG.Add(1)\n\tmanager.metadata.timings <- t\n}", "func (h *HTTP) Timing(stat string, delta int64) error {\n\treadable := time.Duration(delta).String()\n\n\th.Lock()\n\th.json.SetP(delta, stat)\n\th.json.SetP(readable, stat+\"_readable\")\n\th.Unlock()\n\treturn nil\n}", "func (lgr logger) RequestEnd(act string, startAt time.Time, status *int, errMsg *string) {\n\tlgr.client.Sugar().Infow(\"http_request\",\n\t\t\"action\", act,\n\t\t\"status_code\", status,\n\t\t\"error_message\", errMsg,\n\t\t\"created_at\", startAt.Unix(),\n\t\t\"response_time\", fmt.Sprintf(\"%.4f\", time.Since(startAt).Seconds()))\n}", "func incrRequestStatDelta() {\n\tStatMu.Mutex.Lock()\n\n\t// increment the requests counter\n\t*(StatMu.InstanceStat.Requests) = *(StatMu.InstanceStat.Requests) + uint64(1)\n\tStatMu.Mutex.Unlock()\n\n}", "func calculateDuration(r *record) time.Duration {\n\tdateFormat := \"2006-01-0215:04:05\"\n\n\tstart, err := time.Parse(dateFormat, r.date+r.startTime)\n\tcheckErr(err)\n\n\tend, err := time.Parse(dateFormat, r.date+r.endTime)\n\tcheckErr(err)\n\n\tpause, err := time.ParseDuration(r.pause)\n\tcheckErr(err)\n\n\treturn end.Sub(start) - pause\n}", "func (me *Metrics) RecordOverheadTime(overhead OverheadType, length time.Duration) {\n\tme.OverheadTimer[overhead].Update(length)\n}", "func (client PrimitiveClient) GetDurationResponder(resp *http.Response) (result DurationWrapper, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n}", "func keyDuration(oid int64) string {\n\treturn _keyDuration + strconv.FormatInt(oid, 10)\n}", "func main() {\n\tinitFlag()\n\n\tts := status.NewTimerStatus()\n\tts.SetTimerDump(time.Duration(duration)*time.Second, func() {\n\t\tb := bytes.NewBuffer([]byte{})\n\t\tts.DumpCount(b)\n\t\tfmt.Printf(\"%v\\n\", string(b.Bytes()))\n\t})\n\n\tvar wg sync.WaitGroup\n\tfor c := 0; c < concurrence; c++ {\n\t\tgo request(&wg, ts)\n\t\twg.Add(1)\n\t}\n\n\twg.Wait()\n}", "func logEndOfRequest(\n\tr *stdhttp.Request,\n\tduration time.Duration,\n\tmw mutil.WriterProxy,\n) {\n\tl := log.Ctx(r.Context()).WithFields(log.F{\n\t\t\"subsys\": \"http\",\n\t\t\"path\": r.URL.String(),\n\t\t\"method\": r.Method,\n\t\t\"status\": mw.Status(),\n\t\t\"bytes\": mw.BytesWritten(),\n\t\t\"duration\": duration,\n\t})\n\tif routeContext := chi.RouteContext(r.Context()); routeContext != nil {\n\t\tl = l.WithField(\"route\", routeContext.RoutePattern())\n\t}\n\tl.Info(\"finished request\")\n}", "func (r *ApacheLogRecord) formattedTimeRequest() (string, string) {\n\treturn r.time.Format(timeFormat), fmt.Sprintf(requestFormat, r.method, r.uri, r.protocol)\n}", "func (r *Reporter) Timing(metricName string, value time.Duration, tags metrics.Tags) error {\n\treturn nil\n}", "func decodeReq(req logql.QueryParams) ([]*labels.Matcher, model.Time, model.Time, error) {\n\texpr, err := req.LogSelector()\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\n\tmatchers := expr.Matchers()\n\tnameLabelMatcher, err := labels.NewMatcher(labels.MatchEqual, labels.MetricName, \"logs\")\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\tmatchers = append(matchers, nameLabelMatcher)\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\tmatchers, err = injectShardLabel(req.GetShards(), matchers)\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\tfrom, through := util.RoundToMilliseconds(req.GetStart(), req.GetEnd())\n\treturn matchers, from, through, nil\n}", "func (nsc *NilConsumerStatsCollector) UpdateGetRecordsUnmarshalDuration(time.Duration) {}", "func (nsc *NilConsumerStatsCollector) AddGetRecordsTimeout(int) {}", "func (client PrimitiveClient) GetDurationSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (r RecordTTL) Duration() time.Duration {\n\treturn (time.Second * time.Duration(int(r)))\n}", "func MetricMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tt := metrics.NewTimer(serverRequestDuration.WithLabels(c.Request.URL.Path))\n\t\tdefer t.ObserveDuration()\n\t\tc.Next()\n\t}\n}", "func (om OperationMetric) Duration() time.Duration {\n\tif om.Start.IsZero() {\n\t\treturn 0\n\t}\n\treturn om.End.Time.Sub(om.Start.Time)\n}", "func (p *Prometheus) ObserveDurationResourceAddEventProcessedSuccess(handler string, start time.Time) {\n\td := p.getDuration(start)\n\tp.processedSucDuration.WithLabelValues(handler, addEventType).Observe(d.Seconds())\n}", "func UpdateDuration(label FunctionLabel, duration time.Duration) {\n\t// TODO(maciekpytel): remove second condition if we manage to get\n\t// asynchronous node drain\n\tif duration > LogLongDurationThreshold && label != ScaleDown {\n\t\tklog.V(4).Infof(\"Function %s took %v to complete\", label, duration)\n\t}\n\tfunctionDuration.WithLabelValues(string(label)).Observe(duration.Seconds())\n\tfunctionDurationSummary.WithLabelValues(string(label)).Observe(duration.Seconds())\n}", "func (o QuotaLimitResponseOutput) Duration() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.Duration }).(pulumi.StringOutput)\n}", "func (me *Metrics) RecordAdapterRequest(labels AdapterLabels) {\n\tam, ok := me.AdapterMetrics[labels.Adapter]\n\tif !ok {\n\t\tglog.Errorf(\"Trying to run adapter metrics on %s: adapter metrics not found\", string(labels.Adapter))\n\t\treturn\n\t}\n\n\taam, ok := me.getAccountMetrics(labels.PubID).adapterMetrics[labels.Adapter]\n\tswitch labels.AdapterBids {\n\tcase AdapterBidNone:\n\t\tam.NoBidMeter.Mark(1)\n\t\tif ok {\n\t\t\taam.NoBidMeter.Mark(1)\n\t\t}\n\tcase AdapterBidPresent:\n\t\tam.GotBidsMeter.Mark(1)\n\t\tif ok {\n\t\t\taam.GotBidsMeter.Mark(1)\n\t\t}\n\tdefault:\n\t\tglog.Warningf(\"No go-metrics logged for AdapterBids value: %s\", labels.AdapterBids)\n\t}\n\tfor errType := range labels.AdapterErrors {\n\t\tam.ErrorMeters[errType].Mark(1)\n\t}\n\n\tif labels.CookieFlag == CookieFlagNo {\n\t\tam.NoCookieMeter.Mark(1)\n\t}\n}", "func RegisterDuration(key string, def time.Duration, description string) onion.Int {\n\tsetDescription(key, description)\n\treturn o.RegisterDuration(key, def)\n}", "func (tcr *TestCaseReporter) Duration() time.Duration {\n\tif tcr.startTime.IsZero() || tcr.endTime.IsZero() {\n\t\treturn 0\n\t}\n\n\treturn tcr.endTime.Sub(tcr.startTime)\n}", "func (c *volumeSeriesRequestCmd) makeRecord(o *models.VolumeSeriesRequest, now time.Time) map[string]string {\n\tvar cluster string\n\tif cn, ok := c.clusters[string(o.ClusterID)]; ok { // assume map\n\t\tcluster = cn.name\n\t} else {\n\t\tcluster = string(o.ClusterID)\n\t}\n\tvar node string\n\tif cn, ok := c.nodes[string(o.NodeID)]; ok { // assume map\n\t\tnode = cn.name\n\t} else {\n\t\tnode = string(o.NodeID)\n\t}\n\tobj := string(o.VolumeSeriesID)\n\tif util.Contains(o.RequestedOperations, common.VolReqOpCGCreateSnapshot) {\n\t\tobj = string(o.ConsistencyGroupID)\n\t}\n\tif util.Contains(o.RequestedOperations, common.VolReqOpAllocateCapacity) {\n\t\tobj = string(o.ServicePlanAllocationID)\n\t}\n\tpct := \"\"\n\tif o.Progress != nil {\n\t\tpct = fmt.Sprintf(\"%d%%\", swag.Int32Value(o.Progress.PercentComplete))\n\t}\n\tvar tDur string\n\tif util.Contains(terminalVolumeSeriesRequestStates, o.VolumeSeriesRequestState) {\n\t\ttDur = fmt.Sprintf(\"%s\", time.Time(o.Meta.TimeModified).Sub(time.Time(o.Meta.TimeCreated)).Round(time.Millisecond))\n\t\tpct = \"\"\n\t} else {\n\t\tc.activeReq = true\n\t\ttDur = fmt.Sprintf(\"%s\", now.Sub(time.Time(o.Meta.TimeCreated)).Round(time.Second))\n\t}\n\treturn map[string]string{\n\t\thCluster: cluster,\n\t\thCompleteBy: time.Time(o.CompleteByTime).Format(time.RFC3339),\n\t\thID: string(o.Meta.ID),\n\t\thNode: node,\n\t\thRequestState: o.VolumeSeriesRequestState,\n\t\thRequestedOperations: strings.Join(o.RequestedOperations, \", \"),\n\t\thTimeCreated: time.Time(o.Meta.TimeCreated).Format(time.RFC3339),\n\t\thTimeModified: time.Time(o.Meta.TimeModified).Format(time.RFC3339),\n\t\thVsID: string(o.VolumeSeriesID),\n\t\thTimeDuration: tDur,\n\t\thObjectID: obj,\n\t\thProgress: pct,\n\t}\n}", "func (s *Stats) record(rpcStats stats.RPCStats) {\n\tswitch v := rpcStats.(type) {\n\tcase *stats.InHeader:\n\t\ts.Lock()\n\t\tatomic.AddInt64(&s.respSize, int64(v.WireLength))\n\t\ts.respHeaders = v.Header.Copy()\n\t\ts.Unlock()\n\tcase *stats.InPayload:\n\t\tatomic.AddInt64(&s.respSize, int64(v.WireLength))\n\tcase *stats.InTrailer:\n\t\tatomic.AddInt64(&s.respSize, int64(v.WireLength))\n\t\ts.Lock()\n\t\ts.respTrailers = v.Trailer.Copy()\n\t\ts.Unlock()\n\tcase *stats.OutHeader:\n\t\t// No wire length.\n\t\ts.Lock()\n\t\ts.reqHeaders = v.Header.Copy()\n\t\ts.fullMethod = v.FullMethod\n\t\ts.Unlock()\n\tcase *stats.OutPayload:\n\t\tatomic.AddInt64(&s.reqSize, int64(v.WireLength))\n\tcase *stats.OutTrailer:\n\t\tatomic.AddInt64(&s.reqSize, int64(v.WireLength))\n\tcase *stats.End:\n\t\ts.Duration = v.EndTime.Sub(v.BeginTime)\n\t}\n}", "func (s *service) reqHandler(endpoint *Endpoint, req *request) {\n\tstart := time.Now()\n\tendpoint.Handler.Handle(req)\n\ts.m.Lock()\n\tendpoint.stats.NumRequests++\n\tendpoint.stats.ProcessingTime += time.Since(start)\n\tavgProcessingTime := endpoint.stats.ProcessingTime.Nanoseconds() / int64(endpoint.stats.NumRequests)\n\tendpoint.stats.AverageProcessingTime = time.Duration(avgProcessingTime)\n\n\tif req.respondError != nil {\n\t\tendpoint.stats.NumErrors++\n\t\tendpoint.stats.LastError = req.respondError.Error()\n\t}\n\ts.m.Unlock()\n}", "func (s *DevStat) AddSentDuration(start time.Time, duration time.Duration) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\t//only register the first start time on concurrent mode\n\tif s.Counters[BackEndSentStartTime] == 0 {\n\t\ts.Counters[BackEndSentStartTime] = start.Unix()\n\t}\n\ts.Counters[BackEndSentDuration] = s.Counters[BackEndSentDuration].(float64) + duration.Seconds()\n}", "func (c *LoggerClient) Timing(name string, value time.Duration) {\n\tc.print(\"Timing\", name, value, value)\n}", "func MetricsMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tt := time.Now()\n\n\t\t// Call next to jump into the next handler.\n\t\tc.Next()\n\n\t\ttook := time.Since(t).String()\n\n\t\tlog.\n\t\t\tWith(\n\t\t\t\tzap.String(\"path\", c.Request.RequestURI),\n\t\t\t\tzap.String(\"took\", took),\n\t\t\t).\n\t\t\tDebug(\"request end\")\n\t}\n}", "func tickTimeHandler(duration string) http.HandlerFunc {\n\treturn func(respWriter http.ResponseWriter, request *http.Request) {\n\t\trespWriter.Write([]byte(duration))\n\t}\n}", "func (e *RuntimeStat) Record(d time.Duration, rowNum int) {\n\tatomic.AddInt32(&e.loop, 1)\n\tatomic.AddInt64(&e.consume, int64(d))\n\tatomic.AddInt64(&e.rows, int64(rowNum))\n}", "func (mr *MockMetricsProviderMockRecorder) ObserveHTTPRequestDuration(method, handler, statusCode, elapsed interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ObserveHTTPRequestDuration\", reflect.TypeOf((*MockMetricsProvider)(nil).ObserveHTTPRequestDuration), method, handler, statusCode, elapsed)\n}", "func LogRequest(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t// Start timer\n\t\tstart := time.Now()\n\n\t\t// Add a requestID field to logger\n\t\tuid, _ := ulid.NewFromTime(start)\n\t\tl := log.With(zap.String(\"requestID\", uid.String()))\n\t\t// Add logger to context\n\t\tctx := context.WithValue(r.Context(), requestIDKey, l)\n\t\t// Request with this new context.\n\t\tr = r.WithContext(ctx)\n\n\t\t// wrap the ResponseWriter\n\t\tlw := &basicWriter{ResponseWriter: w}\n\n\t\t// Get the real IP even behind a proxy\n\t\trealIP := r.Header.Get(http.CanonicalHeaderKey(\"X-Forwarded-For\"))\n\t\tif realIP == \"\" {\n\t\t\t// if no content in header \"X-Forwarded-For\", get \"X-Real-IP\"\n\t\t\tif xrip := r.Header.Get(http.CanonicalHeaderKey(\"X-Real-IP\")); xrip != \"\" {\n\t\t\t\trealIP = xrip\n\t\t\t} else {\n\t\t\t\trealIP = r.RemoteAddr\n\t\t\t}\n\t\t}\n\n\t\t// Process request\n\t\tnext.ServeHTTP(lw, r)\n\t\tlw.maybeWriteHeader()\n\n\t\t// Stop timer\n\t\tend := time.Now()\n\t\tlatency := end.Sub(start)\n\t\tstatusCode := lw.Status()\n\n\t\tl.Info(\"request\",\n\t\t\tzap.String(\"method\", r.Method),\n\t\t\tzap.String(\"url\", r.RequestURI),\n\t\t\tzap.Int(\"code\", statusCode),\n\t\t\tzap.String(\"clientIP\", realIP),\n\t\t\tzap.Int(\"bytes\", lw.bytes),\n\t\t\tzap.Int64(\"duration\", int64(latency)/int64(time.Microsecond)),\n\t\t)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func SendProcessMetrics() {\n\n c := h.NewClient(ip, port)\n\n processMetrics := s.ProcessMeasurement{\n TimeSlice: timeSlice,\n CpuUsed: cpu,\n MemUsed: mem,\n }\n\n\n path := fmt.Sprintf(\"/v1/metrics/nodes/%s/process/%s/\", nodeName, processName)\n req, _ := c.NewRequest(\"POST\", path, processMetrics)\n\n\n var processMeasurement s.ProcessMeasurement\n\n c.Do(req, &processMeasurement)\n\n\n //fmt.Printf(\"PROCESS MEASUREMENT SENT: %s\\n\", u.PrettyPrint(processMeasurement))\n\n}", "func (m Metric) AddMethodDuration() {\n\tif m.startTime.Equal(time.Time{}) {\n\t\tpanic(\"not initialised method\")\n\t}\n\n\tdur := time.Now().Sub(m.startTime)\n\tm.backend.AddMethodDuration(m.asset, m.methodName, dur)\n}", "func record(ctx context.Context, ms ...stats.Measurement) {\n\tstats.Record(ctx, ms...)\n}", "func (c *Client) Duration(name string, duration time.Duration) error {\n\treturn c.Histogram(name, millisecond(duration))\n}", "func (recorder *ReqRecorder) CloseAfter(dur time.Duration) {\n\tgo func() {\n\t\t<-time.NewTimer(dur).C\n\t\trecorder.Close()\n\t}()\n}", "func (r *Reporter) ReportCloudProviderOperationDuration(operation string, duration time.Duration) error {\n\treturn r.ReportOperation(operation, CloudProviderOperationsDurationM.M(duration.Seconds()))\n}", "func Durations(statsd io.Writer, key string, interval time.Duration, next http.Handler) http.Handler {\n\t// buffered - reporting is concurrent with the handler\n\tdurations := make(chan time.Duration, 1)\n\tgo reportDurations(statsd, key, time.Tick(interval), durations)\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tnext.ServeHTTP(w, r)\n\t\tdurations <- time.Now().Sub(start)\n\t})\n}", "func (c *MockedHTTPContext) Duration() time.Duration {\n\tif c.MockedDuration != nil {\n\t\treturn c.MockedDuration()\n\t}\n\treturn 0\n}", "func (s *Sample) AddSize(t time.Duration, size int64) *Sample {\n\tatomic.AddInt64(&s.Count, 1)\n\n\tp1 := float64(s.TimeSleep) * 0.01\n\tp10 := float64(s.TimeSleep) * 0.10\n\tp50 := float64(s.TimeSleep) / 2\n\tp97 := float64(s.TimeSleep) * 0.97\n\tp99 := float64(s.TimeSleep) * 0.99\n\n\ts.Lock()\n\tif t.Seconds() <= p1 {\n\t\ts.MetricReqSec.P1++\n\t\ts.MetricBodySize.P1 = size\n\t} else if t.Seconds() > p1 && t.Seconds() <= p10 {\n\t\tif s.MetricReqSec.P10 == 0 {\n\t\t\ts.MetricReqSec.P10 = s.MetricReqSec.P1\n\t\t}\n\t\ts.MetricReqSec.P10++\n\t\ts.MetricBodySize.P10 = size\n\t} else if t.Seconds() > p10 && t.Seconds() <= p50 {\n\t\tif s.MetricReqSec.P50 == 0 {\n\t\t\ts.MetricReqSec.P50 = s.MetricReqSec.P10\n\t\t}\n\t\ts.MetricReqSec.P50++\n\t\ts.MetricBodySize.P50 = size\n\t} else if t.Seconds() > p50 && t.Seconds() <= p97 {\n\t\tif s.MetricReqSec.P50 == 0 {\n\t\t\ts.MetricReqSec.P97 = s.MetricReqSec.P50\n\t\t}\n\t\ts.MetricReqSec.P97++\n\t\ts.MetricBodySize.P97 = size\n\t} else if t.Seconds() > p97 && t.Seconds() <= p99 {\n\t\tif s.MetricReqSec.P99 == 0 {\n\t\t\ts.MetricReqSec.P99 = s.MetricReqSec.P97\n\t\t}\n\t\ts.MetricReqSec.P99++\n\t\ts.MetricBodySize.P99 = size\n\t}\n\ts.Unlock()\n\n\treturn s\n}" ]
[ "0.7509087", "0.6741319", "0.6448921", "0.601776", "0.58529365", "0.5823079", "0.573807", "0.5685555", "0.5597103", "0.5575818", "0.5555443", "0.55546105", "0.5551546", "0.5550965", "0.54829746", "0.54797477", "0.54717624", "0.5451511", "0.5430681", "0.5402279", "0.5385498", "0.5377787", "0.53304756", "0.53281516", "0.5317965", "0.5272165", "0.5253002", "0.5242636", "0.5233388", "0.5230767", "0.52152526", "0.52083653", "0.5202938", "0.5197928", "0.5194526", "0.51936924", "0.5159126", "0.5136083", "0.51281834", "0.5119417", "0.5098883", "0.50976866", "0.5070719", "0.5068659", "0.50644505", "0.5064108", "0.5023322", "0.50129795", "0.50084126", "0.49975514", "0.49836764", "0.49755657", "0.49568585", "0.49339178", "0.49257052", "0.4923151", "0.49154618", "0.49136826", "0.49042365", "0.48974466", "0.48961392", "0.48869568", "0.48820713", "0.48789236", "0.48781618", "0.4873461", "0.48733985", "0.48703533", "0.4858786", "0.4848095", "0.48364103", "0.48281088", "0.48268193", "0.48108876", "0.48069996", "0.48002437", "0.47964936", "0.4794554", "0.47922572", "0.4782552", "0.47766417", "0.47728422", "0.47690332", "0.47645664", "0.47587913", "0.47578958", "0.4753405", "0.47462896", "0.47443977", "0.4741586", "0.47077897", "0.4700519", "0.4699927", "0.46984392", "0.46982118", "0.4693301", "0.46869275", "0.46868104", "0.4682211", "0.46795297" ]
0.83944345
0
CreateListFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
CreateListFromDiscriminatorValue создает новый экземпляр соответствующего класса на основе значения дискриминатора
func CreateListFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewList(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateBrowserSiteListFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBrowserSiteList(), nil\n}", "func CreateSharepointIdsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSharepointIds(), nil\n}", "func CreateVulnerabilityFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewVulnerability(), nil\n}", "func CreateDetectionRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDetectionRule(), nil\n}", "func CreateDeviceCategoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCategory(), nil\n}", "func CreateIosDeviceFeaturesConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosDeviceFeaturesConfiguration(), nil\n}", "func CreateCloudCommunicationsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCloudCommunications(), nil\n}", "func CreateSiteCollectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSiteCollection(), nil\n}", "func CreateWin32LobAppRegistryRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryRule(), nil\n}", "func CreateSetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSet(), nil\n}", "func CreateWin32LobAppRegistryDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryDetection(), nil\n}", "func CreateDeviceCompliancePolicyPolicySetItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCompliancePolicyPolicySetItem(), nil\n}", "func CreateSchemaFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSchema(), nil\n}", "func CreatePlannerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPlanner(), nil\n}", "func CreateRoleDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.deviceAndAppManagementRoleDefinition\":\n return NewDeviceAndAppManagementRoleDefinition(), nil\n }\n }\n }\n }\n return NewRoleDefinition(), nil\n}", "func CreateDriveFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDrive(), nil\n}", "func CreateDirectoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDirectory(), nil\n}", "func CreateGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGroup(), nil\n}", "func CreatePolicyRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.networkaccess.forwardingRule\":\n return NewForwardingRule(), nil\n case \"#microsoft.graph.networkaccess.m365ForwardingRule\":\n return NewM365ForwardingRule(), nil\n case \"#microsoft.graph.networkaccess.privateAccessForwardingRule\":\n return NewPrivateAccessForwardingRule(), nil\n }\n }\n }\n }\n return NewPolicyRule(), nil\n}", "func CreateItemFacetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.educationalActivity\":\n return NewEducationalActivity(), nil\n case \"#microsoft.graph.itemAddress\":\n return NewItemAddress(), nil\n case \"#microsoft.graph.itemEmail\":\n return NewItemEmail(), nil\n case \"#microsoft.graph.itemPatent\":\n return NewItemPatent(), nil\n case \"#microsoft.graph.itemPhone\":\n return NewItemPhone(), nil\n case \"#microsoft.graph.itemPublication\":\n return NewItemPublication(), nil\n case \"#microsoft.graph.languageProficiency\":\n return NewLanguageProficiency(), nil\n case \"#microsoft.graph.personAnnotation\":\n return NewPersonAnnotation(), nil\n case \"#microsoft.graph.personAnnualEvent\":\n return NewPersonAnnualEvent(), nil\n case \"#microsoft.graph.personAward\":\n return NewPersonAward(), nil\n case \"#microsoft.graph.personCertification\":\n return NewPersonCertification(), nil\n case \"#microsoft.graph.personInterest\":\n return NewPersonInterest(), nil\n case \"#microsoft.graph.personName\":\n return NewPersonName(), nil\n case \"#microsoft.graph.personResponsibility\":\n return NewPersonResponsibility(), nil\n case \"#microsoft.graph.personWebsite\":\n return NewPersonWebsite(), nil\n case \"#microsoft.graph.projectParticipation\":\n return NewProjectParticipation(), nil\n case \"#microsoft.graph.skillProficiency\":\n return NewSkillProficiency(), nil\n case \"#microsoft.graph.userAccountInformation\":\n return NewUserAccountInformation(), nil\n case \"#microsoft.graph.webAccount\":\n return NewWebAccount(), nil\n case \"#microsoft.graph.workPosition\":\n return NewWorkPosition(), nil\n }\n }\n }\n }\n return NewItemFacet(), nil\n}", "func CreateIosDeviceTypeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosDeviceType(), nil\n}", "func CreateScheduleItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewScheduleItem(), nil\n}", "func CreateSearchAlterationOptionsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSearchAlterationOptions(), nil\n}", "func CreateWindowsInformationProtectionDeviceRegistrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsInformationProtectionDeviceRegistration(), nil\n}", "func CreateVppTokenFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewVppToken(), nil\n}", "func CreateRegistryKeyStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRegistryKeyState(), nil\n}", "func CreateConditionalAccessDeviceStatesFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewConditionalAccessDeviceStates(), nil\n}", "func CreateBusinessScenarioPlannerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBusinessScenarioPlanner(), nil\n}", "func CreateDomainSecurityProfileCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDomainSecurityProfileCollectionResponse(), nil\n}", "func CreateDeviceManagementIntentDeviceStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementIntentDeviceState(), nil\n}", "func CreateMessageRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMessageRule(), nil\n}", "func CreateHeadersFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewHeaders(), nil\n}", "func CreateApplicationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewApplication(), nil\n}", "func CreateDomainCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDomainCollectionResponse(), nil\n}", "func CreateAndroidCustomConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidCustomConfiguration(), nil\n}", "func CreateDeviceManagementSettingsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementSettings(), nil\n}", "func CreateDeviceManagementConfigurationPolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementConfigurationPolicy(), nil\n}", "func CreateSettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSetting(), nil\n}", "func CreateGroupPolicyDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGroupPolicyDefinition(), nil\n}", "func CreateSchemaExtensionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSchemaExtension(), nil\n}", "func CreateTemplateParameterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewTemplateParameter(), nil\n}", "func CreateRecurrenceRangeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRecurrenceRange(), nil\n}", "func CreateVpnConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.androidDeviceOwnerVpnConfiguration\":\n return NewAndroidDeviceOwnerVpnConfiguration(), nil\n }\n }\n }\n }\n return NewVpnConfiguration(), nil\n}", "func CreatePrinterCreateOperationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPrinterCreateOperation(), nil\n}", "func CreatePrinterCreateOperationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPrinterCreateOperation(), nil\n}", "func CreateDeviceManagementSettingDependencyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementSettingDependency(), nil\n}", "func CreatePrinterDefaultsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPrinterDefaults(), nil\n}", "func CreateDeviceAndAppManagementAssignmentFilterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.payloadCompatibleAssignmentFilter\":\n return NewPayloadCompatibleAssignmentFilter(), nil\n }\n }\n }\n }\n return NewDeviceAndAppManagementAssignmentFilter(), nil\n}", "func CreateDeviceCompliancePolicyCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCompliancePolicyCollectionResponse(), nil\n}", "func CreateTeamworkActivePeripheralsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewTeamworkActivePeripherals(), nil\n}", "func CreateConnectedOrganizationMembersFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewConnectedOrganizationMembers(), nil\n}", "func CreateTargetManagerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewTargetManager(), nil\n}", "func CreateWebPartDataFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWebPartData(), nil\n}", "func CreateMeetingParticipantsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMeetingParticipants(), nil\n}", "func CreateProtectGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewProtectGroup(), nil\n}", "func CreateDiscoveredSensitiveTypeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDiscoveredSensitiveType(), nil\n}", "func CreateManagementTemplateStepFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewManagementTemplateStep(), nil\n}", "func CreateRecurrencePatternFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRecurrencePattern(), nil\n}", "func CreateWin32LobAppFileSystemDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppFileSystemDetection(), nil\n}", "func CreateAndroidLobAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidLobApp(), nil\n}", "func CreateMediaFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMedia(), nil\n}", "func CreateUserFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUser(), nil\n}", "func CreateOnPremisesExtensionAttributesFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewOnPremisesExtensionAttributes(), nil\n}", "func CreateCommunicationsIdentitySetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCommunicationsIdentitySet(), nil\n}", "func CreateWorkforceIntegrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkforceIntegration(), nil\n}", "func CreateWorkbookFilterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookFilter(), nil\n}", "func CreateWin32LobAppProductCodeDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppProductCodeDetection(), nil\n}", "func CreateReportsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewReports(), nil\n}", "func CreateSearchBucketFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSearchBucket(), nil\n}", "func CreateSmsLogRowFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSmsLogRow(), nil\n}", "func CreateSubCategoryTemplateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSubCategoryTemplate(), nil\n}", "func CreateFederatedTokenValidationPolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewFederatedTokenValidationPolicy(), nil\n}", "func CreateBookingBusinessFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBookingBusiness(), nil\n}", "func CreateDeviceManagementConfigurationSettingGroupDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.deviceManagementConfigurationSettingGroupCollectionDefinition\":\n return NewDeviceManagementConfigurationSettingGroupCollectionDefinition(), nil\n }\n }\n }\n }\n return NewDeviceManagementConfigurationSettingGroupDefinition(), nil\n}", "func CreateUserExperienceAnalyticsDeviceStartupHistoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUserExperienceAnalyticsDeviceStartupHistory(), nil\n}", "func CreateOpenTypeExtensionCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewOpenTypeExtensionCollectionResponse(), nil\n}", "func CreateAuthenticationCombinationConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.fido2CombinationConfiguration\":\n return NewFido2CombinationConfiguration(), nil\n }\n }\n }\n }\n return NewAuthenticationCombinationConfiguration(), nil\n}", "func CreateCatalogContentFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCatalogContent(), nil\n}", "func CreateAttachmentItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAttachmentItem(), nil\n}", "func CreateMalwareFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMalware(), nil\n}", "func CreateReminderFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewReminder(), nil\n}", "func CreateUpdateAllowedCombinationsResultFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUpdateAllowedCombinationsResult(), nil\n}", "func CreateDirectorySettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDirectorySetting(), nil\n}", "func CreateKeyValueFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewKeyValue(), nil\n}", "func CreateManagedDeviceComplianceCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewManagedDeviceComplianceCollectionResponse(), nil\n}", "func CreateRelatedContactFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRelatedContact(), nil\n}", "func CreateDeviceManagementConfigurationSettingDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.deviceManagementConfigurationChoiceSettingCollectionDefinition\":\n return NewDeviceManagementConfigurationChoiceSettingCollectionDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationChoiceSettingDefinition\":\n return NewDeviceManagementConfigurationChoiceSettingDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationRedirectSettingDefinition\":\n return NewDeviceManagementConfigurationRedirectSettingDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSettingGroupCollectionDefinition\":\n return NewDeviceManagementConfigurationSettingGroupCollectionDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSettingGroupDefinition\":\n return NewDeviceManagementConfigurationSettingGroupDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSimpleSettingCollectionDefinition\":\n return NewDeviceManagementConfigurationSimpleSettingCollectionDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSimpleSettingDefinition\":\n return NewDeviceManagementConfigurationSimpleSettingDefinition(), nil\n }\n }\n }\n }\n return NewDeviceManagementConfigurationSettingDefinition(), nil\n}", "func CreateIosCustomConfigurationCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosCustomConfigurationCollectionResponse(), nil\n}", "func CreateCommsNotificationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCommsNotification(), nil\n}", "func CreateGovernancePolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGovernancePolicy(), nil\n}", "func CreateCreatePostRequestBodyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCreatePostRequestBody(), nil\n}", "func CreateCalendarGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCalendarGroup(), nil\n}", "func CreateFileDataConnectorFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.industryData.azureDataLakeConnector\":\n return NewAzureDataLakeConnector(), nil\n }\n }\n }\n }\n return NewFileDataConnector(), nil\n}", "func CreateMessageSecurityStateCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMessageSecurityStateCollectionResponse(), nil\n}", "func CreateEntitlementManagementSettingsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewEntitlementManagementSettings(), nil\n}", "func CreateConnectorStatusDetailsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewConnectorStatusDetails(), nil\n}", "func CreateAttributeSetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAttributeSet(), nil\n}", "func CreateDeviceManagementConfigurationSettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementConfigurationSetting(), nil\n}", "func CreateDeviceComplianceScriptDeviceStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceComplianceScriptDeviceState(), nil\n}", "func CreateBusinessFlowCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBusinessFlowCollectionResponse(), nil\n}" ]
[ "0.7130501", "0.65420735", "0.6469803", "0.63655806", "0.62998223", "0.62049437", "0.61957437", "0.61202574", "0.61152625", "0.6078244", "0.6048618", "0.60275096", "0.601459", "0.59926915", "0.596089", "0.59600526", "0.5952939", "0.59473586", "0.59227026", "0.59070474", "0.58590144", "0.5850004", "0.5829843", "0.5820803", "0.5817381", "0.5793375", "0.5789015", "0.57866937", "0.57807994", "0.575407", "0.5753894", "0.57476324", "0.57454354", "0.5743987", "0.57437134", "0.5741936", "0.5731635", "0.5717699", "0.571719", "0.5714152", "0.5693347", "0.56809604", "0.56743646", "0.56736016", "0.56736016", "0.5669824", "0.56679684", "0.5666755", "0.56599194", "0.56526804", "0.5643918", "0.5643824", "0.56372964", "0.5636759", "0.56349", "0.56322676", "0.56302387", "0.56196856", "0.5613785", "0.56066513", "0.56049615", "0.5604105", "0.5590915", "0.5588215", "0.5581597", "0.5580076", "0.5575741", "0.5574731", "0.5573298", "0.55705905", "0.55693966", "0.5568692", "0.5564955", "0.55610335", "0.5555037", "0.5549514", "0.55431557", "0.5540566", "0.5531157", "0.55211085", "0.5519989", "0.55188525", "0.5514902", "0.5511952", "0.55002797", "0.54991436", "0.5494518", "0.5491884", "0.5488574", "0.5486759", "0.5486097", "0.54837155", "0.54818016", "0.54793787", "0.5476269", "0.54755056", "0.54741645", "0.54715306", "0.5460713", "0.5459562" ]
0.85900795
0
GetColumns gets the columns property value. The collection of field definitions for this list.
GetColumns получает значение свойства columns. Коллекция определений полей для этого списка.
func (m *List) GetColumns()([]ColumnDefinitionable) { return m.columns }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Model) GetColumns() []Column {\n\treturn m.Columns\n}", "func (fmd *FakeMysqlDaemon) GetColumns(ctx context.Context, dbName, table string) ([]*querypb.Field, []string, error) {\n\treturn []*querypb.Field{}, []string{}, nil\n}", "func (c *Client) GetColumns(sheetID string) (cols []Column, err error) {\n\tpath := fmt.Sprintf(\"sheets/%v/columns\", sheetID)\n\n\tbody, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer body.Close()\n\n\tvar resp PaginatedResponse\n\t//TODO: need generic handling and ability to read from pages to get all datc... eventually\n\tdec := json.NewDecoder(body)\n\tif err = dec.Decode(&resp); err != nil {\n\t\tlog.Fatalf(\"Failed to decode: %v\\n\", err)\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(resp.Data, &cols); err != nil {\n\t\tlog.Fatalf(\"Failed to decode data: %v\\n\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func (o *TelemetryDruidScanRequestAllOf) GetColumns() []string {\n\tif o == nil || o.Columns == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.Columns\n}", "func (qi *QueryIterator) GetColumns() ([]string, error) {\n\tif qi.schema == nil {\n\t\treturn nil, errors.New(\"Failed to get table schema\")\n\t}\n\tvar result = make([]string, 0)\n\tfor _, field := range qi.schema.Fields {\n\t\tresult = append(result, field.Name)\n\t}\n\treturn result, nil\n}", "func (d *dbBase) GetColumns(ctx context.Context, db dbQuerier, table string) (map[string][3]string, error) {\n\tcolumns := make(map[string][3]string)\n\tquery := d.ins.ShowColumnsQuery(table)\n\trows, err := db.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn columns, err\n\t}\n\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tname string\n\t\t\ttyp string\n\t\t\tnull string\n\t\t)\n\t\terr := rows.Scan(&name, &typ, &null)\n\t\tif err != nil {\n\t\t\treturn columns, err\n\t\t}\n\t\tcolumns[name] = [3]string{name, typ, null}\n\t}\n\n\treturn columns, nil\n}", "func (_m *RepositoryMock) GetColumns() []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\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (d *dnfEventPrizeDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (c *Client) GetColumns(dbTableName string) (columns []string, err error) {\n\ttype describeTable struct {\n\t\tData []map[string]string `json:\"data\"`\n\t}\n\n\tvar desc describeTable\n\n\terr = c.Do(http.MethodGet, nil, \"applicaiton/json\", &desc, \"/?query=DESCRIBE%%20%s%%20FORMAT%%20JSON\", dbTableName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get describe of %s: %v\", dbTableName, err)\n\t}\n\n\tfor _, column := range desc.Data {\n\t\tfor key, value := range column {\n\t\t\tif key == \"name\" {\n\t\t\t\tcolumns = append(columns, value)\n\t\t\t}\n\t\t}\n\t}\n\treturn columns, nil\n}", "func (d *maxCountChannelDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (d *tmpCharacDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (o *SummaryResponse) GetColumns() SummaryColumnResponse {\n\tif o == nil || o.Columns == nil {\n\t\tvar ret SummaryColumnResponse\n\t\treturn ret\n\t}\n\treturn *o.Columns\n}", "func GetColumns(tmap *gorp.TableMap) (columns []string) {\n\n\tfor index, _ := range tmap.Columns {\n\t\tcolumns = append(columns, tmap.Columns[index].ColumnName)\n\t}\n\treturn columns\n}", "func (d Dataset) GetColumns(a *config.AppContext) ([]models.Node, error) {\n\tds := models.Dataset(d)\n\treturn ds.GetColumns(a.Db)\n}", "func (r *result) Columns() []string {\n\treturn r.columns\n}", "func (qr *QueryResponse) Columns() []ColumnItem {\n\treturn qr.ColumnList\n}", "func (*__tbl_iba_servers) GetColumns() []string {\n\treturn []string{\"id\", \"name\", \"zex\", \"stort\", \"comment\"}\n}", "func (*__tbl_nodes) GetColumns() []string {\n\treturn []string{\"id\", \"parent_id\", \"description\", \"comment\", \"meta\", \"full_name\", \"directory_id\", \"signal_id\", \"created_at\", \"updated_at\", \"acl\"}\n}", "func (dao *SysConfigDao) Columns() SysConfigColumns {\n\treturn dao.columns\n}", "func (s *DbRecorder) Columns(includeKeys bool) []string {\n\treturn s.colList(includeKeys, false)\n}", "func (o *InlineResponse20075Stats) GetColumns() InlineResponse20075StatsColumns {\n\tif o == nil || o.Columns == nil {\n\t\tvar ret InlineResponse20075StatsColumns\n\t\treturn ret\n\t}\n\treturn *o.Columns\n}", "func (dao *PagesDao) Columns() PagesColumns {\n\treturn dao.columns\n}", "func (d *badUserDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (q Query) Columns() []string {\n\treturn q.columns\n}", "func (ts *STableSpec) Columns() []IColumnSpec {\n\tif ts._columns == nil {\n\t\tval := reflect.Indirect(reflect.New(ts.structType))\n\t\tts.struct2TableSpec(val)\n\t}\n\treturn ts._columns\n}", "func (r *filter) Columns() []string {\n\treturn r.input.Columns()\n}", "func (m *matrix) GetColumns() int {\n\treturn m.cols\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (r *Reader) Columns() []Column {\n\treturn r.cols\n}", "func (b *Blueprint) GetAddedColumns() []*ColumnDefinition {\n\treturn b.columns\n}", "func (t Table) Columns() []*Column {\n\treturn t.columns\n}", "func (db *DB) Columns(table string) ([]string, error) {\n\tif err := db.db.RLock(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.db.RUnlock()\n\n\ts, err := db.db.Schema(table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cols []string\n\tfor _, c := range s.Columns {\n\t\tcols = append(cols, c.Column)\n\t}\n\treturn cols, nil\n}", "func (ref *UIElement) Columns() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ColumnsAttribute)\n}", "func Columns() *ColumnsType {\n\ttable := qbColumnsTable\n\treturn &ColumnsType{\n\t\tqbColumnsFColumnName.Copy(&table),\n\t\tqbColumnsFTableSchema.Copy(&table),\n\t\tqbColumnsFTableName.Copy(&table),\n\t\tqbColumnsFCharacterMaximumLength.Copy(&table),\n\t\t&table,\n\t}\n}", "func (cq *CypherQuery) Columns() []string {\n\treturn cq.cr.Columns\n}", "func (fw *FileWriter) Columns() []*Column {\n\treturn fw.schemaWriter.Columns()\n}", "func (r *rows) Columns() (c []string) {\n\tif trace {\n\t\tdefer func() {\n\t\t\ttracer(r, \"Columns(): %v\", c)\n\t\t}()\n\t}\n\treturn r.columns\n}", "func (c *Conn) GetColumns(schemaName, tableName string) ([]db.Column, error) {\n\tif schemaCache == nil {\n\t\tschemaCache = make(map[string][]db.Column)\n\t}\n\tif _, ok := schemaCache[schemaName+\".\"+tableName]; ok {\n\t\tfor i := range schemaCache[schemaName+\".\"+tableName] {\n\t\t\tschemaCache[schemaName+\".\"+tableName][i].Value = nil\n\t\t}\n\t\treturn schemaCache[schemaName+\".\"+tableName], nil\n\t}\n\tcols := []db.Column{}\n\tvar col db.Column\n\tvar field, tp, null, key, def, extra interface{}\n\tquery := \"show columns from \" + schemaName + \".\" + tableName\n\trows, err := c.conn.Query(query)\n\tif err != nil {\n\t\treturn cols, err\n\t}\n\tdefer rows.Close()\n\tif err == nil && rows != nil {\n\t\tfor rows.Next() {\n\t\t\trows.Scan(&field, &tp, &null, &key, &def, &extra)\n\t\t\tcol = db.Column{\n\t\t\t\tName: db.Interface2string(field, false),\n\t\t\t\tDefaultValue: db.Interface2string(def, false),\n\t\t\t}\n\t\t\tif db.Interface2string(key, false) == \"PRI\" {\n\t\t\t\tcol.PrimaryKey = true\n\t\t\t} else {\n\t\t\t\tcol.PrimaryKey = false\n\t\t\t}\n\t\t\tif db.Interface2string(null, false) == \"YES\" {\n\t\t\t\tcol.Nullable = true\n\t\t\t} else {\n\t\t\t\tcol.Nullable = false\n\t\t\t}\n\t\t\tif db.Interface2string(extra, false) == \"auto_increment\" {\n\t\t\t\tcol.AutoIncrement = true\n\t\t\t} else {\n\t\t\t\tcol.AutoIncrement = false\n\t\t\t}\n\t\t\tcol.Type, col.Length = mapDataType(db.Interface2string(tp, false))\n\t\t\tcols = append(cols, col)\n\t\t}\n\t}\n\n\tschemaCache[schemaName+\".\"+tableName] = cols\n\treturn cols, nil\n}", "func (dao *ConfigAuditProcessDao) Columns() ConfigAuditProcessColumns {\n\treturn dao.columns\n}", "func (r *Iter_UServ_UpdateNameToFoo) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (o ServiceBusQueueOutputDataSourceResponseOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusQueueOutputDataSourceResponse) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func (k *CustomResourceKind) Columns() []*printer.TableColumn {\n\tif k.Spec == nil {\n\t\treturn nil\n\t}\n\n\treturn []*printer.TableColumn{\n\t\t{\n\t\t\tName: \"JSONSchema\",\n\t\t\tValue: k.Spec.JSONSchema,\n\t\t},\n\t}\n}", "func (i *PermissionIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (s *DbRecorder) colList(withKeys bool, omitNil bool) []string {\n\tnames := make([]string, 0, len(s.fields))\n\n\tvar ar reflect.Value\n\tif omitNil {\n\t\tar = reflect.Indirect(reflect.ValueOf(s.record))\n\t}\n\n\tfor _, field := range s.fields {\n\t\tif !withKeys && field.isKey {\n\t\t\tcontinue\n\t\t}\n\t\tif omitNil {\n\t\t\tf := ar.FieldByName(field.name)\n\t\t\tif f.Kind() == reflect.Ptr && f.IsNil() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tnames = append(names, field.column)\n\t}\n\n\treturn names\n}", "func (c *GithubClient) columns(projectId int64) ([]Column, error) {\n\tu := fmt.Sprintf(\"/projects/%v/columns\", projectId)\n\treq, err := c.client.NewRequest(\"GET\", u, nil)\n\treq.Header.Set(\"Accept\", mediaTypeProjectsPreview)\n\tvar columns []Column\n\t_, err = c.client.Do(c.ctx, req, &columns)\n\treturn columns, err\n}", "func (c *cassandraConnector) Get(\n\tctx context.Context,\n\te *base.Definition,\n\tkeyCols []base.Column,\n\tcolNamesToRead ...string,\n) ([]base.Column, error) {\n\tif len(colNamesToRead) == 0 {\n\t\tcolNamesToRead = e.GetColumnsToRead()\n\t}\n\n\tq, err := c.buildSelectQuery(ctx, e, keyCols, colNamesToRead)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// build a result row\n\tresult := buildResultRow(e, colNamesToRead)\n\n\tif err := q.Scan(result...); err != nil {\n\t\tif err == gocql.ErrNotFound {\n\t\t\terr = yarpcerrors.NotFoundErrorf(err.Error())\n\t\t}\n\t\tsendCounters(c.executeFailScope, e.Name, get, err)\n\t\treturn nil, err\n\t}\n\n\tsendLatency(c.scope, e.Name, get, time.Duration(q.Latency()))\n\tsendCounters(c.executeSuccessScope, e.Name, get, nil)\n\n\t// translate the read result into a row ([]base.Column)\n\treturn getRowFromResult(e, colNamesToRead, result), nil\n}", "func (o ServiceBusQueueOutputDataSourceOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusQueueOutputDataSource) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func (o CassandraSchemaOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchema) []Column { return v.Columns }).(ColumnArrayOutput)\n}", "func (r *Iter_UServ_GetAllUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (c *client) GetProjectColumns(org string, projectID int) ([]ProjectColumn, error) {\n\tdurationLogger := c.log(\"GetProjectColumns\", projectID)\n\tdefer durationLogger()\n\n\tpath := fmt.Sprintf(\"/projects/%d/columns\", projectID)\n\tvar projectColumns []ProjectColumn\n\terr := c.readPaginatedResults(\n\t\tpath,\n\t\t\"application/vnd.github.inertia-preview+json\",\n\t\torg,\n\t\tfunc() interface{} {\n\t\t\treturn &[]ProjectColumn{}\n\t\t},\n\t\tfunc(obj interface{}) {\n\t\t\tprojectColumns = append(projectColumns, *(obj.(*[]ProjectColumn))...)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn projectColumns, nil\n}", "func (i *GroupIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (m *MacroEvaluator) GetFields() []Field {\n\tfields := make([]Field, len(m.FieldValues))\n\ti := 0\n\tfor key := range m.FieldValues {\n\t\tfields[i] = key\n\t\ti++\n\t}\n\treturn fields\n}", "func (i *UserIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *Iter_UServ_CreateUsersTable) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (r *Iter_UServ_Drop) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (vt *perfSchemaTable) Cols() []*table.Column {\n\treturn vt.cols\n}", "func (r *rows) Columns() []string {\n\treturn r.parent.columns\n}", "func getAllSchemaColumns(t *testing.T) *schema.ColCollection {\n\tcolColl, err := schema.NewColCollection(\n\t\tschema.NewColumn(\"id\", 0, types.IntKind, true),\n\t\tschema.NewColumn(\"first\", 1, types.StringKind, false),\n\t\tschema.NewColumn(\"last\", 2, types.StringKind, false),\n\t\tschema.NewColumn(\"is_married\", 3, types.BoolKind, false),\n\t\tschema.NewColumn(\"age\", 4, types.IntKind, false),\n\t\tschema.NewColumn(\"rating\", 5, types.FloatKind, false),\n\t\tschema.NewColumn(\"uuid\", 6, types.UUIDKind, false),\n\t\tschema.NewColumn(\"num_episodes\", 7, types.UintKind, false),\n\t\tschema.NewColumn(\"id\", 8, types.IntKind, true),\n\t\tschema.NewColumn(\"name\", 9, types.StringKind, false),\n\t\tschema.NewColumn(\"air_date\", 10, types.IntKind, false),\n\t\tschema.NewColumn(\"rating\", 11, types.FloatKind, false),\n\t\tschema.NewColumn(\"character_id\", 12, types.IntKind, true),\n\t\tschema.NewColumn(\"episode_id\", 13, types.IntKind, true),\n\t\tschema.NewColumn(\"comments\", 14, types.StringKind, false),\n\t)\n\n\trequire.NoError(t, err)\n\treturn colColl\n}", "func (m *List) SetColumns(value []ColumnDefinitionable)() {\n m.columns = value\n}", "func (i *UserGroupsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *Iter_UServ_GetFriends) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (o DataSetGeoSpatialColumnGroupPtrOutput) Columns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *DataSetGeoSpatialColumnGroup) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(pulumi.StringArrayOutput)\n}", "func (s *DbRecorder) colValLists(withKeys, withAutos bool) (columns []string, values []interface{}) {\n\tar := reflect.Indirect(reflect.ValueOf(s.record))\n\n\tfor _, field := range s.fields {\n\n\t\tswitch {\n\t\tcase !withKeys && field.isKey:\n\t\t\tcontinue\n\t\tcase !withAutos && field.isAuto:\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the value of the field we are going to store.\n\t\tf := ar.FieldByName(field.name)\n\t\tvar v reflect.Value\n\t\tif f.Kind() == reflect.Ptr {\n\t\t\tif f.IsNil() {\n\t\t\t\t// nothing to store\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// no indirection: the field is already a reference to its value\n\t\t\tv = f\n\t\t} else {\n\t\t\t// get the value pointed to by the field\n\t\t\tv = reflect.Indirect(f)\n\t\t}\n\n\t\tvalues = append(values, v.Interface())\n\t\tcolumns = append(columns, field.column)\n\t}\n\n\treturn\n}", "func (o DataSetGeoSpatialColumnGroupOutput) Columns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v DataSetGeoSpatialColumnGroup) []string { return v.Columns }).(pulumi.StringArrayOutput)\n}", "func (t *NodesTable) Columns() []table.ColumnDefinition {\n\treturn t.columns\n}", "func (i *UserPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *boltRows) Columns() []string {\n\tfieldsInt, ok := r.metadata[\"fields\"]\n\tif !ok {\n\t\treturn []string{}\n\t}\n\n\tfields, ok := fieldsInt.([]interface{})\n\tif !ok {\n\t\tlog.Errorf(\"Unrecognized fields from success message: %#v\", fieldsInt)\n\t\treturn []string{}\n\t}\n\n\tfieldsStr := make([]string, len(fields))\n\tfor i, f := range fields {\n\t\tif fieldsStr[i], ok = f.(string); !ok {\n\t\t\tlog.Errorf(\"Unrecognized fields from success message: %#v\", fieldsInt)\n\t\t\treturn []string{}\n\t\t}\n\t}\n\treturn fieldsStr\n}", "func (i *GroupPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (ei *Engine) getColumns(e mysql.BinlogEvent) (msgs []*pbmysql.Event, err error) {\n\ttID := e.TableID(ei.getFormat())\n\n\tif ei.tm[tID] == nil {\n\t\treturn\n\t}\n\tvar rows mysql.Rows\n\tif rows, err = e.Rows(ei.getFormat(), ei.tm[tID]); err != nil {\n\t\treturn\n\t}\n\n\tif e.IsWriteRows() {\n\t\tmsgs, err = ei.getInsertColumns(e, rows, tID)\n\t} else if e.IsUpdateRows() {\n\t\tmsgs, err = ei.getUpdateColumns(e, rows, tID)\n\t} else if e.IsDeleteRows() {\n\t\tmsgs, err = ei.getDeleteColumns(e, rows, tID)\n\t} else {\n\t\terr = fmt.Errorf(\"unsupport type\")\n\t}\n\tfor _, msg := range msgs {\n\t\tmsg.NanoTimestamp = time.Now().UnixNano()\n\t\tmsg.Schema = ei.tm[tID].Database\n\t\tmsg.Table = ei.tm[tID].Name\n\t}\n\n\treturn\n}", "func (m *Macro) GetFields() []Field {\n\tfields := m.evaluator.GetFields()\n\n\tfor _, macro := range m.Opts.MacroStore.List() {\n\t\tfields = append(fields, macro.evaluator.GetFields()...)\n\t}\n\n\treturn fields\n}", "func (o CassandraSchemaPtrOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v *CassandraSchema) []Column {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(ColumnArrayOutput)\n}", "func (r *Iter_UServ_SelectUserById) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (r *Iter_UServ_InsertUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (c MethodsCollection) FieldsGet() pFieldsGet {\n\treturn pFieldsGet{\n\t\tMethod: c.MustGet(\"FieldsGet\"),\n\t}\n}", "func (o ServiceBusTopicOutputDataSourceResponseOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusTopicOutputDataSourceResponse) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func (rows *Rows) Columns() []string {\n\tcolInfo := rows.resultSet.ResultSetMetadata.ColumnInfo\n\tcolumns := make([]string, len(colInfo))\n\tfor i, col := range colInfo {\n\t\tcolumns[i] = *col.Name\n\t}\n\treturn columns\n}", "func (r *QueryResult) Columns() []string {\n\tnames := make([]string, r.metadata.ColumnCount())\n\tcols := r.metadata.Columns()\n\tfor i := 0; i < len(names); i++ {\n\t\tnames[i] = cols[i].Name()\n\t}\n\treturn names\n}", "func (s *Simplex) getColumn(pivotColumn int) []float64 {\n\tvar columnValues []float64\n\tfor i := 0; i < s.RowsSize; i++ {\n\t\tcolumnValues = append(columnValues, s.Tableau[i][pivotColumn])\n\t}\n\treturn columnValues\n}", "func(h ColumnHandler)Columns(initialColumn string, howManyColumns uint) []string {\n\tvar (\n\t\ta []string\n\t\tc= initialColumn\n\t)\n\n\ta = append(a, c)\n\n\tfor i := uint(0); i < howManyColumns-1; i++ {\n\t\tc = h.NextColumn(c, 0)\n\n\t\tif c!=\"\" {\n\t\t\ta = append(a, c)\n\t\t}\n\t}\n\n\treturn a\n}", "func (o ServiceBusTopicOutputDataSourceOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusTopicOutputDataSource) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func BenchmarkGetColumns(b *testing.B) {\n\tdbc := csdb.MustConnectTest()\n\tdefer dbc.Close()\n\tsess := dbc.NewSession()\n\tvar err error\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tbenchmarkGetColumns, err = csdb.GetColumns(sess, \"eav_attribute\")\n\t\tif err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t}\n\thashHave, err := benchmarkGetColumns.Hash()\n\tif err != nil {\n\t\tb.Error(err)\n\t}\n\tif 0 != bytes.Compare(hashHave, benchmarkGetColumnsHashWant) {\n\t\tb.Errorf(\"\\nHave %#v\\nWant %#v\\n\", hashHave, benchmarkGetColumnsHashWant)\n\t}\n\t//\tb.Log(benchmarkGetColumns.GoString())\n}", "func (t *BoundedTable) Cols() []*table.Column {\n\treturn t.Columns\n}", "func (v *templateTableType) Columns() []string {\n\treturn []string{\n\t\t\"id\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"type\",\n\t\t\"note\",\n\t\t\"coach_id\",\n\t\t\"place_id\",\n\t\t\"weekday\",\n\t\t\"start_time\",\n\t\t\"duration\",\n\t\t\"created_at\",\n\t\t\"updated_at\",\n\t}\n}", "func (p *HbaseClient) GetColumnDescriptors(tableName Text) (r map[string]*ColumnDescriptor, err error) {\n\tif err = p.sendGetColumnDescriptors(tableName); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetColumnDescriptors()\n}", "func (r RowData) Columns() []string {\n\ttmp := []string{}\n\tfor colName := range r {\n\t\ttmp = append(tmp, colName)\n\t}\n\n\treturn tmp\n}", "func (v *IconView) GetColumns() int {\n\treturn int(C.gtk_icon_view_get_columns(v.native()))\n}", "func (d *Dense) Columns() int {\n\treturn d.columns\n}", "func (a *Client) EmployeesByIDColumnsGet(params *EmployeesByIDColumnsGetParams, authInfo runtime.ClientAuthInfoWriter) (*EmployeesByIDColumnsGetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewEmployeesByIDColumnsGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"EmployeesByIdColumnsGet\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/employees/{id}/columns\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &EmployeesByIDColumnsGetReader{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.(*EmployeesByIDColumnsGetOK), nil\n\n}", "func (v *permutationTableType) Columns() []string {\n\treturn []string{\"uuid\", \"data\"}\n}", "func (fn *formulaFuncs) COLUMNS(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"COLUMNS requires 1 argument\")\n\t}\n\tmin, max := calcColumnsMinMax(argsList)\n\tif max == MaxColumns {\n\t\treturn newNumberFormulaArg(float64(MaxColumns))\n\t}\n\tresult := max - min + 1\n\tif max == min {\n\t\tif min == 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"invalid reference\")\n\t\t}\n\t\treturn newNumberFormulaArg(float64(1))\n\t}\n\treturn newNumberFormulaArg(float64(result))\n}", "func (o CassandraSchemaResponseOutput) Columns() ColumnResponseArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchemaResponse) []ColumnResponse { return v.Columns }).(ColumnResponseArrayOutput)\n}", "func (view *CrosstabView) Columns() ([]string, error) {\n\tif view.err != nil {\n\t\treturn nil, view.err\n\t}\n\tcols := make([]string, len(view.hkeys)+1)\n\tcols[0] = view.v\n\tfor i := 0; i < len(view.hkeys); i++ {\n\t\tcols[i+1] = view.hkeys[i].v\n\t}\n\treturn cols, nil\n}", "func (t *tableCommon) Cols() []*table.Column {\n\ttrace_util_0.Count(_tables_00000, 45)\n\tif len(t.publicColumns) > 0 {\n\t\ttrace_util_0.Count(_tables_00000, 48)\n\t\treturn t.publicColumns\n\t}\n\ttrace_util_0.Count(_tables_00000, 46)\n\tpublicColumns := make([]*table.Column, len(t.Columns))\n\tmaxOffset := -1\n\tfor _, col := range t.Columns {\n\t\ttrace_util_0.Count(_tables_00000, 49)\n\t\tif col.State != model.StatePublic {\n\t\t\ttrace_util_0.Count(_tables_00000, 51)\n\t\t\tcontinue\n\t\t}\n\t\ttrace_util_0.Count(_tables_00000, 50)\n\t\tpublicColumns[col.Offset] = col\n\t\tif maxOffset < col.Offset {\n\t\t\ttrace_util_0.Count(_tables_00000, 52)\n\t\t\tmaxOffset = col.Offset\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 47)\n\treturn publicColumns[0 : maxOffset+1]\n}", "func (sheet *SheetData) GetColumn(col int) []interface{} {\n\t//We need to transpose the data\n\tcolData := make([]interface{}, 0)\n\n\t//March over each row\n\tfor r := range sheet.Values {\n\t\t//If it has the column add it\n\t\tif len(sheet.Values[r]) > col+1 {\n\t\t\tcolData = append(colData, sheet.Values[r][col])\n\t\t}\n\n\t}\n\n\treturn colData\n}", "func (v Chunk) Cols() []flux.ColMeta {\n\treturn v.buf.Columns\n}", "func (m *ItemItemsItemWorkbookTablesWorkbookTableItemRequestBuilder) Columns()(*ItemItemsItemWorkbookTablesItemColumnsRequestBuilder) {\n return NewItemItemsItemWorkbookTablesItemColumnsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (v *nicerButSlowerFilmListViewType) Columns() []string {\n\treturn []string{\n\t\t\"FID\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"category\",\n\t\t\"price\",\n\t\t\"length\",\n\t\t\"rating\",\n\t\t\"actors\",\n\t}\n}" ]
[ "0.6995068", "0.6583713", "0.65590763", "0.6495269", "0.64883107", "0.63101625", "0.6274126", "0.6241689", "0.6212528", "0.6161865", "0.605871", "0.60496694", "0.6028404", "0.6013853", "0.599702", "0.5981092", "0.5973022", "0.5952178", "0.59382784", "0.5925666", "0.58940035", "0.5876905", "0.5861102", "0.58309436", "0.58063185", "0.579757", "0.57902", "0.5779666", "0.5779666", "0.5775891", "0.5775891", "0.57582045", "0.57420623", "0.5713454", "0.5708836", "0.5707396", "0.5706023", "0.5688588", "0.5687705", "0.56782436", "0.5572095", "0.5556475", "0.55517423", "0.5550844", "0.5507536", "0.54948115", "0.54923207", "0.5486347", "0.54764575", "0.5473337", "0.54645526", "0.54634976", "0.5462874", "0.54387087", "0.54302114", "0.54188484", "0.5417897", "0.541193", "0.5411222", "0.5403322", "0.5400279", "0.5393521", "0.5384458", "0.53830826", "0.53649503", "0.5359747", "0.5353298", "0.5323515", "0.53227854", "0.53173023", "0.53159213", "0.53100526", "0.5308569", "0.5306849", "0.5302087", "0.5286391", "0.52672833", "0.5250041", "0.5214074", "0.52134746", "0.5207467", "0.51946646", "0.5186772", "0.5184677", "0.51822585", "0.51739913", "0.51714134", "0.51712656", "0.516204", "0.5159912", "0.5153459", "0.5142394", "0.51365924", "0.5117269", "0.51093125", "0.51082766", "0.5101523", "0.5083754", "0.5083262", "0.50775415" ]
0.76532036
0
GetContentTypes gets the contentTypes property value. The collection of content types present in this list.
GetContentTypes получает значение свойства contentTypes. Коллекция типов содержимого, присутствующих в этом списке.
func (m *List) GetContentTypes()([]ContentTypeable) { return m.contentTypes }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *LastMileAccelerationOptions) GetContentTypes() []string {\n\tif o == nil || o.ContentTypes == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.ContentTypes\n}", "func (m *List) SetContentTypes(value []ContentTypeable)() {\n m.contentTypes = value\n}", "func (set *ContentTypeSet) Types() (types []ContentType) {\n\tif set == nil || len(set.set) == 0 {\n\t\treturn []ContentType{}\n\t}\n\treturn append(make([]ContentType, 0, len(set.set)), set.set...)\n}", "func (o *LastMileAccelerationOptions) SetContentTypes(v []string) {\n\to.ContentTypes = &v\n}", "func (ht HTMLContentTypeBinder) ContentTypes() []string {\n\treturn []string{\n\t\t\"application/html\",\n\t\t\"text/html\",\n\t\t\"application/x-www-form-urlencoded\",\n\t\t\"html\",\n\t}\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (ycp *YamlContentParser) ContentTypes() []string {\n\treturn []string{\"text/x-yaml\", \"application/yaml\", \"text/yaml\", \"application/x-yaml\"}\n}", "func (m *SiteItemRequestBuilder) ContentTypes()(*ItemContentTypesRequestBuilder) {\n return NewItemContentTypesRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypes(contentTypes *string) {\n\to.ContentTypes = contentTypes\n}", "func ContentTypes(types []string, blacklist bool) Option {\n\treturn func(c *config) error {\n\t\tc.contentTypes = []parsedContentType{}\n\t\tfor _, v := range types {\n\t\t\tmediaType, params, err := mime.ParseMediaType(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.contentTypes = append(c.contentTypes, parsedContentType{mediaType, params})\n\t\t}\n\t\tc.blacklist = blacklist\n\t\treturn nil\n\t}\n}", "func (m *ItemSitesSiteItemRequestBuilder) ContentTypes()(*ItemSitesItemContentTypesRequestBuilder) {\n return NewItemSitesItemContentTypesRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func ContentTypes(contentTypes ...string) Option {\n\treturn ArrayOpt(\"content_types\", contentTypes...)\n}", "func (_AccessIndexor *AccessIndexorCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_Container *ContainerCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Container.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_BaseLibrary *BaseLibraryCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (m *Gzip) GetContentType() []string {\n\tif m != nil {\n\t\treturn m.ContentType\n\t}\n\treturn nil\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIe(contentTypesIe *string) {\n\to.ContentTypesIe = contentTypesIe\n}", "func SetOfContentTypes(types ...ContentType) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == t {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, t)\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (sf SearchFilter) GetTypes() []string {\n\tret := funk.Keys(sf.Types).([]string)\n\tsort.Strings(ret)\n\treturn ret\n}", "func (o *LastMileAccelerationOptions) HasContentTypes() bool {\n\tif o != nil && o.ContentTypes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *ChannelSpecification) SetSupportedContentTypes(v []*string) *ChannelSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (s *InferenceSpecification) SetSupportedContentTypes(v []*string) *InferenceSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (o *GetMessagesAllOf) GetContentType() interface{} {\n\tif o == nil {\n\t\tvar ret interface{}\n\t\treturn ret\n\t}\n\treturn o.ContentType\n}", "func (a *Client) GetSchemaTypes(params *GetSchemaTypesParams) (*GetSchemaTypesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSchemaTypesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSchemaTypes\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/schemas/types\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSchemaTypesReader{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.(*GetSchemaTypesOK), nil\n\n}", "func (o *SchemaDefinitionRestDto) GetTypes() map[string]SchemaType {\n\tif o == nil || o.Types == nil {\n\t\tvar ret map[string]SchemaType\n\t\treturn ret\n\t}\n\treturn *o.Types\n}", "func (s *ServerConnection) ContentFilterGetContentApplicationList() (ContentApplicationList, error) {\n\tdata, err := s.CallRaw(\"ContentFilter.getContentApplicationList\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcategories := struct {\n\t\tResult struct {\n\t\t\tCategories ContentApplicationList `json:\"categories\"`\n\t\t} `json:\"result\"`\n\t}{}\n\terr = json.Unmarshal(data, &categories)\n\treturn categories.Result.Categories, err\n}", "func (s *RecommendationJobPayloadConfig) SetSupportedContentTypes(v []*string) *RecommendationJobPayloadConfig {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (o *PluginConfigInterface) GetTypes() []PluginInterfaceType {\n\tif o == nil {\n\t\tvar ret []PluginInterfaceType\n\t\treturn ret\n\t}\n\n\treturn o.Types\n}", "func (s *AdditionalInferenceSpecificationDefinition) SetSupportedContentTypes(v []*string) *AdditionalInferenceSpecificationDefinition {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (o GetInstanceTypesResultOutput) Types() GetInstanceTypesTypeArrayOutput {\n\treturn o.ApplyT(func(v GetInstanceTypesResult) []GetInstanceTypesType { return v.Types }).(GetInstanceTypesTypeArrayOutput)\n}", "func ListTypes(c echo.Context) error {\n\tlogger.Info.Info(\"Preparing to list types\")\n\tresult := new(struct {\n\t\tData interface{} `json:\"data\"`\n\t\tTotal int `json:\"total\"`\n\t})\n\ttypes, total, err := controller.ListTypes()\n\tif err != nil {\n\t\tlogger.Error.Error(\"Error while list of types\", err)\n\t\treturn echo.NewHTTPError(http.StatusNotAcceptable, \"Error while list of types\")\n\t}\n\tresult.Data = types\n\tresult.Total = total\n\tlogger.Success.Info(\"Types listed successfully\")\n\treturn c.JSON(http.StatusOK, result)\n}", "func (o *LastMileAccelerationOptions) GetContentTypesOk() (*[]string, bool) {\n\tif o == nil || o.ContentTypes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ContentTypes, true\n}", "func NewContentTypeSet(types ...string) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\tmediaType, _, err := mime.ParseMediaType(t)\n\t\tif err != nil {\n\t\t\t// skip types that can not be parsed\n\t\t\tcontinue\n\t\t}\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == ContentType(mediaType) {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, ContentType(mediaType))\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (o GetDomainNameEndpointConfigurationOutput) Types() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetDomainNameEndpointConfiguration) []string { return v.Types }).(pulumi.StringArrayOutput)\n}", "func (o *MicrosoftGraphListItem) GetContentType() AnyOfmicrosoftGraphContentTypeInfo {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret AnyOfmicrosoftGraphContentTypeInfo\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (s *CaptureContentTypeHeader) SetCsvContentTypes(v []*string) *CaptureContentTypeHeader {\n\ts.CsvContentTypes = v\n\treturn s\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) GetContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"getContentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (aft AllowedFileTypes) Contents() []string {\n\treturn aft\n}", "func (a *Client) GetSchemaTypes(params *GetSchemaTypesParams) (*GetSchemaTypesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSchemaTypesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSchemaTypes\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/schemas/types\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSchemaTypesReader{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\tsuccess, ok := result.(*GetSchemaTypesOK)\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 getSchemaTypes: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func UtteranceContentType_Values() []string {\n\treturn []string{\n\t\tUtteranceContentTypePlainText,\n\t\tUtteranceContentTypeCustomPayload,\n\t\tUtteranceContentTypeSsml,\n\t\tUtteranceContentTypeImageResponseCard,\n\t}\n}", "func getContentInfoList() ([]content.Info, error) {\n\tinfos := make([]content.Info, 0)\n\twalkFn := func(info content.Info) error {\n\t\tinfos = append(infos, info)\n\t\treturn nil\n\t}\n\tif err := contentStore.Walk(ctrdCtx, walkFn); err != nil {\n\t\treturn nil, fmt.Errorf(\"getContentInfoList: Exception while getting content list. %s\", err.Error())\n\t}\n\treturn infos, nil\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIc(contentTypesIc *string) {\n\to.ContentTypesIc = contentTypesIc\n}", "func PossibleContentTypes(firstByte byte) (ct ContentTypeOptions) {\n\tif firstByte == 0 {\n\t\treturn 0\n\t}\n\n\tswitch {\n\tcase firstByte < '\\t' /* 9 */ :\n\t\t// not a text\n\t\tif firstByte&^maskWireType == 0 {\n\t\t\treturn 0\n\t\t}\n\tcase firstByte >= legalUtf8:\n\t\tct |= ContentOptionText\n\tcase firstByte < illegalUtf8FirstByte:\n\t\tct |= ContentOptionText\n\t}\n\n\tswitch WireType(firstByte & maskWireType) {\n\tcase WireVarint:\n\t\tif ct&ContentOptionText == 0 && firstByte >= illegalUtf8FirstByte {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t\tct |= ContentOptionMessage\n\tcase WireFixed64, WireBytes, WireFixed32, WireStartGroup:\n\t\tct |= ContentOptionMessage\n\tcase WireEndGroup:\n\t\tif ct&ContentOptionText == 0 {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t}\n\treturn ct\n}", "func (*AccountSetContentSettingsRequest) TypeName() string {\n\treturn \"account.setContentSettings\"\n}", "func (o *MicrosoftGraphWorkbookComment) GetContentType() string {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (ContentMuxType) Values() []ContentMuxType {\n\treturn []ContentMuxType{\n\t\t\"ContentOnly\",\n\t}\n}", "func (o *BranchingModelSettings) GetBranchTypes() []BranchingModelSettingsBranchTypes {\n\tif o == nil || o.BranchTypes == nil {\n\t\tvar ret []BranchingModelSettingsBranchTypes\n\t\treturn ret\n\t}\n\treturn *o.BranchTypes\n}", "func GetTypes(c echo.Context) error {\n\tvar types []db.Types\n\n\tif err := config.DB.Find(&types).Error; err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, err.Error())\n\t}\n\treturn c.JSON(http.StatusOK, map[string]interface{}{\n\t\t\"message\": \"Berhasil Menampilkan Semua Tipe Smartphone\",\n\t\t\"types\": types,\n\t})\n}", "func HubContentType_Values() []string {\n\treturn []string{\n\t\tHubContentTypeModel,\n\t\tHubContentTypeNotebook,\n\t}\n}", "func (o *InlineResponse20049Post) GetContentType() string {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (o *InlineResponse200115) GetContentType() string {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) GetContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"getContentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetTypes(path string, excludeFilesRegexp *regexp.Regexp, excludeTypesRegexp *regexp.Regexp) (types []*TypeInfo, err error) {\n\tfiles, err := FindFiles(path, excludeFilesRegexp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !strings.HasSuffix(path, \"/\") {\n\t\tpath += \"/\"\n\t}\n\n\tfor _, file := range files {\n\t\tfileData, err := parser.ParseFile(token.NewFileSet(), path+file.Name(), nil, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfileTypes, err := GetTypesFromFile(fileData, excludeTypesRegexp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttypes = append(types, fileTypes...)\n\t}\n\n\treturn types, nil\n}", "func (d *ceph) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\tvar rsyncFeatures []string\n\n\t// Do not pass compression argument to rsync if the associated\n\t// config key, that is rsync.compression, is set to false.\n\tif shared.IsFalse(d.Config()[\"rsync.compression\"]) {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"bidirectional\"}\n\t} else {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"compress\", \"bidirectional\"}\n\t}\n\n\tif refresh {\n\t\tvar transportType migration.MigrationFSType\n\n\t\tif IsContentBlock(contentType) {\n\t\t\ttransportType = migration.MigrationFSType_BLOCK_AND_RSYNC\n\t\t} else {\n\t\t\ttransportType = migration.MigrationFSType_RSYNC\n\t\t}\n\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: transportType,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\tif contentType == ContentTypeBlock {\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t\t},\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_BLOCK_AND_RSYNC,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\treturn []migration.Type{\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t},\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RSYNC,\n\t\t\tFeatures: rsyncFeatures,\n\t\t},\n\t}\n}", "func (resource *ResourceType) SchemeTypes(name TypeName) []TypeName {\n\treturn []TypeName{\n\t\tname,\n\t\tresource.makeResourceListTypeName(name),\n\t}\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypes(contentTypes *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypes(contentTypes)\n\treturn o\n}", "func (p *Plugin) GetTypes() []types.PluginInterfaceType {\n\tp.mu.RLock()\n\tdefer p.mu.RUnlock()\n\n\treturn p.PluginObj.Config.Interface.Types\n}", "func Parse(data string) (ContentTypeList, error) {\n\ttypes := make(ContentTypeList, 0, 1)\n\n\tfor _, entry := range parseList(data) {\n\t\tt, err := ParseSingle(entry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif t != nil {\n\t\t\ttypes = append(types, t)\n\t\t}\n\t}\n\n\treturn types, nil\n\n}", "func (config *Config) ContentType() ContentType {\n\treturn config.contentType\n}", "func GetTypeFields(typeFileContents []byte) (ContentType, error) {\n\n\tvar contentType ContentType\n\tcontentType.Fields = map[string]string{}\n\n\t// Use empty interface to store JSON field values of unknown primitive type.\n\tvar unknownValues map[string]interface{}\n\t// Put JSON key/values into the map of unknown primitives.\n\terr := json.Unmarshal(typeFileContents, &unknownValues)\n\tif err != nil {\n\t\treturn contentType, fmt.Errorf(\"\\nUnable to read content because: %w\", err)\n\t}\n\tfor field, unknownValue := range unknownValues {\n\t\t// isString will be set to true if the value is a string (vs array, obj, etc).\n\t\t_, isString := unknownValue.(string)\n\t\tif isString {\n\t\t\t// Convert the empty interface into a string that can be stored in ContentType struct.\n\t\t\tcontentType.Fields[field] = fmt.Sprintf(\"%v\", unknownValue)\n\t\t}\n\t}\n\n\treturn contentType, nil\n}", "func (client *Client) ListCatalogItemTypes(req *Request) (*Response, error) {\n\treturn client.Execute(&Request{\n\t\tMethod: \"GET\",\n\t\tPath: ServiceCatalogTypesPath,\n\t\tQueryParams: req.QueryParams,\n\t\tResult: &ListCatalogItemTypesResult{},\n\t})\n}", "func (RestController *RestController) GetDataTypes(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdataTypes := RestController.databaseController.ListDataTypes()\n\tjsonBytes, err := json.Marshal(*dataTypes)\n\tif err == nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tfmt.Fprintf(w, \"%s\", jsonBytes)\n\t} else {\n\t\tmsg := fmt.Sprintf(\"An error occurred during marshaling of list of data types: %s\\n\", err)\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(500)\n\t\tfmt.Fprintf(w, \"%s\", msg)\n\t\tconfiguration.Error.Printf(msg)\n\t}\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIsw(contentTypesIsw *string) {\n\to.ContentTypesIsw = contentTypesIsw\n}", "func (client *ClientImpl) GetProcessWorkItemTypes(ctx context.Context, args GetProcessWorkItemTypesArgs) (*[]ProcessWorkItemType, error) {\n\trouteValues := make(map[string]string)\n\tif args.ProcessId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessId\"}\n\t}\n\trouteValues[\"processId\"] = (*args.ProcessId).String()\n\n\tqueryParams := url.Values{}\n\tif args.Expand != nil {\n\t\tqueryParams.Add(\"$expand\", string(*args.Expand))\n\t}\n\tlocationId, _ := uuid.Parse(\"e2e9d1a6-432d-4062-8870-bfcb8c324ad7\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"6.0-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []ProcessWorkItemType\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (obj *Doc) GetContentLibraries(ctx context.Context) (*ContentLibraryList, error) {\n\tresult := &struct {\n\t\tList *ContentLibraryList `json:\"qList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetContentLibraries\", result)\n\treturn result.List, err\n}", "func (a *Client) GetUniverseTypes(params *GetUniverseTypesParams) (*GetUniverseTypesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseTypesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_types\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/types/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseTypesReader{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.(*GetUniverseTypesOK), nil\n\n}", "func (o *MicrosoftGraphListItem) SetContentType(v AnyOfmicrosoftGraphContentTypeInfo) {\n\to.ContentType = &v\n}", "func (s *Channel) SetContentType(v string) *Channel {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *SoftwarerepositoryCategoryMapper) GetTagTypes() []string {\n\tif o == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.TagTypes\n}", "func (_AccessIndexor *AccessIndexorCaller) GetContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"getContentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (ts *TypeSet) Types() map[string]Type {\n\tts.RLock()\n\tdefer ts.RUnlock()\n\n\tout := map[string]Type{}\n\tfor k, v := range ts.types {\n\t\tout[k] = v\n\t}\n\treturn out\n}", "func (HubContentType) Values() []HubContentType {\n\treturn []HubContentType{\n\t\t\"Model\",\n\t\t\"Notebook\",\n\t}\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNisw(contentTypesNisw *string) {\n\to.ContentTypesNisw = contentTypesNisw\n}", "func (o *MicrosoftGraphWorkbookComment) SetContentType(v string) {\n\to.ContentType = &v\n}", "func GetFieldTypes() []types.FieldTypes {\n\tvar fieldTypeArray []types.FieldTypes\n\tfor key := range types.FieldTypesEnum_value {\n\t\tfieldTypeArray = append(fieldTypeArray, types.FieldTypes{Name: key})\n\t}\n\treturn fieldTypeArray\n}", "func (s *AutoMLChannel) SetContentType(v string) *AutoMLChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func NotificationContentType_Values() []string {\n\treturn []string{\n\t\tNotificationContentTypePlainText,\n\t}\n}", "func (c *CreativesListCall) Types(types ...string) *CreativesListCall {\n\tc.urlParams_.SetMulti(\"types\", append([]string{}, types...))\n\treturn c\n}", "func (json Json) getContentType() (contentType string) {\n\treturn json.contentType\n}", "func GetType() ([]Type, error) {\n\tvar types []Type\n\tstmt, err := mysql.DBConn().Prepare(\"select * from types\")\n\tif err != nil {\n\t\treturn types, utils.ServerError\n\t}\n\n\tdefer stmt.Close()\n\trows, err := stmt.Query()\n\tif err != nil {\n\t\treturn types, utils.ServerError\n\t}\n\n\tfor rows.Next() {\n\t\tt := Type{}\n\t\terr := rows.Scan(&t.ID, &t.Name)\n\t\tif err != nil {\n\t\t\treturn types, utils.ServerError\n\t\t}\n\t\ttypes = append(types, t)\n\t}\n\treturn types, nil\n}", "func (d *cephobject) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\treturn nil\n}", "func (o DomainNameEndpointConfigurationOutput) Types() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DomainNameEndpointConfiguration) string { return v.Types }).(pulumi.StringOutput)\n}", "func (o *BranchingModel) GetBranchTypes() []BranchingModelBranchTypes {\n\tif o == nil || o.BranchTypes == nil {\n\t\tvar ret []BranchingModelBranchTypes\n\t\treturn ret\n\t}\n\treturn *o.BranchTypes\n}", "func (s *Style) Types() []TokenType {\n\tdedupe := map[TokenType]bool{}\n\tfor tt := range s.entries {\n\t\tdedupe[tt] = true\n\t}\n\tif s.parent != nil {\n\t\tfor _, tt := range s.parent.Types() {\n\t\t\tdedupe[tt] = true\n\t\t}\n\t}\n\tout := make([]TokenType, 0, len(dedupe))\n\tfor tt := range dedupe {\n\t\tout = append(out, tt)\n\t}\n\treturn out\n}", "func (s *UtteranceBotResponse) SetContentType(v string) *UtteranceBotResponse {\n\ts.ContentType = &v\n\treturn s\n}", "func (a *API) AssetTypes(ctx context.Context) (*AssetTypesResult, error) {\n\tres := &AssetTypesResult{}\n\t_, err := a.get(ctx, assets, nil, res)\n\n\treturn res, err\n}", "func (s *QueryFilters) SetTypes(v []*string) *QueryFilters {\n\ts.Types = v\n\treturn s\n}", "func (m *SiteItemRequestBuilder) ContentTypesById(id string)(*ItemContentTypesContentTypeItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"contentType%2Did\"] = id\n }\n return NewItemContentTypesContentTypeItemRequestBuilderInternal(urlTplParams, m.requestAdapter)\n}", "func (o *GetContentSourcesUsingGETParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (m *TestMod) AllowedTypes() base.MessageType {\n\treturn m.allowedTypes\n}", "func (m *SchemaExtension) GetTargetTypes()([]string) {\n val, err := m.GetBackingStore().Get(\"targetTypes\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesn(contentTypesn *string) {\n\to.ContentTypesn = contentTypesn\n}", "func (me *TContentType) Walk() (err error) {\n\tif fn := WalkHandlers.TContentType; 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.XsdGoPkgHasElems_TextchoiceContentTypeschema_Text_XsdtString_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_ListchoiceContentTypeschema_List_TxsdContentTypeChoiceList_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_FormattedContentchoiceContentTypeschema_FormattedContent_XsdtString_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_BinarychoiceContentTypeschema_Binary_TBinaryContentType_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_ApplicationchoiceContentTypeschema_Application_TApplicationContentType_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_EmbeddedBinarychoiceContentTypeschema_EmbeddedBinary_TEmbeddedBinaryContentType_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_TitlechoiceContentTypeschema_Title_XsdtString_.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 (s *MetricsSource) SetContentType(v string) *MetricsSource {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *MicrosoftGraphListItem) HasContentType() bool {\n\tif o != nil && o.ContentType != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *AutoMLJobChannel) SetContentType(v string) *AutoMLJobChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func (cr *ContactReceiver) GetContactTypes() error {\n\terr := database.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstmt, err := database.DB.Prepare(getContactTypesByReceiver)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\tvar ct ContactType\n\tres, err := stmt.Query(cr.ID)\n\tfor res.Next() {\n\t\terr = res.Scan(&ct.ID, &ct.Name, &ct.ShowOnWebsite, &ct.BrandID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcr.ContactTypes = append(cr.ContactTypes, ct)\n\t}\n\tdefer res.Close()\n\treturn err\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) ContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"contentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}" ]
[ "0.77380264", "0.7120515", "0.6951072", "0.683847", "0.6325658", "0.63171864", "0.62789446", "0.61402726", "0.6130467", "0.6012503", "0.5989417", "0.5985794", "0.59765583", "0.58592784", "0.56957906", "0.56474996", "0.5573628", "0.5445044", "0.5442282", "0.54262537", "0.54202455", "0.53830886", "0.5322562", "0.52157044", "0.52118427", "0.5201793", "0.5201748", "0.5186983", "0.5169693", "0.51183057", "0.51110417", "0.5100947", "0.507782", "0.5071021", "0.5056867", "0.50218326", "0.49885827", "0.4945979", "0.49403155", "0.49033895", "0.48936868", "0.4885376", "0.48610204", "0.48594972", "0.48497996", "0.48405424", "0.48319465", "0.48103294", "0.48094308", "0.48085505", "0.47819787", "0.47773618", "0.4770419", "0.47585413", "0.4745482", "0.47426748", "0.4738846", "0.47296554", "0.47095704", "0.470481", "0.46928164", "0.46920532", "0.4680611", "0.4664239", "0.46605065", "0.4660471", "0.46474847", "0.46292517", "0.46251974", "0.46190205", "0.46178302", "0.46144947", "0.46049443", "0.46025896", "0.46010235", "0.45990118", "0.45884725", "0.458654", "0.45862278", "0.4571762", "0.45659468", "0.45529622", "0.45528245", "0.4537807", "0.45362216", "0.45354912", "0.45351994", "0.45338088", "0.45318073", "0.45306662", "0.45194697", "0.4517363", "0.4514074", "0.45019433", "0.4499135", "0.4498523", "0.44984573", "0.44949898", "0.44936714", "0.4488536" ]
0.79392874
0
GetDisplayName gets the displayName property value. The displayable title of the list.
GetDisplayName получает значение свойства displayName. Отображаемое название списка.
func (m *List) GetDisplayName()(*string) { return m.displayName }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *DeviceClient) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *RoleWithAccess) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *DeviceAndAppManagementAssignmentFilter) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *MicrosoftGraphAppIdentity) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *SchemaDefinitionRestDto) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *MicrosoftGraphModifiedProperty) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (u *User) GetDisplayName() string {\n\treturn u.DisplayName\n}", "func (o *MicrosoftGraphEducationSchool) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (s UserSet) DisplayName() string {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"DisplayName\", \"display_name\")).(string)\n\treturn res\n}", "func (o *RoleAssignment) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *BrowserSiteList) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *User) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *User) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *Tier) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *User) GetDisplayName()(*string) {\n return m.displayName\n}", "func (u *User) GetDisplayName() string {\n\treturn u.displayName\n}", "func (o *MailFolder) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *MicrosoftGraphMailSearchFolder) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *List) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o *MicrosoftGraphEducationUser) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *MicrosoftGraphSharedPcConfiguration) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *IdentityProviderBase) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o *SubscriptionRegistration) GetDisplayName() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&4 != 0\n\tif ok {\n\t\tvalue = o.displayName\n\t}\n\treturn\n}", "func (m *RPCRegistrationRequest) GetDisplayName() string {\n\tif m != nil && m.DisplayName != nil {\n\t\treturn *m.DisplayName\n\t}\n\treturn \"\"\n}", "func (m *Group) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *RoleDefinition) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *DeviceCategory) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *RelatedContact) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (a *Action) GetDisplayName() string {\n\tif setting.UI.DefaultShowFullName {\n\t\ttrimmedFullName := strings.TrimSpace(a.GetActFullName())\n\t\tif len(trimmedFullName) > 0 {\n\t\t\treturn trimmedFullName\n\t\t}\n\t}\n\treturn a.ShortActUserName()\n}", "func (m *RemoteAssistancePartner) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *WorkforceIntegration) GetDisplayName()(*string) {\n return m.displayName\n}", "func (u *User) GetDisplayName() string {\n\tif u.DisplayName != \"\" {\n\t\treturn u.DisplayName\n\t}\n\treturn u.Username\n}", "func (m *IndustryDataRunActivity) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *EducationAssignment) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *MessageRule) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *TelecomExpenseManagementPartner) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *BookingNamedEntity) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *TeamworkTag) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o ContactListTopicOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ContactListTopic) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *ConditionalAccessPolicy) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (d UserData) DisplayName() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"DisplayName\", \"display_name\"))\n\tif !d.Has(models.NewFieldName(\"DisplayName\", \"display_name\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}", "func (c FieldsCollection) DisplayName() *models.Field {\n\treturn c.MustGet(\"DisplayName\")\n}", "func (a *Action) GetDisplayNameTitle() string {\n\tif setting.UI.DefaultShowFullName {\n\t\treturn a.ShortActUserName()\n\t}\n\treturn a.GetActFullName()\n}", "func (o AllowlistCustomAlertRuleResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AllowlistCustomAlertRuleResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *NamedLocation) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *Setting) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *GroupPolicyDefinition) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *AccessPackage) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *IdentityUserFlowAttributeAssignment) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *AccessPackageCatalog) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *DirectorySetting) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *ManagementTemplateStep) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *DeviceManagementConfigurationSettingDefinition) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *CreatePostRequestBody) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *TemplateParameter) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *ProfileCardAnnotation) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *CloudPcAuditEvent) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *PrintConnector) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *ManagedAppPolicy) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o LookupContactResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupContactResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (u *User) DisplayName() string {\n\tif len(u.FullName) > 0 {\n\t\treturn u.FullName\n\t}\n\treturn u.Name\n}", "func (m *Application) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o DenylistCustomAlertRuleResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DenylistCustomAlertRuleResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o MonitoredResourceDescriptorResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MonitoredResourceDescriptorResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *WorkforceIntegration) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o UserOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *BookingBusiness) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o LookupEntryResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupEntryResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *CloudPcConnection) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *SchemaDefinitionRestDto) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (m *RoleDefinition) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o LogDescriptorResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LogDescriptorResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o LookupIntentResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIntentResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *EducationAssignment) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o LookupOrganizationResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOrganizationResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o *DisplayInfo) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (o SourceOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Source) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o LookupPipelineResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPipelineResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o MonitoredResourceDescriptorOutput) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MonitoredResourceDescriptor) *string { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (o *RoleAssignment) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o UserOutput) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringPtrOutput { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (o DatastoreOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Datastore) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (s *Experiment) SetDisplayName(v string) *Experiment {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o ClientOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Client) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *AdministrativeUnit) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o LookupConnectivityTestResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConnectivityTestResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o ConversationModelOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ConversationModel) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *ProgramControl) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o LakeOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lake) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o ConnectorOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Connector) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o ServicePrincipalOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServicePrincipal) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o LogDescriptorOutput) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LogDescriptor) *string { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (m *PaymentTerm) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o LookupProxyConfigResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupProxyConfigResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o *DeviceClient) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o ScheduledQueryRulesAlertV2Output) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScheduledQueryRulesAlertV2) pulumi.StringPtrOutput { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (m *RemoteAssistancePartner) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (s *Trial) SetDisplayName(v string) *Trial {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o LookupClientConnectorServiceResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupClientConnectorServiceResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}" ]
[ "0.7741837", "0.7733561", "0.74696445", "0.7466271", "0.74494886", "0.7443389", "0.74368083", "0.7429317", "0.7401814", "0.74005044", "0.73881435", "0.73865306", "0.73865306", "0.7367366", "0.7334453", "0.73278743", "0.73046476", "0.72927064", "0.727479", "0.7256103", "0.7253778", "0.72264194", "0.72171676", "0.7202448", "0.7190159", "0.7189942", "0.7188653", "0.71860635", "0.71804476", "0.7167179", "0.71669805", "0.7156371", "0.7152575", "0.70977217", "0.7095738", "0.709168", "0.70711035", "0.70694554", "0.7044781", "0.7041599", "0.7041483", "0.7037661", "0.70190793", "0.70137143", "0.6995211", "0.69807136", "0.69609255", "0.6959646", "0.6948451", "0.69426906", "0.6938619", "0.6928187", "0.69278234", "0.69031054", "0.68859935", "0.68759745", "0.6870766", "0.68683976", "0.68404967", "0.68258405", "0.68212444", "0.68084913", "0.67975485", "0.67929995", "0.6791627", "0.6769298", "0.67669773", "0.6763644", "0.67256206", "0.67189884", "0.66953516", "0.6687927", "0.6662133", "0.6659929", "0.6650593", "0.66394836", "0.66361016", "0.66268826", "0.66252136", "0.66114944", "0.6610825", "0.66049004", "0.6602177", "0.6595578", "0.65955216", "0.65916485", "0.65746367", "0.65688705", "0.6568414", "0.6568287", "0.6567559", "0.6562745", "0.655484", "0.6554218", "0.6550082", "0.6549063", "0.65408725", "0.6538555", "0.65375483", "0.6524655" ]
0.83683056
0
GetDrive gets the drive property value. Only present on document libraries. Allows access to the list as a [drive][] resource with [driveItems][driveItem].
GetDrive получает значение свойства drive. Доступно только для библиотек документов. Позволяет получить доступ к списку как к ресурсу [drive][] с [driveItems][driveItem].
func (m *List) GetDrive()(Driveable) { return m.drive }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *Block) GetDrive(ctx context.Context) (drive dbus.ObjectPath, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"Drive\").Store(&drive)\n\treturn\n}", "func (m *Group) GetDrive()(Driveable) {\n return m.drive\n}", "func (m *User) GetDrive()(Driveable) {\n return m.drive\n}", "func (o *User) GetDrive() Drive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret Drive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (m *Drive) GetDriveType()(*string) {\n return m.driveType\n}", "func GetDrive() (*drive.Service, *oauth2.Token) {\n\ttoken := getToken(GetOAuthConfig())\n\tsrv, err := drive.NewService(context.Background(), option.WithHTTPClient(GetOAuthConfig().Client(context.Background(), token)))\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve Drive client: %v\", err)\n\t}\n\n\treturn srv, token\n}", "func (o *User) GetDrive() AnyOfmicrosoftGraphDrive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret AnyOfmicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (ref FileView) Drive() resource.ID {\n\treturn ref.drive\n}", "func (repo Repository) Drive(driveID resource.ID) drivestream.DriveReference {\n\treturn Drive{\n\t\tdb: repo.db,\n\t\tdrive: driveID,\n\t}\n}", "func (o *MicrosoftGraphItemReference) GetDriveId() string {\n\tif o == nil || o.DriveId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveId\n}", "func (o *MicrosoftGraphItemReference) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (a *HyperflexApiService) GetHyperflexDriveList(ctx context.Context) ApiGetHyperflexDriveListRequest {\n\treturn ApiGetHyperflexDriveListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (m *User) GetDrives()([]Driveable) {\n return m.drives\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (device *DCV2Bricklet) GetDriveMode() (mode DriveMode, err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Get(uint8(FunctionGetDriveMode), buf.Bytes())\n\tif err != nil {\n\t\treturn mode, err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 9 {\n\t\t\treturn mode, fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 9)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn mode, DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tresultBuf := bytes.NewBuffer(resultBytes[8:])\n\t\tbinary.Read(resultBuf, binary.LittleEndian, &mode)\n\n\t}\n\n\treturn mode, nil\n}", "func (m *Group) GetDrives()([]Driveable) {\n return m.drives\n}", "func (o *StorageFlexUtilVirtualDrive) GetVirtualDrive() string {\n\tif o == nil || o.VirtualDrive == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VirtualDrive\n}", "func (o *StorageFlexFlashVirtualDrive) GetDriveScope() string {\n\tif o == nil || o.DriveScope == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveScope\n}", "func (h *stubDriveHandler) GetDrives() []models.Drive {\n\treturn h.drives\n}", "func (m *List) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (d *portworx) GetDriveSet(n *node.Node) (*torpedovolume.DriveSet, error) {\n\tout, err := d.nodeDriver.RunCommandWithNoRetry(*n, fmt.Sprintf(pxctlCloudDriveInspect, d.getPxctlPath(*n), n.VolDriverNodeID), node.ConnectionOpts{\n\t\tTimeout: crashDriverTimeout,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error when inspecting drive sets for node ID [%s] using PXCTL, Err: %v\", n.VolDriverNodeID, err)\n\t}\n\tvar driveSetInspect torpedovolume.DriveSet\n\terr = json.Unmarshal([]byte(out), &driveSetInspect)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal drive set inspect, Err: %v\", err)\n\t}\n\treturn &driveSetInspect, nil\n}", "func (m *Drive) GetList()(Listable) {\n return m.list\n}", "func (o *StoragePhysicalDisk) GetDriveFirmware() string {\n\tif o == nil || o.DriveFirmware == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveFirmware\n}", "func (o *User) GetDrives() []Drive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []Drive\n\t\treturn ret\n\t}\n\treturn o.Drives\n}", "func (o *MicrosoftGraphListItem) GetDriveItem() AnyOfmicrosoftGraphDriveItem {\n\tif o == nil || o.DriveItem == nil {\n\t\tvar ret AnyOfmicrosoftGraphDriveItem\n\t\treturn ret\n\t}\n\treturn *o.DriveItem\n}", "func (o *StoragePhysicalDiskAllOf) GetDriveFirmware() string {\n\tif o == nil || o.DriveFirmware == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveFirmware\n}", "func (o *VirtualizationIweClusterAllOf) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (o *User) GetDrives() []MicrosoftGraphDrive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []MicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drives\n}", "func (o *User) GetDriveOk() (*Drive, bool) {\n\tif o == nil || o.Drive == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Drive, true\n}", "func (o *StorageFlexFlashVirtualDrive) GetVirtualDrive() string {\n\tif o == nil || o.VirtualDrive == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VirtualDrive\n}", "func (o *User) SetDrive(v AnyOfmicrosoftGraphDrive) {\n\to.Drive = &v\n}", "func (m *Group) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (g Graph) GetDrives(w http.ResponseWriter, r *http.Request) {\n\tg.getDrives(w, r, false)\n}", "func (o *Drive) GetSerial(ctx context.Context) (serial string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Serial\").Store(&serial)\n\treturn\n}", "func (g Graph) GetSingleDrive(w http.ResponseWriter, r *http.Request) {\n\tdriveID, _ := url.PathUnescape(chi.URLParam(r, \"driveID\"))\n\tif driveID == \"\" {\n\t\terr := fmt.Errorf(\"no valid space id retrieved\")\n\t\tg.logger.Err(err)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tg.logger.Info().Str(\"driveID\", driveID).Msg(\"Calling GetSingleDrive\")\n\tctx := r.Context()\n\n\tfilters := []*storageprovider.ListStorageSpacesRequest_Filter{listStorageSpacesIDFilter(driveID)}\n\tres, err := g.ListStorageSpacesWithFilters(ctx, filters, true)\n\tswitch {\n\tcase err != nil:\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesTransportErr)\n\t\terrorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\tcase res.Status.Code != cs3rpc.Code_CODE_OK:\n\t\tif res.Status.Code == cs3rpc.Code_CODE_NOT_FOUND {\n\t\t\t// the client is doing a lookup for a specific space, therefore we need to return\n\t\t\t// not found to the caller\n\t\t\tg.logger.Error().Str(\"driveID\", driveID).Msg(fmt.Sprintf(NoSpaceFoundMessage, driveID))\n\t\t\terrorcode.ItemNotFound.Render(w, r, http.StatusNotFound, fmt.Sprintf(NoSpaceFoundMessage, driveID))\n\t\t\treturn\n\t\t}\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesReturnsErr)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, res.Status.Message)\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tspaces, err := g.formatDrives(ctx, wdu, res.StorageSpaces)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error encoding response\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tswitch num := len(spaces); {\n\tcase num == 0:\n\t\tg.logger.Error().Str(\"driveID\", driveID).Msg(\"no space found\")\n\t\terrorcode.ItemNotFound.Render(w, r, http.StatusNotFound, fmt.Sprintf(NoSpaceFoundMessage, driveID))\n\t\treturn\n\tcase num == 1:\n\t\trender.Status(r, http.StatusOK)\n\t\trender.JSON(w, r, spaces[0])\n\tdefault:\n\t\tg.logger.Error().Int(\"number\", num).Msg(\"expected to find a single space but found more\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"expected to find a single space but found more\")\n\t\treturn\n\t}\n}", "func GetDriveState(client *http.Client, token *Token, id int) (*DriveState, error) {\n\tresJson, err := GetRequest(client, token, fmt.Sprintf(DriveStateURL, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar res DriveStateResponse\n\terr = json.Unmarshal(resJson, &res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &(res.Response), nil\n}", "func (m *User) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (o *User) GetDriveOk() (AnyOfmicrosoftGraphDrive, bool) {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret AnyOfmicrosoftGraphDrive\n\t\treturn ret, false\n\t}\n\treturn *o.Drive, true\n}", "func (o *Drive) GetVendor(ctx context.Context) (vendor string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Vendor\").Store(&vendor)\n\treturn\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveStatus() string {\n\tif o == nil || o.DriveStatus == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveStatus\n}", "func (o *Drive) GetMedia(ctx context.Context) (media string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Media\").Store(&media)\n\treturn\n}", "func (o *Drive) GetId(ctx context.Context) (id string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Id\").Store(&id)\n\treturn\n}", "func NewDrive()(*Drive) {\n m := &Drive{\n BaseItem: *NewBaseItem(),\n }\n odataTypeValue := \"#microsoft.graph.drive\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func (a *HyperflexApiService) GetHyperflexDriveByMoid(ctx context.Context, moid string) ApiGetHyperflexDriveByMoidRequest {\n\treturn ApiGetHyperflexDriveByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (o *StorageFlexFlashVirtualDrive) GetDriveStatus() string {\n\tif o == nil || o.DriveStatus == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveStatus\n}", "func (m *Drive) GetRoot()(DriveItemable) {\n return m.root\n}", "func (c *Conn) GetDriveState(id int) (*DriveState, error) {\n\tif c.accessToken == \"\" {\n\t\treturn nil, fmt.Errorf(\"%w\", ErrMissingAccessToken)\n\t}\n\n\ttype response struct {\n\t\tResponse DriveState `json:\"response\"`\n\t}\n\n\tvar respBody response\n\n\terr := c.doRequest(http.MethodGet, fmt.Sprintf(\"/api/1/vehicles/%d/data_request/drive_state\", id), nil, &respBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &respBody.Response, nil\n}", "func (o *Drive) GetCanPowerOff(ctx context.Context) (canPowerOff bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"CanPowerOff\").Store(&canPowerOff)\n\treturn\n}", "func getDriveFile(path string) (*drive.File, error) {\n\tparent, err := getFileById(\"root\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get Drive root directory: %v\", err)\n\t}\n\n\tdirs := strings.Split(path, \"/\")\n\t// Walk through the directories in the path in turn.\n\tfor _, dir := range dirs {\n\t\tif dir == \"\" {\n\t\t\t// The first string in the split is \"\" if the\n\t\t\t// path starts with a '/'.\n\t\t\tcontinue\n\t\t}\n\n\t\tquery := fmt.Sprintf(\"title='%s' and '%s' in parents and trashed=false\",\n\t\t\tdir, parent.Id)\n\t\tfiles := runDriveQuery(query)\n\n\t\tif len(files) == 0 {\n\t\t\treturn nil, fileNotFoundError{\n\t\t\t\tpath: path,\n\t\t\t}\n\t\t} else if len(files) > 1 {\n\t\t\treturn nil, fmt.Errorf(\"%s: multiple files found\", path)\n\t\t} else {\n\t\t\tparent = files[0]\n\t\t}\n\t}\n\treturn parent, nil\n}", "func (m *Drive) GetQuota()(Quotaable) {\n return m.quota\n}", "func (o *User) SetDrive(v Drive) {\n\to.Drive = &v\n}", "func (o *Drive) GetRevision(ctx context.Context) (revision string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Revision\").Store(&revision)\n\treturn\n}", "func (m *SiteItemRequestBuilder) Drive()(*ItemDriveRequestBuilder) {\n return NewItemDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (o *StoragePhysicalDisk) GetDriveState() string {\n\tif o == nil || o.DriveState == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveState\n}", "func (o *Drive) GetConfiguration(ctx context.Context) (configuration map[string]dbus.Variant, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Configuration\").Store(&configuration)\n\treturn\n}", "func (o *Drive) GetModel(ctx context.Context) (model string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Model\").Store(&model)\n\treturn\n}", "func (o *Drive) GetEjectable(ctx context.Context) (ejectable bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Ejectable\").Store(&ejectable)\n\treturn\n}", "func (o *Drive) GetOptical(ctx context.Context) (optical bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Optical\").Store(&optical)\n\treturn\n}", "func (o *StoragePhysicalDiskAllOf) GetDriveState() string {\n\tif o == nil || o.DriveState == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveState\n}", "func NewDrive(object dbus.BusObject) *Drive {\n\treturn &Drive{object}\n}", "func (v Vehicle) DriveState() (*DriveState, error) {\n\tstateRequest, err := fetchState(\"/drive_state\", v.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stateRequest.Response.DriveState, nil\n}", "func (m *Drive) GetItems()([]DriveItemable) {\n return m.items\n}", "func (s *GDrive) Type() string {\n\treturn \"gdrive\"\n}", "func (o *Drive) GetWWN(ctx context.Context) (wWN string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"WWN\").Store(&wWN)\n\treturn\n}", "func (g Graph) getDrives(w http.ResponseWriter, r *http.Request, unrestricted bool) {\n\tsanitizedPath := strings.TrimPrefix(r.URL.Path, \"/graph/v1.0/\")\n\t// Parse the request with odata parser\n\todataReq, err := godata.ParseRequest(r.Context(), sanitizedPath, r.URL.Query())\n\tif err != nil {\n\t\tg.logger.Err(err).Interface(\"query\", r.URL.Query()).Msg(\"query error\")\n\t\terrorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tg.logger.Debug().\n\t\tInterface(\"query\", r.URL.Query()).\n\t\tBool(\"unrestricted\", unrestricted).\n\t\tMsg(\"Calling getDrives\")\n\tctx := r.Context()\n\n\tfilters, err := generateCs3Filters(odataReq)\n\tif err != nil {\n\t\tg.logger.Err(err).Interface(\"query\", r.URL.Query()).Msg(\"query error\")\n\t\terrorcode.NotSupported.Render(w, r, http.StatusNotImplemented, err.Error())\n\t\treturn\n\t}\n\tres, err := g.ListStorageSpacesWithFilters(ctx, filters, unrestricted)\n\tswitch {\n\tcase err != nil:\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesTransportErr)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\tcase res.Status.Code != cs3rpc.Code_CODE_OK:\n\t\tif res.Status.Code == cs3rpc.Code_CODE_NOT_FOUND {\n\t\t\t// return an empty list\n\t\t\trender.Status(r, http.StatusOK)\n\t\t\trender.JSON(w, r, &listResponse{})\n\t\t\treturn\n\t\t}\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesReturnsErr)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, res.Status.Message)\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tspaces, err := g.formatDrives(ctx, wdu, res.StorageSpaces)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error encoding response as json\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tspaces, err = sortSpaces(odataReq, spaces)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error sorting the spaces list\")\n\t\terrorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\trender.Status(r, http.StatusOK)\n\trender.JSON(w, r, &listResponse{Value: spaces})\n}", "func (m *Drive) GetSystem()(SystemFacetable) {\n return m.system\n}", "func (o *Drive) GetSize(ctx context.Context) (size uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Size\").Store(&size)\n\treturn\n}", "func (o *Drive) GetSortKey(ctx context.Context) (sortKey string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"SortKey\").Store(&sortKey)\n\treturn\n}", "func (d *portworx) GetDriver() (*v1.StorageCluster, error) {\n\t// TODO: Need to implement it for Daemonset deployment as well, right now its only for StorageCluster\n\tstcList, err := pxOperator.ListStorageClusters(d.namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed get StorageCluster list from namespace [%s], Err: %v\", d.namespace, err)\n\t}\n\n\tstc, err := pxOperator.GetStorageCluster(stcList.Items[0].Name, stcList.Items[0].Namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get StorageCluster [%s] from namespace [%s], Err: %v\", stcList.Items[0].Name, stcList.Items[0].Namespace, err.Error())\n\t}\n\n\treturn stc, nil\n}", "func (m *ItemDriveItemRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemDriveItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DriveItemable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateDriveItemFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DriveItemable), nil\n}", "func (o *MicrosoftGraphItemReference) GetDriveTypeOk() (string, bool) {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.DriveType, true\n}", "func (o *Drive) GetConnectionBus(ctx context.Context) (connectionBus string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"ConnectionBus\").Store(&connectionBus)\n\treturn\n}", "func (m *Drive) SetDriveType(value *string)() {\n m.driveType = value\n}", "func getGDriveClient(ctx context.Context, config *oauth2.Config, localConfigPath string, logger *log.Logger) *http.Client {\n\ttokenFile := filepath.Join(localConfigPath, gDriveTokenJSONFile)\n\ttok, err := gDriveTokenFromFile(tokenFile)\n\tif err != nil {\n\t\ttok = getGDriveTokenFromWeb(ctx, config, logger)\n\t\tsaveGDriveToken(tokenFile, tok, logger)\n\t}\n\n\treturn config.Client(ctx, tok)\n}", "func (o *MicrosoftGraphItemReference) SetDriveId(v string) {\n\to.DriveId = &v\n}", "func (obj *Global) GetLogicalDriveStrings(ctx context.Context) ([]*DriveInfo, error) {\n\tresult := &struct {\n\t\tDrives []*DriveInfo `json:\"qDrives\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetLogicalDriveStrings\", result)\n\treturn result.Drives, err\n}", "func (o *VirtualizationIweClusterAllOf) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (m *ItemSitesSiteItemRequestBuilder) Drive()(*ItemSitesItemDriveRequestBuilder) {\n return NewItemSitesItemDriveRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (o *MicrosoftGraphItemReference) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func OpenDrive() *OpenDriveOptions {\n\treturn &OpenDriveOptions{}\n}", "func (c *FakePortalDocumentClient) Get(ctx context.Context, partitionkey string, id string, options *Options) (*pkg.PortalDocument, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tif c.err != nil {\n\t\treturn nil, c.err\n\t}\n\n\tportalDocument, exists := c.portalDocuments[id]\n\tif !exists {\n\t\treturn nil, &Error{StatusCode: http.StatusNotFound}\n\t}\n\n\treturn c.decodePortalDocument(portalDocument)\n}", "func (c *Client) GetEndpoint() error {\n\treq, err := http.NewRequest(\"GET\", \"https://drive.amazonaws.com/drive/v1/account/endpoint\", nil)\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.config.AccessToken)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.Status != \"200 OK\" {\n\t\treturn errors.New(\"Unsuccessful response for getting endpoint\")\n\t}\n\n\tdec := json.NewDecoder(resp.Body)\n\tvar ep endpointStruct\n\tif err := dec.Decode(&ep); err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.config.ContentUrl = ep.ContentUrl\n\tc.config.MetaDataUrl = ep.MetaDataUrl\n\n\treturn nil\n}", "func (o *Drive) GetRemovable(ctx context.Context) (removable bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Removable\").Store(&removable)\n\treturn\n}", "func (a *HyperflexApiService) GetHyperflexDriveListExecute(r ApiGetHyperflexDriveListRequest) (*HyperflexDriveResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *HyperflexDriveResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.GetHyperflexDriveList\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/Drives\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tif r.filter != nil {\n\t\tlocalVarQueryParams.Add(\"$filter\", parameterToString(*r.filter, \"\"))\n\t}\n\tif r.orderby != nil {\n\t\tlocalVarQueryParams.Add(\"$orderby\", parameterToString(*r.orderby, \"\"))\n\t}\n\tif r.top != nil {\n\t\tlocalVarQueryParams.Add(\"$top\", parameterToString(*r.top, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"$skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.select_ != nil {\n\t\tlocalVarQueryParams.Add(\"$select\", parameterToString(*r.select_, \"\"))\n\t}\n\tif r.expand != nil {\n\t\tlocalVarQueryParams.Add(\"$expand\", parameterToString(*r.expand, \"\"))\n\t}\n\tif r.apply != nil {\n\t\tlocalVarQueryParams.Add(\"$apply\", parameterToString(*r.apply, \"\"))\n\t}\n\tif r.count != nil {\n\t\tlocalVarQueryParams.Add(\"$count\", parameterToString(*r.count, \"\"))\n\t}\n\tif r.inlinecount != nil {\n\t\tlocalVarQueryParams.Add(\"$inlinecount\", parameterToString(*r.inlinecount, \"\"))\n\t}\n\tif r.at != nil {\n\t\tlocalVarQueryParams.Add(\"at\", parameterToString(*r.at, \"\"))\n\t}\n\tif r.tags != nil {\n\t\tlocalVarQueryParams.Add(\"tags\", parameterToString(*r.tags, \"\"))\n\t}\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\", \"text/csv\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\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\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\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 (m *Drive) GetSpecial()([]DriveItemable) {\n return m.special\n}", "func (d *DriveDB) get(key []byte, item interface{}) error {\n\tdata, err := d.db.Get(key, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn decode(data, item)\n}", "func ExportDrive(conn *dbus.Conn, path dbus.ObjectPath, v Driveer) error {\n\treturn conn.ExportSubtreeMethodTable(map[string]interface{}{\n\t\t\"Eject\": v.Eject,\n\t\t\"SetConfiguration\": v.SetConfiguration,\n\t\t\"PowerOff\": v.PowerOff,\n\t}, path, InterfaceDrive)\n}", "func (a *PhonebookAccess1) GetFolder() (string, error) {\n\tv, err := a.GetProperty(\"Folder\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn v.Value().(string), nil\n}", "func (b *Dirs) Get(parentInode uint64, name string) (*wirefs.Dirent, error) {\n\tkey := dirKey(parentInode, name)\n\tbuf := b.b.Get(key)\n\tif buf == nil {\n\t\treturn nil, fuse.ENOENT\n\t}\n\n\tvar de wirefs.Dirent\n\tif err := proto.Unmarshal(buf, &de); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &de, nil\n}", "func (obj *Global) GetLogicalDriveStringsRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tDrives json.RawMessage `json:\"qDrives\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetLogicalDriveStrings\", result)\n\treturn result.Drives, err\n}", "func WatchDrive(client *Client, env *util.Env) {\n\tpull := func() {\n\t\tUpdateMenu(client, env)\n\t}\n\tutil.SetInterval(pull, time.Duration(env.CFG.Frequency)*time.Millisecond)\n\tpull()\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveTypeOk() (*string, bool) {\n\tif o == nil || o.DriveType == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DriveType, true\n}", "func (o *StorageFlexUtilVirtualDrive) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (db *DriveDb) LookupDrive(ident []byte) DriveModel {\n\tvar model DriveModel\n\n\tfor _, d := range db.Drives {\n\t\t// Skip placeholder entry\n\t\tif strings.HasPrefix(d.Family, \"$Id\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif d.Family == \"DEFAULT\" {\n\t\t\tmodel = d\n\t\t\tcontinue\n\t\t}\n\n\t\tif d.CompiledRegexp.Match(ident) {\n\t\t\tmodel.Family = d.Family\n\t\t\tmodel.ModelRegex = d.ModelRegex\n\t\t\tmodel.FirmwareRegex = d.FirmwareRegex\n\t\t\tmodel.WarningMsg = d.WarningMsg\n\t\t\tmodel.CompiledRegexp = d.CompiledRegexp\n\n\t\t\tfor id, p := range d.Presets {\n\t\t\t\tif _, exists := model.Presets[id]; exists {\n\t\t\t\t\t// Some drives override the conv but don't specify a name, so copy it from default\n\t\t\t\t\tif p.Name == \"\" {\n\t\t\t\t\t\tp.Name = model.Presets[id].Name\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmodel.Presets[id] = AttrConv{Name: p.Name, Conv: p.Conv}\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn model\n}", "func (vc *client) GetFolder(folderPath string) (*object.Folder, error) {\n\tlog.Info(fmt.Sprintf(\"Getting Folder `%s`\", folderPath))\n\n\tfolder, err := vc.finder.Folder(vc.context, folderPath)\n\tif err != nil {\n\t\tlog.Error(err, fmt.Sprintf(\"Error getting Folder `%s`\", folderPath))\n\t\treturn nil, err\n\t}\n\n\treturn folder, nil\n}", "func (o *Drive) GetRotationRate(ctx context.Context) (rotationRate int32, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"RotationRate\").Store(&rotationRate)\n\treturn\n}", "func (o *StorageFlexUtilVirtualDrive) GetVirtualDriveOk() (*string, bool) {\n\tif o == nil || o.VirtualDrive == nil {\n\t\treturn nil, false\n\t}\n\treturn o.VirtualDrive, true\n}", "func (m *Group) SetDrives(value []Driveable)() {\n m.drives = value\n}" ]
[ "0.752509", "0.7201301", "0.7189572", "0.6953924", "0.6819783", "0.6769293", "0.6731472", "0.66618615", "0.64475167", "0.6344764", "0.62929523", "0.6108446", "0.5979537", "0.59536654", "0.59533954", "0.59533954", "0.5950644", "0.59289634", "0.5919691", "0.5914934", "0.58727837", "0.58614016", "0.5853273", "0.58063877", "0.5759239", "0.5758416", "0.57436424", "0.56726915", "0.5670783", "0.565167", "0.56311315", "0.56101346", "0.55522907", "0.54844135", "0.54787785", "0.5457151", "0.5452468", "0.5442821", "0.54427224", "0.5418745", "0.5397032", "0.5389707", "0.53705436", "0.53365797", "0.5324481", "0.52474856", "0.5244638", "0.5229101", "0.5204504", "0.51863736", "0.51784724", "0.516728", "0.5164186", "0.5151046", "0.5136681", "0.51233554", "0.5097034", "0.50905925", "0.5071097", "0.50152254", "0.50119287", "0.49807876", "0.49614117", "0.4950061", "0.49439022", "0.49433175", "0.49013692", "0.48973396", "0.48915872", "0.48713312", "0.4859178", "0.4857685", "0.4841138", "0.4833732", "0.48237687", "0.48180023", "0.47971362", "0.47902197", "0.47851872", "0.47847214", "0.4775776", "0.4769202", "0.47675654", "0.4756815", "0.47502545", "0.47432235", "0.47370827", "0.47281557", "0.47101766", "0.468065", "0.46544757", "0.46524018", "0.46389487", "0.46312544", "0.46141207", "0.46135443", "0.45991832", "0.45990306", "0.45976627", "0.4595486" ]
0.78761816
0
GetItems gets the items property value. All items contained in the list.
GetItems получает значение свойства items. Все элементы, содержащиеся в списке.
func (m *List) GetItems()([]ListItemable) { return m.items }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (l *RestAPIList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func GetItems(c *gin.Context) {\n\tvar items []model.ItemJson\n\terr := util.DB.Table(\"items\").Find(&items).Error\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", items))\n\t}\n}", "func (out Outlooky) GetItems(folder *ole.IDispatch) *ole.IDispatch {\n\titems, err := out.CallMethod(folder, \"Items\")\n\tutil.Catch(err, \"Failed retrieving items.\")\n\n\treturn items.ToIDispatch()\n}", "func (l *IntegrationList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (api *API) ItemsGet(params Params) (res Items, err error) {\n\tif _, present := params[\"output\"]; !present {\n\t\tparams[\"output\"] = \"extend\"\n\t}\n\tresponse, err := api.CallWithError(\"item.get\", params)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treflector.MapsToStructs2(response.Result.([]interface{}), &res, reflector.Strconv, \"json\")\n\treturn\n}", "func (l *AuthorizerList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Client) GetItems(ctx context.Context, owner string) (Items, error) {\n\tresponse, err := c.sendRequest(ctx, owner, http.MethodGet, fmt.Sprintf(\"%s/%s\", c.storeBaseURL, c.bucket), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.Code != http.StatusOK {\n\t\tlevel.Error(c.getLogger(ctx)).Log(xlog.MessageKey(), \"Argus responded with non-200 response for GetItems request\",\n\t\t\t\"code\", response.Code, \"ErrorHeader\", response.ArgusErrorHeader)\n\t\treturn nil, fmt.Errorf(errStatusCodeFmt, response.Code, translateNonSuccessStatusCode(response.Code))\n\t}\n\n\tvar items Items\n\n\terr = json.Unmarshal(response.Body, &items)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetItems: %w: %s\", errJSONUnmarshal, err.Error())\n\t}\n\n\treturn items, nil\n}", "func (l *DeploymentList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *DomainNameList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *DocumentationVersionList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *ResourceList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *List) GetItems() []ListItem {\n\treturn l.items\n}", "func (l *StageList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *IntegrationResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (m *MGOStore) GetItems() interface{} {\n\treturn m.items\n}", "func (l *DocumentationPartList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Client) GetItems(id int) (Item, error) {\n\tc.defaultify()\n\tvar item Item\n\tresp, err := http.Get(fmt.Sprintf(\"%s/item/%d.json\", c.apiBase, id))\n\tif err != nil {\n\t\treturn item, err\n\t}\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\terr = dec.Decode(&item)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\treturn item, nil\n}", "func GetItems(c *gin.Context) {\n\tvar items []models.Item\n\tif err := models.DB.Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Could not find items\"})\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func GetItems(ctx *fasthttp.RequestCtx) {\n\tenc := json.NewEncoder(ctx)\n\titems := ReadItems()\n\tenc.Encode(&items)\n\tctx.SetStatusCode(fasthttp.StatusOK)\n}", "func (self *SearchJob) GetItems() (items []Item) {\n\tself.Mutex.Lock()\n\titems = self.Items\n\t//update last access time\n\tself.LastRead = time.Now()\n\t//write to the writer\n\tself.Items = make([]Item, 0)\n\tself.Mutex.Unlock()\n\tlog.Println(\"items:\",len(items))\n\treturn items\n}", "func (l *MethodList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *ModelList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *MethodResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *GatewayResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (s *GORMStore) GetItems() interface{} {\n\treturn s.items\n}", "func (l *APIKeyList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (us *ItemsUseCase) GetItems() ([]model.Item, *model.Error) {\n\treturn us.csvservice.GetItemsFromCSV()\n}", "func (db Database) GetItems() (*models.ItemList, error) {\n\tlist := &models.ItemList{}\n\n\trows, err := db.Conn.Query(\"SELECT * FROM items ORDER BY created_at desc;\")\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar item models.Item\n\n\t\tif err = rows.Scan(\n\t\t\t&item.ID,\n\t\t\t&item.Name,\n\t\t\t&item.Description,\n\t\t\t&item.Creation,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlist.Items = append(list.Items, item)\n\t}\n\n\treturn list, nil\n}", "func (m *ExternalConnection) GetItems()([]ExternalItemable) {\n return m.items\n}", "func (c *pricedCart) GetItems() []Item {\n\titems := make([]Item, len(c.items))\n\ti := 0\n\tfor _, item := range c.items {\n\t\titems[i] = *item\n\t\ti++\n\t}\n\treturn items\n}", "func (m *Drive) GetItems()([]DriveItemable) {\n return m.items\n}", "func getItems(w http.ResponseWriter, r *http.Request) {\n\titems, err := supermart.GetItems(r.Context(), r)\n\tif err != nil {\n\t\tutils.WriteErrorResponse(http.StatusInternalServerError, err, w)\n\t\treturn\n\t}\n\tutils.WriteResponse(http.StatusOK, items, w)\n}", "func (l *BasePathMappingList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (b *OGame) GetItems(celestialID ogame.CelestialID) ([]ogame.Item, error) {\n\treturn b.WithPriority(taskRunner.Normal).GetItems(celestialID)\n}", "func (l *VPCLinkList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func getItems(ctx context.Context, request events.APIGatewayProxyRequest,\n\tih *item.Handler) (events.APIGatewayProxyResponse, error) {\n\n\tvar list *item.List\n\n\tlist, err := ih.List(ctx, request.PathParameters[PathParamCategoryID])\n\tif err != nil {\n\t\treturn web.GetResponse(ctx, err.Error(), http.StatusInternalServerError)\n\t}\n\n\treturn web.GetResponse(ctx, list, http.StatusOK)\n}", "func (l *UsagePlanKeyList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Cache) GetItems() map[string]*Item {\n\treturn c.items\n}", "func (o *Invoice) GetItems() []InvoiceItems {\n\tif o == nil || o.Items == nil {\n\t\tvar ret []InvoiceItems\n\t\treturn ret\n\t}\n\treturn o.Items\n}", "func (l *UsagePlanList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *RequestValidatorList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Controller) GetItems() http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {\n\t\tu := utility.New(writer, req)\n\t\tsession := c.store.DB.Copy()\n\t\tdefer session.Close()\n\n\t\tvar items []Item\n\t\tcollection := session.DB(c.databaseName).C(ItemsCollection)\n\t\terr := collection.\n\t\t\tFind(nil).\n\t\t\tSelect(bson.M{\"_id\": 1, \"color\": 1, \"code\": 1, \"description\": 1, \"category\": 1}).\n\t\t\tSort(\"description\").\n\t\t\tAll(&items)\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\tu.WriteJSONError(\"verification failed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tu.WriteJSON(items)\n\t})\n}", "func (ris *rssItems) getItems() []RssItem {\n\tris.RLock()\n\tdefer ris.RUnlock()\n\treturn ris.items\n}", "func (svc *svc) ListItems(ctx context.Context, query model.ItemQuery) ([]model.Item, int64, error) {\n\titems, err := svc.repo.ListItems(ctx, query)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\ttotal, err := svc.repo.CountItems(ctx, query)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn items, total, nil\n}", "func GetItems(filter interface{}) (GetItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tcursor, err := c.collection(itemCollection).Find(context.Background(), filter)\n\tif err == mongo.ErrNoDocuments {\n\t\treturn GetItemResult{\n\t\t\tGotItemCount: 0,\n\t\t\tData: nil,\n\t\t}, nil\n\t} else if err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\n\tvar res []bson.M\n\tif err = cursor.All(context.Background(), &res); err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\treturn GetItemResult{\n\t\tGotItemCount: int64(len(res)),\n\t\tData: res,\n\t}, nil\n}", "func (is *ItemServices) Items(ctx context.Context, limit, offset int) ([]entity.Item, []error) {\n\titms, errs := is.itemRepo.Items(ctx, limit, offset)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn itms, errs\n}", "func (s *InventoryApiService) ListItems(w http.ResponseWriter) error {\n\tctx := context.Background()\n\tl, err := s.db.ListItems(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(l, nil, w)\n}", "func GetItems(huntID int) ([]*models.Item, *response.Error) {\n\titemDBs, e := db.GetItemsWithHuntID(huntID)\n\tif itemDBs == nil {\n\t\treturn nil, e\n\t}\n\n\titems := make([]*models.Item, 0, len(itemDBs))\n\tfor _, itemDB := range itemDBs {\n\t\titem := models.Item{ItemDB: *itemDB}\n\t\titems = append(items, &item)\n\t}\n\n\treturn items, e\n}", "func (o *CreditBankEmploymentReport) GetItems() []CreditBankEmploymentItem {\n\tif o == nil {\n\t\tvar ret []CreditBankEmploymentItem\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func GetItems() (items []Item, err error) {\n\tdir, err := os.Open(rootPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfi, err := dir.Stat()\n\tif !fi.Mode().IsDir() {\n\t\tpanic(\"need directory\")\n\t}\n\n\tnames, err := dir.Readdirnames(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, name := range names {\n\t\titem, err := NewItem(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\tsort.Sort(sort.Reverse(byCreatedAt(items)))\n\n\treturn items, nil\n}", "func (o *AssetReport) GetItems() []AssetReportItem {\n\tif o == nil {\n\t\tvar ret []AssetReportItem\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (c *M) Items() []*js.Object {\n\treturn c.items\n}", "func GetItems(da DataAccess, username string) (*ItemList, error) {\n\t// find the user and verify they exist\n\tuser, err := FindUserByName(da, username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// try to get their items\n\titems, err := da.GetItemsByUser(context.Background(), user.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// calculate net worth, asset total, liability total\n\tvar net, asset, liability int64\n\tfor i := range *items {\n\t\tif (*items)[i].Type == ItemTypeAsset {\n\t\t\tnet += (*items)[i].Value\n\t\t\tasset += (*items)[i].Value\n\t\t} else if (*items)[i].Type == ItemTypeLiability {\n\t\t\tnet -= (*items)[i].Value\n\t\t\tliability += (*items)[i].Value\n\t\t}\n\t}\n\n\treturn &ItemList{Username: username, Items: items, NetWorth: net, AssetTotal: asset, LiabilityTotal: liability}, nil\n}", "func (o TagsOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v Tags) []string { return v.Items }).(pulumi.StringArrayOutput)\n}", "func (o *MainSetStockStatusInput) GetItems() []MainStockItemState {\n\tif o == nil {\n\t\tvar ret []MainStockItemState\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (o PersistentVolumeListOutput) Items() PersistentVolumeTypeArrayOutput {\n\treturn o.ApplyT(func(v *PersistentVolumeList) PersistentVolumeTypeArrayOutput { return v.Items }).(PersistentVolumeTypeArrayOutput)\n}", "func (d *Database) GetItems(\n\treq GetItemsRequest) (*GetItemsResponse, error) {\n\tvar err error\n\tresp := GetItemsResponse{\n\t\tItems: []*structs.Item{}}\n\n\tif !req.Unread && req.ReadAfter == nil && req.ReadBefore == nil {\n\t\tlog.Info(\"GetItems() called with empty request\")\n\t\treturn &resp, nil\n\t}\n\n\tif len(req.FeedIDs) != 0 && req.CategoryID != nil {\n\t\treturn nil, errors.New(\"Can't call GetItems for both feeds and a category\")\n\t}\n\n\tif req.Unread && len(req.FeedIDs) == 0 {\n\t\treturn nil, errors.New(\"Can't request unread except by feeds\")\n\t}\n\n\tif (req.ReadAfter != nil) && (req.ReadBefore != nil) {\n\t\treturn nil, errors.New(\"Must not specify both ReadBefore and ReadAfter\")\n\t}\n\n\tif req.ReadAfter != nil {\n\t\t*req.ReadAfter = req.ReadAfter.UTC().Truncate(time.Second)\n\t}\n\n\tif req.ReadBefore != nil {\n\t\t*req.ReadBefore = req.ReadBefore.UTC().Truncate(time.Second)\n\t}\n\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\tif err := d.checkClosed(); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif !req.IncludeFeeds {\n\t\tresp.Items, err = getItemsFor(d.db, req)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &resp, nil\n\t}\n\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\tresp.Items, err = getItemsFor(tx, req)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif req.IncludeFeeds && req.FeedIDs != nil {\n\t\tresp.Feeds, err = getFeeds(tx, req.FeedIDs)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\ttx.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (o TagsResponseOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TagsResponse) []string { return v.Items }).(pulumi.StringArrayOutput)\n}", "func (r *CompanyItemsCollectionRequest) Get(ctx context.Context) ([]Item, error) {\n\treturn r.GetN(ctx, 0)\n}", "func (us *ItemsUseCase) GetItemsAPI(token string, query url.Values) ([]model.ApiItem, *model.Error) {\n\tnewItems, err := us.httpservice.GetItemAPI(token, query)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terrorSaveItem := us.csvservice.SaveItems(&newItems)\n\n\tif errorSaveItem != nil {\n\t\treturn nil, errorSaveItem\n\t}\n\n\treturn newItems, nil\n}", "func (r *MachinePoolsListResponse) GetItems() (value *MachinePoolList, ok bool) {\n\tok = r != nil && r.items != nil\n\tif ok {\n\t\tvalue = r.items\n\t}\n\treturn\n}", "func (b *Bag) Items() []Item {\n\treturn b.items\n}", "func (o MetadataOutput) Items() MetadataItemsItemArrayOutput {\n\treturn o.ApplyT(func(v Metadata) []MetadataItemsItem { return v.Items }).(MetadataItemsItemArrayOutput)\n}", "func (r *SubscriptionsListServerResponse) Items(value *SubscriptionList) *SubscriptionsListServerResponse {\n\tr.items = value\n\treturn r\n}", "func (o HorizontalPodAutoscalerListOutput) Items() HorizontalPodAutoscalerTypeArrayOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerList) HorizontalPodAutoscalerTypeArrayOutput { return v.Items }).(HorizontalPodAutoscalerTypeArrayOutput)\n}", "func (api *API) ItemsGetByApplicationID(id string) (res Items, err error) {\n\treturn api.ItemsGet(Params{\"applicationids\": id})\n}", "func (d *Dao) ItemList(ctx context.Context, params *model.SourceSearch) (itemsList []model.Items, err error) {\n\tquery := make(map[string]interface{})\n\tquery[\"pageNum\"] = params.PageNum\n\tquery[\"pageSize\"] = params.PageSize\n\tquery[\"shopId\"] = 0\n\tquery[\"keyword\"] = params.Keyword\n\tjsonQuery, _ := json.Marshal(query)\n\tresp, err := d.client.Post(d.c.URL.ItemSearch, \"application/json\", bytes.NewReader(jsonQuery))\n\tif err != nil {\n\t\tlog.Error(\"Request error(%v)\", err)\n\t\treturn\n\t}\n\tHTTPResponse := model.HTTPResponse{}\n\tbodyJSON, _ := ioutil.ReadAll(resp.Body)\n\tif err = json.Unmarshal(bodyJSON, &HTTPResponse); err != nil {\n\t\tlog.Error(\"json.Unmarshal error(%v)\", err)\n\t}\n\tif HTTPResponse.Code != 0 {\n\t\tlog.Error(\"Request (%s) search error(%v)\", d.c.URL.ItemSearch, err)\n\t\treturn\n\t}\n\titemsList = HTTPResponse.Data.List\n\treturn\n}", "func GetAllItems(w http.ResponseWriter, r *http.Request) {\r\n\titems, err := models.GetAllItems()\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusNotFound, \"Items could not be returned due to an error\")\r\n\t\treturn\r\n\t}\r\n\r\n\trespondWithJSON(w, http.StatusOK, items)\r\n}", "func (c *Container) Items(prefix string, cursor string, count int) ([]stow.Item, string, error) {\n\tquery := &storage.Query{Prefix: prefix}\n\tcall := c.Bucket().Objects(c.ctx, query)\n\n\tp := iterator.NewPager(call, count, cursor)\n\tvar results []*storage.ObjectAttrs\n\tnextPageToken, err := p.NextPage(&results)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tvar items []stow.Item\n\tfor _, item := range results {\n\t\ti, err := c.convertToStowItem(item)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\titems = append(items, i)\n\t}\n\n\treturn items, nextPageToken, nil\n}", "func (o *RoleListAllOf) GetItems() []Role {\n\tif o == nil || o.Items == nil {\n\t\tvar ret []Role\n\t\treturn ret\n\t}\n\treturn *o.Items\n}", "func (o HorizontalPodAutoscalerListTypeOutput) Items() HorizontalPodAutoscalerTypeArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerListType) []HorizontalPodAutoscalerType { return v.Items }).(HorizontalPodAutoscalerTypeArrayOutput)\n}", "func (o HorizontalPodAutoscalerListTypeOutput) Items() HorizontalPodAutoscalerTypeArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerListType) []HorizontalPodAutoscalerType { return v.Items }).(HorizontalPodAutoscalerTypeArrayOutput)\n}", "func (c *container) Items(prefix, cursor string, count int) ([]stow.Item, string, error) {\n\tvar entries []entry\n\tentries, cursor, err := c.getFolderItems([]entry{}, prefix, \"\", filepath.Join(c.location.config.basePath, c.name), cursor, count, false)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// Convert entries to []stow.Item\n\tsItems := make([]stow.Item, len(entries))\n\tfor i := range entries {\n\t\tsItems[i] = entries[i].item\n\t}\n\n\treturn sItems, cursor, nil\n}", "func (p *PaginationModel) ReadItems(v interface{}) error {\n\treturn json.Unmarshal(p.RawItems, v)\n}", "func (o TagsPtrOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Tags) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(pulumi.StringArrayOutput)\n}", "func (o IopingSpecVolumeVolumeSourceDownwardAPIOutput) Items() IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceDownwardAPI) []IopingSpecVolumeVolumeSourceDownwardAPIItems {\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput)\n}", "func (o *WorkflowListResponse) GetItems() []Workflow {\n\tif o == nil {\n\t\tvar ret []Workflow\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (o JobListTypeOutput) Items() JobTypeArrayOutput {\n\treturn o.ApplyT(func(v JobListType) []JobType { return v.Items }).(JobTypeArrayOutput)\n}", "func (oq *SortedQueue) Items() ItemList {\n\treturn oq.items\n}", "func (r *MachinePoolsListServerResponse) Items(value *MachinePoolList) *MachinePoolsListServerResponse {\n\tr.items = value\n\treturn r\n}", "func (c Caretaker) Items() []string {\n\tvar items []string\n\tfor k, _ := range c.o.data {\n\t\titems = append(items, k)\n\t}\n\n\treturn items\n}", "func (o *AclBindingListPage) GetItems() []AclBinding {\n\tif o == nil || o.Items == nil {\n\t\tvar ret []AclBinding\n\t\treturn ret\n\t}\n\treturn *o.Items\n}", "func (c *CaptureList) Items() []Capture {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\treturn c.items\n}", "func GetSelfItems() ([]Item, error) {\n\treq, _ := http.NewRequest(\"GET\", \"https://qiita.com/api/v2/authenticated_user/items\", nil)\n\tresbyte, err := DoRequest(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to DoRequest\")\n\t}\n\n\tvar items []Item\n\tif err := json.Unmarshal(resbyte, &items); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal\")\n\t}\n\treturn items, nil\n}", "func (o TagsResponsePtrOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *TagsResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(pulumi.StringArrayOutput)\n}", "func (c CacheReader) GetAllItems(ctx context.Context) ([]models.Item, error) {\n\tvar items []models.Item\n\n\terr := c.cache.Once(&cache.Item{\n\t\tKey: \"all\",\n\t\tValue: &items,\n\t\tTTL: c.cfg.CacheTimout,\n\t\tDo: func(*cache.Item) (interface{}, error) {\n\t\t\ti, err := c.reader.GetAllItems(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"cache\")\n\t\t\t}\n\t\t\treturn i, nil\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}", "func (m *statusTableDataModel) Items() interface{} {\n\treturn m.items\n}", "func (o *BatchCreateRoleAssignment) GetItems() []CreateRoleAssignment {\n\tif o == nil {\n\t\tvar ret []CreateRoleAssignment\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (c *Chromium) GetAllItems() ([]data.Item, error) {\n\tvar items []data.Item\n\tfor item, choice := range chromiumItems {\n\t\tm, err := GetItemPath(c.profilePath, choice.mainFile)\n\t\tif err != nil {\n\t\t\tlogger.Debugf(\"%s find %s file failed, ERR:%s\", c.name, item, err)\n\t\t\tcontinue\n\t\t}\n\t\ti := choice.newItem(m, \"\")\n\t\tlogger.Debugf(\"%s find %s File Success\", c.name, item)\n\t\titems = append(items, i)\n\t}\n\treturn items, nil\n}", "func (l *LogItems) Items() []*LogItem {\n\tl.mx.RLock()\n\tdefer l.mx.RUnlock()\n\n\treturn l.items\n}", "func getItemList(r *http.Request, pb transactionPb.TransactionService) (proto.Message, error) {\n\tpbRequest := &transactionPb.ItemListReq{}\n\tpbResponse, err := pb.GetItemList(context.Background(), pbRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pbResponse, nil\n}", "func (res ItemsResource) List(w http.ResponseWriter, r *http.Request) {\n\trender.JSON(w, r, items)\n}", "func (b *Bag) QueryItems() *BagItemQuery {\n\treturn (&BagClient{config: b.config}).QueryItems(b)\n}", "func GetItemsHandler(db *sqlx.DB) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar searchQuery ItemsGetQuery\n\t\tif err := ctx.ShouldBindQuery(&searchQuery); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tquery := sq.Select(\"items.public_id, name, price, unit, created_at, updated_at\").From(\"items\")\n\n\t\tif createdBy != \"\" {\n\t\t\tquery = query.Join(\"users ON users.id = items.created_by\").Where(sq.Eq{\"users.public_id\": createdBy})\n\t\t}\n\n\t\tif searchQuery.Name != \"\" {\n\t\t\tquery = query.Where(\"items.name LIKE ?\", fmt.Sprint(\"%\", searchQuery.Name, \"%\"))\n\t\t}\n\n\t\tqueryString, queryStringArgs, err := query.ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\titems := []Item{}\n\t\tif err := db.Select(&items, queryString, queryStringArgs...); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\n\t\tctx.JSON(http.StatusOK, items)\n\t}\n}", "func (r *MachinePoolsListResponse) Items() *MachinePoolList {\n\tif r == nil {\n\t\treturn nil\n\t}\n\treturn r.items\n}", "func (db *DB) Items() *ItemIterator {\n\treturn &ItemIterator{db: db}\n}", "func (o FioSpecVolumeVolumeSourceDownwardAPIOutput) Items() FioSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceDownwardAPI) []FioSpecVolumeVolumeSourceDownwardAPIItems {\n\t\treturn v.Items\n\t}).(FioSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput)\n}", "func (b *CompanyRequestBuilder) Items() *CompanyItemsCollectionRequestBuilder {\n\tbb := &CompanyItemsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/items\"\n\treturn bb\n}", "func GetList(c Context) {\n\tres, err := db.SelectAllItems()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, res)\n}", "func (o *RoleListAllOf) SetItems(v []Role) {\n\to.Items = &v\n}" ]
[ "0.75478745", "0.744459", "0.7434444", "0.74341697", "0.7407838", "0.73677117", "0.73617125", "0.7360272", "0.7359669", "0.7346144", "0.7336508", "0.7334327", "0.73200595", "0.7295804", "0.72761357", "0.72758305", "0.72643614", "0.7261494", "0.72567713", "0.7251349", "0.7244536", "0.7231289", "0.71946055", "0.71710896", "0.71686697", "0.71456456", "0.71053827", "0.7077708", "0.70618194", "0.7054976", "0.70537543", "0.70506066", "0.7049282", "0.7012157", "0.70017946", "0.6981622", "0.6949256", "0.690125", "0.6893008", "0.6881061", "0.68801546", "0.68694264", "0.6771782", "0.67012346", "0.668106", "0.6644188", "0.6520586", "0.6488233", "0.6450608", "0.6412892", "0.6392377", "0.6323595", "0.63167125", "0.63130563", "0.6308038", "0.62881166", "0.62848985", "0.6244262", "0.62409115", "0.6201512", "0.61974305", "0.6171747", "0.6168615", "0.61513764", "0.6150155", "0.6116454", "0.6108938", "0.60923177", "0.6092114", "0.60891134", "0.60865134", "0.60865134", "0.6084561", "0.60669935", "0.60423964", "0.6040523", "0.60404915", "0.6014265", "0.60138816", "0.5999712", "0.5983943", "0.598288", "0.59575015", "0.59552836", "0.5951859", "0.5951611", "0.59365827", "0.5925251", "0.5916604", "0.58928686", "0.5886617", "0.58829796", "0.5882622", "0.58758473", "0.5870828", "0.5853358", "0.58398885", "0.5839663", "0.58359593", "0.58355755" ]
0.7805831
0
GetList gets the list property value. Provides additional details about the list.
GetList получает значение свойства списка. Предоставляет дополнительные сведения о списке.
func (m *List) GetList()(ListInfoable) { return m.list }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *ClientImpl) GetList(ctx context.Context, args GetListArgs) (*PickList, error) {\n\trouteValues := make(map[string]string)\n\tif args.ListId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ListId\"}\n\t}\n\trouteValues[\"listId\"] = (*args.ListId).String()\n\n\tlocationId, _ := uuid.Parse(\"01e15468-e27c-4e20-a974-bd957dcccebc\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"6.0-preview.1\", routeValues, nil, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue PickList\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (l *Lists) GetList(id string) (*ListOutput, error) {\n\tif id == \"\" {\n\t\treturn nil, errors.New(\"goengage: id is required\")\n\t}\n\n\treq, err := l.client.newRequest(http.MethodGet, fmt.Sprintf(\"/lists/%v\", id), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar output ListOutput\n\terr = l.client.makeRequest(req, &output)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &output, err\n}", "func (p *Profile) ListGet() *queue.List {\n\treturn &p.List\n}", "func (a *alphaMock) GetList(ctx context.Context, in *alpha.GetListRequest, opts ...grpc.CallOption) (*alpha.List, error) {\n\t// TODO(#2716): Implement me!\n\treturn nil, errors.Errorf(\"Unimplemented -- GetList coming soon\")\n}", "func (n NestedInteger) GetList() []*NestedInteger {\n\tif n.single {\n\t\treturn nil\n\t} else {\n\t\tlist, _ := n.value.([]*NestedInteger)\n\t\treturn list\n\t}\n}", "func GetList(w http.ResponseWriter, r *http.Request) {\n\tlist, err := watchlist.GetWatchList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.JSON(w, list)\n}", "func (c *Client) GetList(board *trello.Board, name string) (*trello.List, error) {\n\tlists, err := board.GetLists(trello.Defaults())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, list := range lists {\n\t\tif list.Name == name {\n\t\t\treturn list, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find list %s on board %s\", name, board.Name)\n}", "func (n NestedInteger) GetList() []*NestedInteger {\n\treturn n.Ns\n}", "func (m *Drive) GetList()(Listable) {\n return m.list\n}", "func (c *Firewall) GetList() ([]string, error) {\n\tans := c.container()\n\treturn c.ns.Listing(util.Get, c.pather(), ans)\n}", "func GetList(c Context) {\n\tres, err := db.SelectAllItems()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, res)\n}", "func (ctl *SaleCounterProductController) GetList() {\n\tviewType := ctl.Input().Get(\"view\")\n\tif viewType == \"\" || viewType == \"table\" {\n\t\tctl.Data[\"ViewType\"] = \"table\"\n\t}\n\tctl.PageAction = utils.MsgList\n\tctl.Data[\"tableId\"] = \"table-sale-counter-product\"\n\tctl.Layout = \"base/base_list_view.html\"\n\tctl.TplName = \"sale/sale_counter_product_list_search.html\"\n}", "func (m *Mongo) GetList(ctx context.Context) ([]ListItem, error) {\n\tcoll := m.C.Database(m.dbName).Collection(listCollection)\n\n\tcursor, err := coll.Find(ctx, bson.D{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar list []ListItem\n\n\tfor cursor.Next(ctx) {\n\t\tvar item ListItem\n\n\t\terr = cursor.Decode(&item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlist = append(list, item)\n\t}\n\n\treturn list, nil\n}", "func (client *GroupMgmtClient) listGet(\n\tpath string,\n\tqueryParams map[string]string,\n\tparams *param.GetParams,\n) (interface{}, error) {\n\t// build the url\n\turl := fmt.Sprintf(\"%s/%s/detail\", client.URL, path)\n\n\tresponse, err := client.Client.R().\n\t\tSetQueryParams(queryParams).\n\t\tSetHeader(\"X-Auth-Token\", client.SessionToken).\n\t\tGet(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn processResponse(client, response, path, nil, params)\n}", "func getList(w io.Writer, r *http.Request) error {\n\tc := appengine.NewContext(r)\n\n\t// Get the list id from the URL.\n\tid := mux.Vars(r)[\"list\"]\n\n\t// Decode the obtained id into a datastore key.\n\tkey, err := datastore.DecodeKey(id)\n\tif err != nil {\n\t\treturn appErrorf(http.StatusBadRequest, \"invalid list id\")\n\t}\n\n\t// Fetch the list from the datastore.\n\tlist := &List{}\n\terr = datastore.Get(c, key, list)\n\tif err == datastore.ErrNoSuchEntity {\n\t\treturn appErrorf(http.StatusNotFound, \"list not found\")\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fetch list: %v\", err)\n\t}\n\n\t// Set the ID field with the id from the request url and encode the list.\n\tlist.ID = id\n\treturn json.NewEncoder(w).Encode(&list)\n}", "func (c *FwRouter) GetList() ([]string, error) {\n\tresult, _ := c.versioning()\n\treturn c.ns.Listing(util.Get, c.xpath(nil), result)\n}", "func (this NestedInteger) GetList() []*NestedInteger {\n\treturn nil\n}", "func (this NestedInteger) GetList() []*NestedInteger {\n\treturn nil\n}", "func (c *Client) GetList(dir string) ([]string, error) {\n\tvar list []string\n\n\t// Prepare the URL\n\tURL := fmt.Sprintf(wpListURL, dir)\n\n\t// Make the Request\n\tresp, err := c.getRequest(URL)\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\t// Drain body and check Close error\n\tdefer drainAndClose(resp.Body, &err)\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tmatches := regexList.FindAllStringSubmatch(string(bytes), -1)\n\n\t// Add all matches to extension list\n\tfor _, match := range matches {\n\t\tlist = append(list, match[1])\n\t}\n\n\treturn list, err\n}", "func (s *Storage) GetList(key string) ([]string, error) {\n\titem := s.get(key)\n\tif item == nil {\n\t\treturn nil, nil\n\t}\n\n\tif list, ok := item.value.([]string); ok {\n\t\treturn list, nil\n\t}\n\n\treturn nil, newErrCustom(errWrongType)\n}", "func (c *CappedList) List() []string {\n\t// get size of list\n\tsize, err := c.client.LLen(c.name).Result()\n\tif err != nil {\n\t\tsetup.LogCommon(err).Error(\"Failed LLen\")\n\t} else if size > c.size {\n\t\t// sanity check that the list is not bigger than possible\n\t\tsetup.LogCommon(nil).WithField(\"size\", size).Error(\"Size is larger than expected\")\n\t}\n\n\t// get the elements\n\tout, err := c.client.LRange(c.name, 0, size-1).Result()\n\tif err != nil {\n\t\tsetup.LogCommon(err).Error(\"Failed LRange\")\n\t}\n\n\treturn out\n\n}", "func (item Item) GetList(name string) sugar.List {\n\tlist := sugar.List{}\n\n\tswitch item[name].(type) {\n\tcase []interface{}:\n\t\tlist = make(sugar.List, len(item[name].([]interface{})))\n\n\t\tfor k, _ := range item[name].([]interface{}) {\n\t\t\tlist[k] = item[name].([]interface{})[k]\n\t\t}\n\t}\n\n\treturn list\n}", "func (nls *NetworkListService) GetNetworkList(ListID string, opts ListNetworkListsOptions) (*AkamaiNetworkList, *ClientResponse, error) {\n\n\tapiURI := fmt.Sprintf(\"%s/%s?listType=%s&extended=%t&includeDeprecated=%t&includeElements=%t\",\n\t\tapiPaths[\"network_list\"],\n\t\tListID,\n\t\topts.TypeOflist,\n\t\topts.Extended,\n\t\topts.IncludeDeprecated,\n\t\topts.IncludeElements)\n\n\tvar k *AkamaiNetworkList\n\tresp, err := nls.client.NewRequest(\"GET\", apiURI, nil, &k)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn k, resp, err\n\n}", "func (o *ViewProjectActivePages) GetList() bool {\n\tif o == nil || o.List == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.List\n}", "func (h *Handle) optionGetList(f func(*C.alpm_handle_t) *C.alpm_list_t) (StringList, error) {\n\talpmList := f(h.ptr)\n\tgoList := StringList{(*list)(unsafe.Pointer(alpmList))}\n\n\tif alpmList == nil {\n\t\treturn goList, h.LastError()\n\t}\n\n\treturn goList, nil\n}", "func GetList(tx *sql.Tx) (list []Info, err error) {\n\tmapper := rlt.NewAccountMapper(tx)\n\trows, err := mapper.FindAccountAll()\n\tfor _, row := range rows {\n\t\tinfo := Info{}\n\t\tinfo.ID = row.ID\n\t\tinfo.Domain = row.Domain.String\n\t\tinfo.UserName = row.UserName\n\t\tinfo.DisplayName = row.DisplayName\n\t\tinfo.Email = row.Email\n\t\tlist = append(list, info) //数据写入\n\t}\n\treturn list, err\n}", "func GetList(path string) ([]string, error) {\n\tftpConn, err := connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer ftpConn.Quit()\n\tvar entries []string\n\tentries, err = ftpConn.NameList(path)\n\tif err != nil {\n\t\treturn entries, &FTPError{\n\t\t\tMessage: fmt.Sprintf(\"获取路径%s下文件列表失败\", path),\n\t\t\tOriginErr: err,\n\t\t}\n\t}\n\n\treturn entries, nil\n}", "func (obj *Global) GetDocList(ctx context.Context) ([]*DocListEntry, error) {\n\tresult := &struct {\n\t\tDocList []*DocListEntry `json:\"qDocList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetDocList\", result)\n\treturn result.DocList, err\n}", "func (l *ArrayLister) List() ([]string, error) {\n\treturn l.Items, nil\n}", "func GetList(pattern string) ([]string, error) {\n\tconn := db.Pool.Get()\n\tdefer conn.Close()\n\n\treturn db.GetList(conn, pattern)\n}", "func (s *initServer) GetUserList(ctx context.Context, in *pb.UserListRequest) (*pb.UserListResponse, error) {\t\n\treturn userListTempl(ctx, in, \"userList:user\", false)\n}", "func (c *Client) List(ctx context.Context, p *ListPayload) (res *ListResult, err error) {\n\tvar ires interface{}\n\tires, err = c.ListEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*ListResult), nil\n}", "func GetList(str string) []string {\n\tif str == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(strings.Replace(str, \" \", \"\", -1), \",\")\n}", "func GetList(str, seperator string) ([]string, bool) {\n\tss := strings.Split(str, seperator)\n\tif len(ss) > 1 {\n\t\treturn ss, true\n\t}\n\treturn ss, false\n}", "func (f *StringList) Get() any {\n\tif f == nil {\n\t\treturn []string(nil)\n\t}\n\treturn *f\n}", "func GetUserList(w http.ResponseWriter, r *http.Request) {\n\n\tusers, err := user.GetUserList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"Ok\", users)\n}", "func testList(t *testing.T) *List {\n\tc := testClient()\n\tc.BaseURL = mockResponse(\"lists\", \"list-api-example.json\").URL\n\tlist, err := c.GetList(\"4eea4ff\", Defaults())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn list\n}", "func (a *adapter) getList() []*net.IPNet {\n\treturn a.atomicList.Load().([]*net.IPNet)\n}", "func GetList(pageNumber, minRating int, sort, order string) ([]Movie, error) {\n\tv := url.Values{}\n\tv.Set(\"limit\", \"50\")\n\tv.Set(\"sort_by\", sort)\n\tv.Set(\"order_by\", order)\n\tv.Set(\"minimum_rating\", strconv.Itoa(minRating))\n\tv.Set(\"page\", strconv.Itoa(pageNumber))\n\tURL := fmt.Sprintf(\"%s/list_movies.json?%s\", APIEndpoint, v.Encode())\n\treturn getMovieList(URL)\n}", "func (c *ChargeClient) GetList(ctx context.Context, paymentID string) ([]Charge, error) {\n\tvar charges []Charge\n\tif err := c.Caller.Call(ctx, \"GET\", c.chargesPath(paymentID), nil, nil, &charges); err != nil {\n\t\treturn nil, err\n\t}\n\treturn charges, nil\n}", "func GetListUser(c *gin.Context) {\r\n\tvar usr []model.UserTemporary\r\n\tres := model.GetLUser(usr)\r\n\r\n\tutils.WrapAPIData(c, map[string]interface{}{\r\n\t\t\"Data\": res,\r\n\t}, http.StatusOK, \"success\")\r\n}", "func (om *OrderedMap) GetList() (kvList []KV) {\n\tfor idx := 0; idx < len(om.kvList); idx++ {\n\t\tif om.kvList[idx] != nil {\n\t\t\tkvList = append(kvList, *om.kvList[idx])\n\t\t}\n\t}\n\treturn\n}", "func (_m *Usecase) GetList(ctx context.Context, pocketId int) ([]activities.Domain, error) {\n\tret := _m.Called(ctx, pocketId)\n\n\tvar r0 []activities.Domain\n\tif rf, ok := ret.Get(0).(func(context.Context, int) []activities.Domain); ok {\n\t\tr0 = rf(ctx, pocketId)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]activities.Domain)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, int) error); ok {\n\t\tr1 = rf(ctx, pocketId)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (element *Element) List(value string) *Element {\n\treturn element.Attr(\"list\", value)\n}", "func (s *ResolutionService) GetList(ctx context.Context) ([]Resolution, *Response, error) {\n\tapiEndpoint := \"rest/api/2/resolution\"\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresolutionList := []Resolution{}\n\tresp, err := s.client.Do(req, &resolutionList)\n\tif err != nil {\n\t\treturn nil, resp, NewJiraError(resp, err)\n\t}\n\treturn resolutionList, resp, nil\n}", "func (c *vaultLists) Get(name string, options v1.GetOptions) (result *v1alpha1.VaultList, err error) {\n\tresult = &v1alpha1.VaultList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"vaultlists\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (m *publicUser) GetUserList(c *gin.Context) (int, interface{}) {\n\tuser := plugins.CurrentPlugin(c, m.config.LoginVersion)\n\tuserList, err := user.GetUserList(c, m.config.ConfigMap)\n\trspBody := metadata.LonginSystemUserListResult{}\n\tif nil != err {\n\t\trspBody.Code = common.CCErrCommHTTPDoRequestFailed\n\t\trspBody.ErrMsg = err.Error()\n\t\trspBody.Result = false\n\t}\n\trspBody.Result = true\n\trspBody.Data = userList\n\treturn 200, rspBody\n}", "func GetListStops(api goemt.IAPI, postData PostListStops) (listStops []ListStops, err error) {\n\tif postData == nil {\n\t\tpostData = PostListStops{}\n\t}\n\tvar data auxListStops\n\terr = postInfoToPlatform(api, endpointListStops, postData, &data)\n\tif err != nil {\n\t\treturn listStops, err\n\t}\n\treturn data.Data, nil\n}", "func (tmdb *TMDb) GetListInfo(id string) (*ListInfo, error) {\n\tvar listInfo ListInfo\n\turi := fmt.Sprintf(\"%s/list/%v?api_key=%s\", baseURL, id, tmdb.apiKey)\n\tresult, err := getTmdb(uri, &listInfo)\n\treturn result.(*ListInfo), err\n}", "func GetListOptions(ctx *context.APIContext) models.ListOptions {\n\treturn models.ListOptions{\n\t\tPage: ctx.QueryInt(\"page\"),\n\t\tPageSize: convert.ToCorrectPageSize(ctx.QueryInt(\"limit\")),\n\t}\n}", "func (obj *Doc) GetMediaList(ctx context.Context) (*MediaList, error) {\n\tresult := &struct {\n\t\tList *MediaList `json:\"qList\"`\n\t\tReturn bool `json:\"qReturn\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetMediaList\", result)\n\treturn result.List, err\n}", "func GetListMeta(obj interface{}) (*api.ListMeta, error) {\n\tswitch t := obj.(type) {\n\tcase ListMetaAccessor:\n\t\tif meta := t.GetListMeta(); meta != nil {\n\t\t\treturn meta, nil\n\t\t}\n\t}\n\treturn nil, errNotListObject\n}", "func GetList() []string {\n\tvar envList []string\n\tif config.UsingDB() {\n\t\tenvList = getEnvironmentList()\n\t} else {\n\t\tds := datastore.New()\n\t\tenvList = ds.GetList(\"env\")\n\t\tenvList = append(envList, \"_default\")\n\t}\n\treturn envList\n}", "func (o *GetListParams) WithListID(listID int64) *GetListParams {\n\to.SetListID(listID)\n\treturn o\n}", "func (a *API) List(path string) (*ListObject, error) {\n\tvar out struct {\n\t\tObjects []*ListObject\n\t}\n\terr := a.Request(\"ls\", path).Exec(context.Background(), &out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(out.Objects) != 1 {\n\t\treturn nil, errors.New(\"bad response from server\")\n\t}\n\treturn out.Objects[0], nil\n}", "func (c *Dg) GetList() ([]string, error) {\n c.con.LogQuery(\"(get) list of device groups\")\n path := c.xpath(nil)\n return c.con.EntryListUsing(c.con.Get, path[:len(path) - 1])\n}", "func LoanGetList(l models.Loan, m *models.Message) {\n\tm.Code = http.StatusBadRequest\n\tif l.CodCollection <= 0 && l.CodClient <= 0 {\n\t\tm.Message = \"especifique cobro o cliente\"\n\t\treturn\n\t}\n\tls := []models.Loan{l}\n\tdb := configuration.GetConnection()\n\tdefer db.Close()\n\terr := getLoanList(&ls, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"no se encontro litado de prestamos\"\n\t\treturn\n\t}\n\tm.Code = http.StatusOK\n\tm.Message = \"lista de prestamos\"\n\tm.Data = ls\n}", "func (this NestedInteger) GetList() []*NestedInteger { panic(\"\") }", "func GetListMembersWithLists(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\r\n\tvar lists []List\r\n\r\n\tjson.NewDecoder(r.Body).Decode(&lists)\r\n\r\n\tvar listMembers = make([]ListMember, 0)\r\n\tfmt.Println(\"lists \", lists)\r\n\tfor _, list := range lists {\r\n\t\tvar listMemberArray []ListMember\r\n\t\tdb.Where(\"listID = ?\", list.UUID).Find(&listMemberArray)\r\n\t\tlistMembers = append(listMembers, listMemberArray...)\r\n\t}\r\n\tfmt.Println(\"listmembers \", listMembers)\r\n\tjson.NewEncoder(w).Encode(listMembers)\r\n}", "func (db *Mysql) GetLists(args *models.GetListsArgs, user *models.User) (*[]models.ListInfo, error) {\n\tvar lists []models.ListInfo\n\n\tteam, err := db.getTeamFromID(args.TeamID)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"func\": \"GetLists\",\n\t\t\t\"subFunc\": \"getTeamFromID\",\n\t\t\t\"userID\": user.ID,\n\t\t\t\"args\": *args,\n\t\t}).Error(err)\n\t\treturn nil, err\n\t}\n\n\tif team.AdminID != user.ID {\n\t\treturn nil, errors.New(\"User not admin of team\")\n\t}\n\n\terr = db.Client.Table(\"lists\").Joins(\"LEFT JOIN tasks on lists.id = tasks.list_id\").\n\t\tSelect(\"lists.*,\"+\n\t\t\t\"sum(case when complete = true AND tasks.archived = false then 1 else 0 end) as completed_tasks,\"+\n\t\t\t\"sum(case when complete = false AND tasks.archived = false then 1 else 0 end) as pending_tasks\").\n\t\tWhere(\"lists.archived = false AND lists.user_id = ? AND lists.team_id = ?\", user.ID, team.ID).\n\t\tGroup(\"lists.id\").\n\t\tFind(&lists).Error\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"func\": \"GetLists\",\n\t\t\t\"info\": \"retrieving list info\",\n\t\t\t\"userID\": user.ID,\n\t\t}).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn &lists, nil\n}", "func (c *Variable) GetList(tmpl, ts string) ([]string, error) {\n c.con.LogQuery(\"(get) list of template variables\")\n path := c.xpath(tmpl, ts, nil)\n return c.con.EntryListUsing(c.con.Get, path[:len(path) - 1])\n}", "func (yp *YamlParser) getListValue() error {\n\t// Skip prefix token\n\typ.move(len(TkPreListValue))\n\n\tv, err := yp.parseValue(\"\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\typ.currentNode.ntype = NodeTypeList\n\typ.appendValue(v)\n\n\treturn nil\n}", "func ContactListGet() ([]ContactList, error) {\n\tvar contacts []ContactList\n\trows, err := pool.Query(context.Background(), `\n\t\tSELECT\n\t\t\tc.id,\n\t\t\tc.name,\n\t\t\tco.id AS company_id,\n\t\t\tco.name AS company_name,\n\t\t\tpo.name AS post_name,\n\t\t\tarray_agg(DISTINCT ph.phone) AS phones,\n\t\t\tarray_agg(DISTINCT f.phone) AS faxes\n\t\tFROM\n\t\t\tcontacts AS c\n\t\tLEFT JOIN\n\t\t\tcompanies AS co ON c.company_id = co.id\n\t\tLEFT JOIN\n\t\t\tposts AS po ON c.post_id = po.id\n\t\tLEFT JOIN\n\t\t\tphones AS ph ON c.id = ph.contact_id AND ph.fax = false\n\t\tLEFT JOIN\n\t\t\tphones AS f ON c.id = f.contact_id AND f.fax = true\n\t\tGROUP BY\n\t\t\tc.id,\n\t\t\tco.id,\n\t\t\tpo.name\n\t\tORDER BY\n\t\t\tname ASC\n\t`)\n\tif err != nil {\n\t\terrmsg(\"GetContactList Query\", err)\n\t}\n\tfor rows.Next() {\n\t\tvar contact ContactList\n\t\terr := rows.Scan(&contact.ID, &contact.Name, &contact.CompanyID, &contact.CompanyName,\n\t\t\t&contact.PostName, &contact.Phones, &contact.Faxes)\n\t\tif err != nil {\n\t\t\terrmsg(\"GetContactList Scan\", err)\n\t\t\treturn contacts, err\n\t\t}\n\t\tcontacts = append(contacts, contact)\n\t}\n\treturn contacts, rows.Err()\n}", "func (pl *PolledList) List() *pb.ListResponse { return pl.resp.Load().(*pb.ListResponse) }", "func (pl *PolledList) List() *pb.ListResponse { return pl.resp.Load().(*pb.ListResponse) }", "func (a *AccessListService) GetAccessList(ctx context.Context, name string) (*accesslist.AccessList, error) {\n\taccessList, err := a.svc.GetResource(ctx, name)\n\treturn accessList, trace.Wrap(err)\n}", "func (s Store) List() ([]string, error) {\n\treturn s.backingStore.List(ItemType)\n}", "func (m *SharepointIds) GetListId()(*string) {\n val, err := m.GetBackingStore().Get(\"listId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func GetProfileList(ctx context.Context) ([]*shill.Profile, error) {\n\tmanager, err := shill.NewManager(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed creating shill manager object\")\n\t}\n\t// Refresh the in-memory profile list.\n\tif _, err := manager.GetProperties(ctx); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed refreshing the in-memory profile list\")\n\t}\n\t// Get current profiles.\n\tprofiles, err := manager.Profiles(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed getting profile list\")\n\t}\n\treturn profiles, nil\n}", "func (Alert) GetList(ctx goctx.Context, userID uint) []dto.Alert {\n\talerts := context.DB(ctx).Table(\"alert\")\n\n\tvar res []dto.Alert\n\talerts.Where(\"user_id = ?\", userID).Find(&res)\n\n\treturn res\n}", "func (s *PriorityService) GetList(ctx context.Context) ([]Priority, *Response, error) {\n\tapiEndpoint := \"rest/api/2/priority\"\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpriorityList := []Priority{}\n\tresp, err := s.client.Do(req, &priorityList)\n\tif err != nil {\n\t\treturn nil, resp, NewJiraError(resp, err)\n\t}\n\treturn priorityList, resp, nil\n}", "func (o *GetListParams) SetListID(listID int64) {\n\to.ListID = listID\n}", "func GetList(conn redis.Conn, pattern string) ([]string, error) {\n\treturn redis.Strings(conn.Do(\"KEYS\", pattern))\n}", "func (c *Contract) GetList(offset, limit int64) ([]Contract, error) {\n\tresult := new([]Contract)\n\terr := DBConn.Table(c.TableName()).Offset(offset).Limit(limit).Order(\"id asc\").Find(&result).Error\n\treturn *result, err\n}", "func (r *Readarr) GetImportList(importListID int64) (*ImportListOutput, error) {\n\treturn r.GetImportListContext(context.Background(), importListID)\n}", "func (s *Store) List() []string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tls := make([]string, 0, len(s.ls))\n\tfor p := range s.ls {\n\t\tls = append(ls, p)\n\t}\n\n\treturn ls\n}", "func (s *Store) List() []string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tls := make([]string, 0, len(s.ls))\n\tfor p := range s.ls {\n\t\tls = append(ls, p)\n\t}\n\n\treturn ls\n}", "func (a *Client) GetTokenList(params *GetTokenListParams) (*GetTokenListOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetTokenListParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getTokenList\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/asset/tokens\",\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: &GetTokenListReader{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\tsuccess, ok := result.(*GetTokenListOK)\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 getTokenList: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s Store) List() ([]string, error) {\n\treturn s.backingStore.List(ItemType, \"\")\n}", "func (c *cache) GetDeviceList() (devList []lava.DeviceList, err error) {\n\terr = c.updateDeviceList()\n\tdevList = c.deviceList.DeviceList\n\n\treturn\n}", "func (o *GetListParams) WithTimeout(timeout time.Duration) *GetListParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (b *ListBuilder) List() *CSPList {\n\treturn b.CspList\n}", "func (client Client) GetListResponder(resp *http.Response) (result VolumeInstanceListResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (l *list) Get() interface{} {\n\ttypeOf := reflect.TypeOf(l.t)\n\tsliceOf := reflect.SliceOf(typeOf)\n\tvar result = reflect.ValueOf(reflect.New(sliceOf).Interface()).Elem()\n\n\tl.ForEach(func(index int, el interface{}) {\n\t\tresult.Set(reflect.Append(result, reflect.ValueOf(el)))\n\t})\n\n\treturn result.Interface()\n}", "func (b *Base) GetSlotList(req *GetSlotListReq) (*GetSlotListResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}", "func (client ListManagementTermListsClient) GetDetails(ctx context.Context, listID string) (result TermList, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListManagementTermListsClient.GetDetails\")\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.GetDetailsPreparer(ctx, listID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementTermListsClient\", \"GetDetails\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetDetailsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementTermListsClient\", \"GetDetails\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetDetailsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementTermListsClient\", \"GetDetails\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (s *SalesPriceListDetailsEndpoint) List(ctx context.Context, division int, all bool, o *api.ListOptions) ([]*SalesPriceListDetails, error) {\n\tvar entities []*SalesPriceListDetails\n\tu, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/sales/SalesPriceListDetails\", division) // #nosec\n\tapi.AddListOptionsToURL(u, o)\n\n\tif all {\n\t\terr := s.client.ListRequestAndDoAll(ctx, u.String(), &entities)\n\t\treturn entities, err\n\t}\n\t_, _, err := s.client.NewRequestAndDo(ctx, \"GET\", u.String(), nil, &entities)\n\treturn entities, err\n}", "func (m *List) SetList(value ListInfoable)() {\n m.list = value\n}", "func (f *FeatureGateClient) GetFeatureList(ctx context.Context) (*corev1alpha2.FeatureList, error) {\n\tfeatures := &corev1alpha2.FeatureList{}\n\terr := f.crClient.List(ctx, features)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get features on cluster: %w\", err)\n\t}\n\treturn features, nil\n}", "func (obj *Global) GetStreamList(ctx context.Context) ([]*NxStreamListEntry, error) {\n\tresult := &struct {\n\t\tStreamList []*NxStreamListEntry `json:\"qStreamList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetStreamList\", result)\n\treturn result.StreamList, err\n}", "func (a Accessor) GetSubscriptionList(service, servicePath string, subscriptions *[]Subscription) error {\n\treturn a.access(&AccessParameter{\n\t\tEpID: EntryPointIDs.Subscriptions,\n\t\tMethod: gohttp.HttpMethods.GET,\n\t\tService: service,\n\t\tServicePath: servicePath,\n\t\tPath: \"\",\n\t\tReceivedBody: subscriptions,\n\t})\n}", "func GetLists(ctx Context) {\n\titems, err := db.SelectAllItems()\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, items)\n}", "func GetSecretList(c *gin.Context) {\n\trepo := session.Repo(c)\n\tlist, err := Config.Services.Secrets.SecretList(repo)\n\tif err != nil {\n\t\tc.String(500, \"Error getting secret list. %s\", err)\n\t\treturn\n\t}\n\t// copy the secret detail to remove the sensitive\n\t// password and token fields.\n\tfor i, secret := range list {\n\t\tlist[i] = secret.Copy()\n\t}\n\tc.JSON(200, list)\n}", "func (obj *Global) GetDocListRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tDocList json.RawMessage `json:\"qDocList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetDocList\", result)\n\treturn result.DocList, err\n}", "func (r *r) List() ([]*internal.Item, error) {\n\treturn nil, fmt.Errorf(\"not implemented yet\")\n}", "func (s *ServerConnection) MailingListsGet(query SearchQuery, domainId KId) (MlList, int, error) {\n\tquery = addMissedParametersToSearchQuery(query)\n\tparams := struct {\n\t\tQuery SearchQuery `json:\"query\"`\n\t\tDomainId KId `json:\"domainId\"`\n\t}{query, domainId}\n\tdata, err := s.CallRaw(\"MailingLists.get\", params)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tlist := struct {\n\t\tResult struct {\n\t\t\tList MlList `json:\"list\"`\n\t\t\tTotalItems int `json:\"totalItems\"`\n\t\t} `json:\"result\"`\n\t}{}\n\terr = json.Unmarshal(data, &list)\n\treturn list.Result.List, list.Result.TotalItems, err\n}", "func (r *FakeClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {\n\t// TODO (covariance) implement me!\n\tpanic(\"not implemented\")\n}", "func (c *Checklist) GetChecklist(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\tjson.NewEncoder(w).Encode(c.Items)\n}", "func (l *ToDoList) showList() []string {\n\treturn l.list\n}", "func (s *CallListsService) GetCallListDetails(params GetCallListDetailsParams) (*GetCallListDetailsReturn, *structure.VError, error) {\n\treq, err := s.client.NewRequest(\"POST\", \"GetCallListDetails\", params)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tresponse := &GetCallListDetailsReturn{}\n\tverr, err := s.client.MakeResponse(req, response)\n\tif verr != nil || err != nil {\n\t\treturn nil, verr, err\n\t}\n\treturn response, nil, nil\n}" ]
[ "0.7402214", "0.7211892", "0.7197566", "0.7090484", "0.7002887", "0.69607484", "0.69395965", "0.68194044", "0.6801362", "0.67747223", "0.6725991", "0.663443", "0.66022295", "0.6588623", "0.65876096", "0.65801454", "0.65714175", "0.65714175", "0.6566503", "0.6454622", "0.6409096", "0.62911844", "0.6214806", "0.61964786", "0.6189537", "0.61595297", "0.6131997", "0.6122757", "0.6096117", "0.60928833", "0.607829", "0.6032064", "0.6019856", "0.6009313", "0.59953886", "0.5995058", "0.59682524", "0.59586746", "0.5956028", "0.5946521", "0.59375024", "0.59360474", "0.5907806", "0.590699", "0.5904573", "0.5900708", "0.5887597", "0.58861136", "0.58836395", "0.58677685", "0.5859086", "0.58510494", "0.5848091", "0.5843247", "0.58289564", "0.58079445", "0.5795391", "0.57594067", "0.57368976", "0.5726731", "0.5726342", "0.5725025", "0.57040745", "0.56986004", "0.56986004", "0.56910485", "0.5686415", "0.5684947", "0.56814915", "0.56669605", "0.5662032", "0.56364954", "0.56356364", "0.5635325", "0.56235534", "0.5616956", "0.5616956", "0.5607719", "0.56061846", "0.5602275", "0.5587779", "0.55870914", "0.5584738", "0.5575373", "0.55726343", "0.5565984", "0.55541855", "0.55519086", "0.55456835", "0.5539817", "0.5537219", "0.552446", "0.55157477", "0.5508771", "0.5503025", "0.54980165", "0.54913", "0.5489442", "0.5485862", "0.54849756" ]
0.7468337
0
GetOperations gets the operations property value. The collection of longrunning operations on the list.
GetOperations получает значение свойства operations. Коллекция долгоживущих операций в списке.
func (m *List) GetOperations()([]RichLongRunningOperationable) { return m.operations }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Endpoint) GetOperations() []models.EndpointOperation {\n\treturn e.Operations\n}", "func GetOperations() ([]dtos.Operation, error) {\n\tvar ops []dtos.Operation\n\n\tresp, err := makeJSONRequest(\"GET\", apiURL+\"/operations\", http.NoBody)\n\tif err != nil {\n\t\treturn ops, errors.Append(err, ErrCannotConnect)\n\t}\n\n\tif err = evaluateResponseStatusCode(resp.StatusCode); err != nil {\n\t\treturn ops, err\n\t}\n\n\terr = readResponseBody(&ops, resp.Body)\n\n\treturn ops, err\n}", "func (m *Microservice) GetOperations(status string) (*c8y.OperationCollection, *c8y.Response, error) {\n\topt := &c8y.OperationCollectionOptions{\n\t\tStatus: status,\n\t\tAgentID: m.AgentID,\n\t\tPaginationOptions: c8y.PaginationOptions{\n\t\t\tPageSize: 5,\n\t\t\tWithTotalPages: false,\n\t\t},\n\t}\n\n\tdata, resp, err := m.Client.Operation.GetOperations(m.WithServiceUser(), opt)\n\treturn data, resp, err\n}", "func (c *jobsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v2/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (client BaseClient) ListOperations(ctx context.Context) (result Operations, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/BaseClient.ListOperations\")\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.ListOperationsPreparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListOperationsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListOperationsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *tensorboardRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/ui/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (process *Process) GetOperations() []*Operation {\n\n\t// fields\n\tfieldList := \"operation.id, operation.content, operation.start, operation.end, operation.is_running, operation.current_task, operation.result\"\n\n\t// the query\n\tsql := \"SELECT \" + fieldList + \" FROM `operation` AS operation WHERE process=? ORDER BY operation.id DESC\"\n\n\trows, err := database.Connection.Query(sql, process.Action.ID)\n\tif err != nil {\n\t\tfmt.Println(\"Problem #7 when getting all the operations of the process: \")\n\t\tfmt.Println(err)\n\t}\n\n\tvar (\n\t\tlist []*Operation\n\t\tID, currentTaskID int\n\t\tstart, end int64\n\t\tisRunning bool\n\t\tcontent, isRunningString, result string\n\t\ttask *Task\n\t)\n\n\tfor rows.Next() {\n\t\trows.Scan(&ID, &content, &start, &end, &isRunningString, &currentTaskID, &result)\n\n\t\tisRunning, err = strconv.ParseBool(isRunningString)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tif isRunning {\n\t\t\ttask = NewTask(currentTaskID)\n\t\t}\n\n\t\tlist = append(list, &Operation{\n\t\t\tCurrentTask: task,\n\t\t\tAction: &Action{\n\t\t\t\tID: ID,\n\t\t\t\tIsRunning: isRunning,\n\t\t\t\tStart: start,\n\t\t\t\tEnd: end,\n\t\t\t\tContent: content,\n\t\t\t\tresult: result,\n\t\t\t},\n\t\t})\n\t}\n\treturn list\n}", "func (c *cloudChannelRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (r *SpanReader) GetOperations(ctx context.Context, service string) ([]string, error){\n\treturn r.cache.LoadOperations(service)\n}", "func (m *Workbook) GetOperations()([]WorkbookOperationable) {\n return m.operations\n}", "func (m *List) SetOperations(value []RichLongRunningOperationable)() {\n m.operations = value\n}", "func (m *ExternalConnection) GetOperations()([]ConnectionOperationable) {\n return m.operations\n}", "func (so *Operations) Operations() api.Operations {\n\treturn api.Operations(so)\n}", "func (reader *LogzioSpanReader) GetOperations(ctx context.Context, query spanstore.OperationQueryParameters) ([]spanstore.Operation, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"GetOperations\")\n\tdefer span.Finish()\n\toperations, err := reader.serviceOperationStorage.getOperations(ctx, query.ServiceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []spanstore.Operation\n\tfor _, operation := range operations {\n\t\tresult = append(result, spanstore.Operation{\n\t\t\tName: operation,\n\t\t})\n\t}\n\treturn result, err\n\n\n}", "func (c *workflowsServiceV2BetaRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v2beta/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (m *Master) GetOperations(session *gocql.Session, hostname string) ([]ops.Operation, error) {\n\tvar operations []ops.Operation\n\tvar description, scriptName string\n\tvar attributes map[string]string\n\tq := `SELECT description, script_name, attributes FROM operations where hostname = ?`\n\titer := session.Query(q, hostname).Iter()\n\tfor iter.Scan(&description, &scriptName, &attributes) {\n\t\to := ops.Operation{\n\t\t\tDescription: description,\n\t\t\tScriptName: scriptName,\n\t\t\tAttributes: attributes,\n\t\t}\n\t\toperations = append(operations, o)\n\t}\n\tif err := iter.Close(); err != nil {\n\t\treturn []ops.Operation{}, fmt.Errorf(\"error getting operations from DB: %v\", err)\n\t}\n\n\treturn operations, nil\n}", "func (c *CloudChannelClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (bq *InMemoryBuildQueue) ListOperations(ctx context.Context, request *buildqueuestate.ListOperationsRequest) (*buildqueuestate.ListOperationsResponse, error) {\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\t// Obtain operation names in sorted order.\n\tnameList := make([]string, 0, len(bq.operationsNameMap))\n\tfor name := range bq.operationsNameMap {\n\t\tnameList = append(nameList, name)\n\t}\n\tsort.Strings(nameList)\n\tpaginationInfo, endIndex := getPaginationInfo(len(nameList), request.PageSize, func(i int) bool {\n\t\treturn request.StartAfter == nil || nameList[i] > request.StartAfter.OperationName\n\t})\n\n\t// Extract status.\n\tnameListRegion := nameList[paginationInfo.StartIndex:endIndex]\n\toperations := make([]*buildqueuestate.OperationState, 0, len(nameListRegion))\n\tfor _, name := range nameListRegion {\n\t\to := bq.operationsNameMap[name]\n\t\toperations = append(operations, o.getOperationState(bq))\n\t}\n\treturn &buildqueuestate.ListOperationsResponse{\n\t\tOperations: operations,\n\t\tPaginationInfo: paginationInfo,\n\t}, nil\n}", "func (c *Client) ListOperations(ctx context.Context, params *ListOperationsInput, optFns ...func(*Options)) (*ListOperationsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListOperationsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListOperations\", params, optFns, addOperationListOperationsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListOperationsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (cli *FakeDatabaseClient) ListOperations(ctx context.Context, in *lropb.ListOperationsRequest, opts ...grpc.CallOption) (*lropb.ListOperationsResponse, error) {\n\tatomic.AddInt32(&cli.listOperationsCalledCnt, 1)\n\treturn nil, nil\n}", "func ListOperations() ([]*op.Operation, error) {\n\tmessage := protocol.NewRequestListMessage()\n\terr := channel.Broadcast(message)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc1 := make(chan *protocol.ResponseList)\n\n\tonResponse := func(response *protocol.ResponseList) {\n\t\tc1 <- response\n\t}\n\n\tbus.SubscribeOnce(string(message.RequestList.ID), onResponse)\n\n\tselect {\n\tcase res := <-c1:\n\t\tif res.Result == protocol.ResponseOk {\n\t\t\treturn res.Operations, nil\n\t\t}\n\n\t\treturn nil, errors.New(string(res.Message))\n\tcase <-time.After(10 * time.Second):\n\t\tbus.Unsubscribe(string(message.RequestList.ID), onResponse)\n\t\treturn nil, errors.New(\"timeout\")\n\t}\n}", "func (o NamedRuleWithOperationsPatchOutput) Operations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v NamedRuleWithOperationsPatch) []string { return v.Operations }).(pulumi.StringArrayOutput)\n}", "func Operations() (string, error) {\n\treturn makeRequest(\"operations\")\n}", "func (c *TensorboardClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *JobsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *WorkflowsServiceV2BetaClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *cloudChannelReportsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (o NamedRuleWithOperationsOutput) Operations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v NamedRuleWithOperations) []string { return v.Operations }).(pulumi.StringArrayOutput)\n}", "func (s *OperationNamesStorage) GetOperations(service string) ([]string, error) {\n\titer := s.session.Query(s.QueryStmt, service).Iter()\n\n\tvar operation string\n\tvar operations []string\n\tfor iter.Scan(&operation) {\n\t\toperations = append(operations, operation)\n\t}\n\tif err := iter.Close(); err != nil {\n\t\terr = errors.Wrap(err, \"Error reading operation_names from storage\")\n\t\treturn nil, err\n\t}\n\treturn operations, nil\n}", "func (r *OperationsService) List(name string) *OperationsListCall {\n\tc := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *OperationsService) List(name string) *OperationsListCall {\n\tc := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *PolicyBasedRoutingClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (r *ManagedAppRegistrationOperationsCollectionRequest) Get(ctx context.Context) ([]ManagedAppOperation, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func (db Db) GetOperations(portfolioID string, key string, value string, from string, to string) ([]models.Operation, error) {\n\tpid, err := primitive.ObjectIDFromHex(portfolioID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not decode portfolio Id (%s). Internal error : %s\", portfolioID, err)\n\t}\n\n\tfilter := bson.M{\"pid\": pid}\n\tand := []interface{}{}\n\thasParams := false\n\tif key != \"\" && value != \"\" {\n\t\tand = append(and, bson.M{key: value})\n\t\thasParams = true\n\t}\n\n\tif dtime, err := time.Parse(\"2006-01-02T15:04:05Z07:00\", from); err == nil {\n\t\tand = append(and, bson.M{\"time\": bson.M{\"$gte\": dtime}})\n\t\thasParams = true\n\t}\n\n\tif dtime, err := time.Parse(\"2006-01-02T15:04:05Z07:00\", to); err == nil {\n\t\tand = append(and, bson.M{\"time\": bson.M{\"$lte\": dtime}})\n\t\thasParams = true\n\t}\n\tif hasParams {\n\t\tand = append(and, filter)\n\t\tfilter = bson.M{\"$and\": and}\n\t}\n\n\tfindOptions := options.Find()\n\tfindOptions.SetSort(bson.M{\"time\": 1})\n\treturn db.getOperations(filter, findOptions)\n}", "func (client *ApplicationClient) ListOperations(options *ApplicationClientListOperationsOptions) *ApplicationClientListOperationsPager {\n\treturn &ApplicationClientListOperationsPager{\n\t\tclient: client,\n\t\trequester: func(ctx context.Context) (*policy.Request, error) {\n\t\t\treturn client.listOperationsCreateRequest(ctx, options)\n\t\t},\n\t\tadvancer: func(ctx context.Context, resp ApplicationClientListOperationsResponse) (*policy.Request, error) {\n\t\t\treturn runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink)\n\t\t},\n\t}\n}", "func (eClass *eClassImpl) GetEAllOperations() EList {\n\teClass.getInitializers().initEAllOperations()\n\treturn eClass.eAllOperations\n}", "func (eClass *eClassImpl) GetEOperations() EList {\n\tif eClass.eOperations == nil {\n\t\teClass.eOperations = eClass.getInitializers().initEOperations()\n\t}\n\treturn eClass.eOperations\n}", "func (dop *patchCollector) Operations() []OperationSpec {\n\treturn dop.patchOperations\n}", "func (om *OperationsManager) GetOperation(ctx context.Context) (*model.Operation, error) {\n\tom.mutex.Lock()\n\tdefer om.mutex.Unlock()\n\n\ttx, err := om.transact.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer om.transact.RollbackUnlessCommitted(ctx, tx)\n\tctx = persistence.SaveToContext(ctx, tx)\n\n\toperations, err := om.opSvc.ListPriorityQueue(ctx, om.cfg.PriorityQueueLimit, om.opType)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while fetching operations from priority queue with type %v \", om.opType)\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, operation := range operations {\n\t\top, err := om.tryToGetOperation(ctx, operation.ID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif op != nil {\n\t\t\treturn op, nil\n\t\t}\n\t}\n\treturn nil, apperrors.NewNoScheduledOperationsError()\n}", "func NewOperations() *Operations {\n\treturn &Operations{}\n}", "func (r *InspectOperationsService) List(name string) *InspectOperationsListCall {\n\tc := &InspectOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *CloudChannelReportsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func getOperations(props *spec.PathItem) map[string]*spec.Operation {\n\tops := map[string]*spec.Operation{\n\t\t\"DELETE\": props.Delete,\n\t\t\"GET\": props.Get,\n\t\t\"HEAD\": props.Head,\n\t\t\"OPTIONS\": props.Options,\n\t\t\"PATCH\": props.Patch,\n\t\t\"POST\": props.Post,\n\t\t\"PUT\": props.Put,\n\t}\n\n\t// Keep those != nil\n\tfor key, op := range ops {\n\t\tif op == nil {\n\t\t\tdelete(ops, key)\n\t\t}\n\t}\n\treturn ops\n}", "func GetAll() (result []Operation) {\n\tview(func(k, v []byte) {\n\t\top := &Operation{}\n\t\tboltdb.DecodeValue(v, op, cfg.DataEncoding)\n\t\tresult = append(result, *op)\n\t})\n\treturn\n}", "func (p *profileCache) ResourceOperations(profileName string, cmd string, method string) ([]models.ResourceOperation, errors.EdgeX) {\n\tp.mutex.RLock()\n\tdefer p.mutex.RUnlock()\n\n\tif err := p.verifyProfileExists(profileName); err != nil {\n\t\treturn nil, err\n\t}\n\n\trosMap, err := p.verifyResourceOperationsExists(method, profileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ok bool\n\tvar ros []models.ResourceOperation\n\tif ros, ok = rosMap[cmd]; !ok {\n\t\terrMsg := fmt.Sprintf(\"failed to find DeviceCommand %s in Profile %s\", cmd, profileName)\n\t\treturn nil, errors.NewCommonEdgeX(errors.KindEntityDoesNotExist, errMsg, nil)\n\t}\n\n\treturn ros, nil\n}", "func (m *ExternalConnection) SetOperations(value []ConnectionOperationable)() {\n m.operations = value\n}", "func (p *Postgres) Operations() []bindings.OperationKind {\n\treturn []bindings.OperationKind{\n\t\texecOperation,\n\t\tqueryOperation,\n\t\tcloseOperation,\n\t}\n}", "func (client BaseClient) ListOperationsResponder(resp *http.Response) (result Operations, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *StoragePhysicalDisk) GetBackgroundOperations() string {\n\tif o == nil || o.BackgroundOperations == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.BackgroundOperations\n}", "func (op *OperationRequest) SetOperationsEndpoint() *OperationRequest {\n\treturn op.setEndpoint(\"operations\")\n}", "func (client BaseClient) GetAllOperations(ctx context.Context, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.GetAllOperations\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetAllOperationsPreparer(ctx, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetAllOperationsSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetAllOperationsResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (b *ManagedAppRegistrationRequestBuilder) Operations() *ManagedAppRegistrationOperationsCollectionRequestBuilder {\n\tbb := &ManagedAppRegistrationOperationsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/operations\"\n\treturn bb\n}", "func ToOperations(operations []operation.Operation) ([]*api.Operation, error) {\n\tvar pbOperations []*api.Operation\n\n\tfor _, o := range operations {\n\t\tpbOperation := &api.Operation{}\n\t\tvar err error\n\t\tswitch op := o.(type) {\n\t\tcase *operation.Set:\n\t\t\tpbOperation.Body, err = toSet(op)\n\t\tcase *operation.Add:\n\t\t\tpbOperation.Body, err = toAdd(op)\n\t\tcase *operation.Move:\n\t\t\tpbOperation.Body, err = toMove(op)\n\t\tcase *operation.Remove:\n\t\t\tpbOperation.Body, err = toRemove(op)\n\t\tcase *operation.Edit:\n\t\t\tpbOperation.Body, err = toEdit(op)\n\t\tcase *operation.Select:\n\t\t\tpbOperation.Body, err = toSelect(op)\n\t\tcase *operation.RichEdit:\n\t\t\tpbOperation.Body, err = toRichEdit(op)\n\t\tcase *operation.Style:\n\t\t\tpbOperation.Body, err = toStyle(op)\n\t\tcase *operation.Increase:\n\t\t\tpbOperation.Body, err = toIncrease(op)\n\t\tdefault:\n\t\t\treturn nil, ErrUnsupportedOperation\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpbOperations = append(pbOperations, pbOperation)\n\t}\n\n\treturn pbOperations, nil\n}", "func (m *Workbook) SetOperations(value []WorkbookOperationable)() {\n m.operations = value\n}", "func (handler *NullHandler) Operations() api_operation.Operations {\n\tops := api_operation.New_SimpleOperations()\n\n\t// Add Null config operations\n\tops.Add(api_operation.Operation(&NullConfigReadersOperation{}))\n\tops.Add(api_operation.Operation(&NullConfigWritersOperation{}))\n\t// Add Null setting operations\n\tops.Add(api_operation.Operation(&NullSettingGetOperation{}))\n\tops.Add(api_operation.Operation(&NullSettingSetOperation{}))\n\t// Add Null command operations\n\tops.Add(api_operation.Operation(&NullCommandListOperation{}))\n\tops.Add(api_operation.Operation(&NullCommandExecOperation{}))\n\t// Add Null documentation operations\n\tops.Add(api_operation.Operation(&NullDocumentTopicListOperation{}))\n\tops.Add(api_operation.Operation(&NullDocumentTopicGetOperation{}))\n\t// Add null monitor operations\n\tops.Add(api_operation.Operation(&NullMonitorStatusOperation{}))\n\tops.Add(api_operation.Operation(&NullMonitorInfoOperation{}))\n\tops.Add(api_operation.Operation(&api_monitor.MonitorStandardLogOperation{}))\n\t// Add Null orchestration operations\n\tops.Add(api_operation.Operation(&NullOrchestrateUpOperation{}))\n\tops.Add(api_operation.Operation(&NullOrchestrateDownOperation{}))\n\t// Add Null security handlers\n\tops.Add(api_operation.Operation(&NullSecurityAuthenticateOperation{}))\n\tops.Add(api_operation.Operation(&NullSecurityAuthorizeOperation{}))\n\tops.Add(api_operation.Operation(&NullSecurityUserOperation{}))\n\n\treturn ops.Operations()\n}", "func NewOperations(\n\texecutor interfaces.CommandExecutor,\n\tlc logger.LoggingClient,\n\texecutorPath string) *operations {\n\n\treturn &operations{\n\t\texecutor: executor,\n\t\tloggingClient: lc,\n\t\texecutorPath: executorPath,\n\t}\n}", "func (q *Q) Operations() OperationsQI {\n\treturn &OperationsQ{\n\t\tparent: q,\n\t\tsql: selectOperation,\n\t}\n}", "func (o *ResourceDefinitionFilter) GetOperation() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Operation\n}", "func (c *CloudChannelClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (g *Grafeas) GetOperation(pID, oID string) (*swagger.Operation, *errors.AppError) {\n\treturn g.S.GetOperation(pID, oID)\n}", "func (c *jobsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v2/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\topts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &longrunningpb.Operation{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn resp, nil\n}", "func (client ManagementClient) GetOperationResults(hostName string, filter string, top *int32, selectParameter string) (result OperationResultCollection, err error) {\n\treq, err := client.GetOperationResultsPreparer(hostName, filter, top, selectParameter)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetOperationResults\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetOperationResultsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetOperationResults\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetOperationResultsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetOperationResults\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (b *backend) GetSiteOperations(siteDomain string) ([]storage.SiteOperation, error) {\n\tif siteDomain == \"\" {\n\t\treturn nil, trace.BadParameter(\"missing parameter SiteDomain\")\n\t}\n\tids, err := b.getKeys(b.key(sitesP, siteDomain, operationsP))\n\tif err != nil {\n\t\tif trace.IsNotFound(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar out []storage.SiteOperation\n\tvar uncachedOperations []string\n\n\tb.cachedCompleteOperationsMutex.RLock()\n\tfor _, id := range ids {\n\t\tif op, ok := b.cachedCompleteOperations[id]; ok {\n\t\t\tout = append(out, *op)\n\t\t} else {\n\t\t\tuncachedOperations = append(uncachedOperations, id)\n\t\t}\n\t}\n\tb.cachedCompleteOperationsMutex.RUnlock()\n\n\tfor _, id := range uncachedOperations {\n\t\top, err := b.GetSiteOperation(siteDomain, id)\n\t\tif err != nil {\n\t\t\tif !trace.IsNotFound(err) {\n\t\t\t\treturn nil, trace.Wrap(err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tout = append(out, *op)\n\t}\n\n\tsort.Sort(operationsSorter(out))\n\treturn out, nil\n}", "func ExampleOperationsClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armmonitor.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewOperationsClient().List(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.OperationListResult = armmonitor.OperationListResult{\n\t// \tValue: []*armmonitor.Operation{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Operations/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Operations read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Operations\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Metrics/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metrics read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metrics\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Incidents/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule Incidents read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rule Incident resource\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/providers/Microsoft.Insights/MetricDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Activated/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity Log Alert Activated\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity Log Alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/EventCategories/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event category read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Event category\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/eventtypes/values/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event types management values read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Events\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/eventtypes/digestevents/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event types management digest read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Digest events\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log Definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Scaleup/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale scale up operation\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Scaledown/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale scale down operation\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Activated/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule activated\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Resolved/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule resolved\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Throttled/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule throttled\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Register/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Register Microsoft.Insights\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Microsoft.Insights\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Webtests/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Webtest write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Web tests\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Webtests/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Webtest delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Web tests\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t}},\n\t// }\n}", "func (r *AppsOperationsService) Get(appsId string, operationsId string) *AppsOperationsGetCall {\n\tc := &AppsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.appsId = appsId\n\tc.operationsId = operationsId\n\treturn c\n}", "func (c *TensorboardClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (c *JobsClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (bc *BaseController) GetOperationsByPermissionID(rID int64) ([]*dream.Operation, error) {\n\n\tresult, err := dream.GetOperationsByPermissionID(bc.DB, rID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (cli *FakeDatabaseClient) GetOperation(context.Context, *longrunning.GetOperationRequest, ...grpc.CallOption) (*longrunning.Operation, error) {\n\tatomic.AddInt32(&cli.getOperationCalledCnt, 1)\n\n\tswitch cli.NextGetOperationStatus() {\n\tcase StatusDone:\n\t\treturn &longrunning.Operation{Done: true}, nil\n\n\tcase StatusDoneWithError:\n\t\treturn &longrunning.Operation{\n\t\t\tDone: true,\n\t\t\tResult: &longrunning.Operation_Error{\n\t\t\t\tError: &status.Status{Code: int32(codes.Unknown), Message: \"Test Error\"},\n\t\t\t},\n\t\t}, nil\n\n\tcase StatusRunning:\n\t\treturn &longrunning.Operation{}, nil\n\n\tcase StatusNotFound:\n\t\treturn nil, grpcstatus.Errorf(codes.NotFound, \"\")\n\n\tcase StatusUndefined:\n\t\tpanic(\"Misconfigured test, set up expected operation status\")\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown status: %v\", cli.NextGetOperationStatus()))\n\t}\n}", "func (r *AppsOperationsService) List(appsId string) *AppsOperationsListCall {\n\tc := &AppsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.appsId = appsId\n\treturn c\n}", "func (handler *LocalHandler_Setting) Operations() api_operation.Operations {\n\tops := api_operation.New_SimpleOperations()\n\n\t// Make a wrapper for the Settings Config interpretation, based on itnerpreting YML settings\n\twrapper := handler_configwrapper.SettingsConfigWrapper(handler_configwrapper.New_BaseSettingConfigWrapperYmlOperation(handler.ConfigWrapper()))\n\n\t// Now we can add config operations that use that Base class\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperGetOperation{Wrapper: wrapper}))\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperSetOperation{Wrapper: wrapper}))\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperListOperation{Wrapper: wrapper}))\n\n\treturn ops.Operations()\n}", "func (operation *Operation) GetTasks() []*Task {\n\n\t// fields\n\tfieldList := \"task.id, task.content, task.start, task.end, task.is_running, task.result, task.explication\"\n\n\t// the query\n\tsql := \"SELECT \" + fieldList + \" FROM `task` WHERE operation=? ORDER BY task.id DESC\"\n\n\trows, err := database.Connection.Query(sql, operation.Action.ID)\n\tif err != nil {\n\t\tfmt.Println(\"Problem when getting all the tasks of the operation (Error #5): \")\n\t\tfmt.Println(err)\n\t}\n\n\tvar (\n\t\tlist []*Task\n\t\tID int\n\t\tstart, end int64\n\t\tisRunning bool\n\t\tcontent, isRunningString, result, explication string\n\t)\n\n\tfor rows.Next() {\n\t\trows.Scan(&ID, &content, &start, &end, &isRunningString, &result, &explication)\n\n\t\tisRunning, err = strconv.ParseBool(isRunningString)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tlist = append(list, &Task{\n\t\t\tExplication: explication,\n\t\t\tAction: &Action{\n\t\t\t\tID: ID,\n\t\t\t\tIsRunning: isRunning,\n\t\t\t\tStart: start,\n\t\t\t\tEnd: end,\n\t\t\t\tContent: content,\n\t\t\t\tresult: result,\n\t\t\t},\n\t\t})\n\t}\n\treturn list\n}", "func GetActiveOperations(siteKey SiteKey, operator Operator) (active []SiteOperation, err error) {\n\toperations, err := operator.GetSiteOperations(siteKey, OperationsFilter{\n\t\tActive: true,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif len(operations) == 0 {\n\t\treturn nil, trace.NotFound(\"no active operation found for %v\", siteKey)\n\t}\n\n\tfor _, op := range operations {\n\t\tactive = append(active, SiteOperation(op))\n\t}\n\n\treturn active, nil\n}", "func (p *BoteaterServiceClient) FetchOps(ctx context.Context, localRev int64, count int32, globalRev int64, individualRev int64) (r []*OperationStruct, err error) {\r\n var _args121 BoteaterServiceFetchOpsArgs\r\n _args121.LocalRev = localRev\r\n _args121.Count = count\r\n _args121.GlobalRev = globalRev\r\n _args121.IndividualRev = individualRev\r\n var _result122 BoteaterServiceFetchOpsResult\r\n if err = p.Client_().Call(ctx, \"fetchOps\", &_args121, &_result122); err != nil {\r\n return\r\n }\r\n switch {\r\n case _result122.E!= nil:\r\n return r, _result122.E\r\n }\r\n\r\n return _result122.GetSuccess(), nil\r\n}", "func (os *OpSet) Ops() []*Op {\n\treturn os.set\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (transactionMeta *TransactionMeta) OperationsMeta() []OperationMeta {\n\tswitch transactionMeta.V {\n\tcase 0:\n\t\treturn *transactionMeta.Operations\n\tcase 1:\n\t\treturn transactionMeta.MustV1().Operations\n\tcase 2:\n\t\treturn transactionMeta.MustV2().Operations\n\tcase 3:\n\t\treturn transactionMeta.MustV3().Operations\n\tdefault:\n\t\tpanic(\"Unsupported TransactionMeta version\")\n\t}\n}", "func (r *InspectOperationsService) Get(name string) *InspectOperationsGetCall {\n\tc := &InspectOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *cloudChannelRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\topts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &longrunningpb.Operation{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn resp, nil\n}", "func (req *UpsertObjectRequest) Operations(operations []Operation) *UpsertObjectRequest {\n\treq.operations = operations\n\treturn req\n}", "func (o *Volume) GetIops() int64 {\n\tif o == nil || o.Iops == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Iops\n}", "func (client DatasetClient) GetOperation(ctx context.Context, operationID string) (result LongRunningOperationResult, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/DatasetClient.GetOperation\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetOperationPreparer(ctx, operationID)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"GetOperation\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetOperationSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"GetOperation\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetOperationResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"GetOperation\", resp, \"Failure responding to request\")\n return\n }\n\n return\n}", "func GetOperation(name string) (*lropb.Operation, error) {\n\tctx := context.Background()\n\tclient, err := automl.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewClient: %v\", err)\n\t}\n\tdefer client.Close()\n\n\treq := &lropb.GetOperationRequest{\n\t\tName: name,\n\t}\n\n\treturn client.LROClient.GetOperation(ctx, req)\n}", "func (m *TeamItemRequestBuilder) Operations()(*i9fa0e9d329dc2b42ce0cc0330991bb8f8e864efaaef5061789d895e28321a6b2.OperationsRequestBuilder) {\n return i9fa0e9d329dc2b42ce0cc0330991bb8f8e864efaaef5061789d895e28321a6b2.NewOperationsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (r *OrganizationsOperationsService) List(name string) *OrganizationsOperationsListCall {\n\tc := &OrganizationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *OperationClient) Get(ctx context.Context, id uuid.UUID) (*Operation, error) {\n\treturn c.Query().Where(operation.ID(id)).Only(ctx)\n}", "func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (i *Info) GetQueryOps() []string {\n\n\t// checked in template already, but safety and stuff\n\tif len(i.Selectable) > 0 {\n\t\tos := strings.Split(i.Selectable, \",\")\n\t\tfor x := range os {\n\t\t\tos[x] = superCleanString(os[x])\n\t\t}\n\t\treturn os\n\t}\n\treturn nil\n}", "func (o *TOC) OutputOperations(i int, outputChapter outputs.Chapter, operations *kubernetes.ActionInfoList) error {\n\toperationsSection, err := outputChapter.AddSection(i, \"Operations\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, operation := range *operations {\n\t\to.OutputOperation(i, operationsSection, &operation)\n\t\t_ = operation\n\t}\n\treturn nil\n}" ]
[ "0.7211943", "0.7144373", "0.7129846", "0.7005646", "0.6984113", "0.6979087", "0.6979087", "0.6970134", "0.6949761", "0.6890829", "0.6889747", "0.6889747", "0.68835425", "0.68729496", "0.68609893", "0.68579656", "0.68536425", "0.67909795", "0.6768954", "0.6740723", "0.6734948", "0.67348295", "0.66751343", "0.66742504", "0.66699624", "0.6633077", "0.6630138", "0.65970755", "0.6535597", "0.6528932", "0.6394858", "0.6394858", "0.63838184", "0.6368351", "0.6361213", "0.6350676", "0.6350676", "0.632308", "0.61999637", "0.6193671", "0.6165864", "0.616416", "0.61617035", "0.6075222", "0.6057926", "0.60416687", "0.59913707", "0.5985264", "0.5961738", "0.58603764", "0.5852363", "0.58127856", "0.57003677", "0.5675637", "0.56630844", "0.565388", "0.5594034", "0.5581831", "0.5539351", "0.5517464", "0.54576683", "0.5442278", "0.5390083", "0.534994", "0.5325316", "0.52941656", "0.5280456", "0.5265064", "0.5264178", "0.52517617", "0.5241402", "0.5230426", "0.5230148", "0.5227759", "0.5217193", "0.5213738", "0.5213012", "0.5204429", "0.5197836", "0.5194437", "0.5172125", "0.51565325", "0.51565325", "0.51565325", "0.51565325", "0.51565325", "0.51542324", "0.51381236", "0.5127272", "0.5123834", "0.5122067", "0.5081803", "0.5079711", "0.50740767", "0.5070642", "0.5063568", "0.50594664", "0.50594664", "0.5055723", "0.5044171" ]
0.83329624
0
GetSharepointIds gets the sharepointIds property value. Returns identifiers useful for SharePoint REST compatibility. Readonly.
GetSharepointIds получает значение свойства sharepointIds. Возвращает идентификаторы, полезные для совместимости с SharePoint REST. Только для чтения.
func (m *List) GetSharepointIds()(SharepointIdsable) { return m.sharepointIds }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Drive) GetSharePointIds()(SharepointIdsable) {\n return m.sharePointIds\n}", "func (o *MicrosoftGraphItemReference) GetSharepointIds() AnyOfmicrosoftGraphSharepointIds {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret\n\t}\n\treturn *o.SharepointIds\n}", "func (o *MicrosoftGraphListItem) GetSharepointIds() AnyOfmicrosoftGraphSharepointIds {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret\n\t}\n\treturn *o.SharepointIds\n}", "func (m *List) SetSharepointIds(value SharepointIdsable)() {\n m.sharepointIds = value\n}", "func NewSharepointIds()(*SharepointIds) {\n m := &SharepointIds{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (o *MicrosoftGraphListItem) SetSharepointIds(v AnyOfmicrosoftGraphSharepointIds) {\n\to.SharepointIds = &v\n}", "func (o *MicrosoftGraphItemReference) SetSharepointIds(v AnyOfmicrosoftGraphSharepointIds) {\n\to.SharepointIds = &v\n}", "func (o *MicrosoftGraphListItem) HasSharepointIds() bool {\n\tif o != nil && o.SharepointIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Drive) SetSharePointIds(value SharepointIdsable)() {\n m.sharePointIds = value\n}", "func (o *MicrosoftGraphItemReference) GetSharepointIdsOk() (AnyOfmicrosoftGraphSharepointIds, bool) {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret, false\n\t}\n\treturn *o.SharepointIds, true\n}", "func (o *MicrosoftGraphListItem) GetSharepointIdsOk() (AnyOfmicrosoftGraphSharepointIds, bool) {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret, false\n\t}\n\treturn *o.SharepointIds, true\n}", "func (o *MicrosoftGraphItemReference) HasSharepointIds() bool {\n\tif o != nil && o.SharepointIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *SharepointIds) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"listId\", m.GetListId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"listItemId\", m.GetListItemId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"listItemUniqueId\", m.GetListItemUniqueId())\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.WriteStringValue(\"siteId\", m.GetSiteId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"siteUrl\", m.GetSiteUrl())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tenantId\", m.GetTenantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"webId\", m.GetWebId())\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}", "func getIds() []string {\n\tclient := &http.Client{}\n\tvar ids []string\n\tsongRequest, err := http.NewRequest(\"GET\", \"https://api.spotify.com/v1/me/tracks?limit=50&offset=0\", nil)\n\tsongRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(songRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\ttrack := gjson.Get(items.Array()[i].String(), \"track\")\n\t\t\tid := gjson.Get(track.String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\tids = append(ids, getPlaylistIds()...) // Calls to get song IDs from user playlists\n\treturn fixIds(ids)\n}", "func (m *SharepointIds) GetListItemId()(*string) {\n val, err := m.GetBackingStore().Get(\"listItemId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *SharepointIds) GetListId()(*string) {\n val, err := m.GetBackingStore().Get(\"listId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *DeviceManagementComplexSettingDefinition) GetPropertyDefinitionIds()([]string) {\n val, err := m.GetBackingStore().Get(\"propertyDefinitionIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func getPlaylistIds() []string {\n\tclient := &http.Client{}\n\n\tvar ids []string\n\turl := \"https://api.spotify.com/v1/users/\" + userId + \"/playlists?limit=50\"\n\tplaylistRequest, err := http.NewRequest(\"GET\", url, nil)\n\n\tplaylistRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(playlistRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\tid := gjson.Get(items.Array()[i].String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\treturn getPlaylistSongIds(ids)\n}", "func (m *SharepointIds) GetListItemUniqueId()(*string) {\n val, err := m.GetBackingStore().Get(\"listItemUniqueId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (d *Dispatch) GetIds(names ...string) (dispid []int32, err error) {\n\tdispid, err = d.Object.GetIDsOfName(names)\n\treturn\n}", "func (m *PromotionMutation) SaleIDs() (ids []int) {\n\tif id := m.sale; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (o *ViewUserDashboard) GetDashboardSettingIds() []int32 {\n\tif o == nil || o.DashboardSettingIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.DashboardSettingIds\n}", "func (c *Client) FindReportPointOfSaleReportInvoiceIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(ReportPointOfSaleReportInvoiceModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (m *UserMutation) SellsIDs() (ids []int) {\n\tfor id := range m.sells {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (m *SharepointIds) GetSiteId()(*string) {\n val, err := m.GetBackingStore().Get(\"siteId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (d docs) getIds() (ids []bson.ObjectId) {\n\tfor _, doc := range d {\n\t\tids = append(ids, doc[\"_id\"].(bson.ObjectId))\n\t}\n\treturn\n}", "func (op *ListSharedAccessOp) FolderIds(val ...string) *ListSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"folder_ids\", strings.Join(val, \",\"))\n\t}\n\treturn op\n}", "func (c *Client) ListIds() (*[]aadpodid.AzureIdentity, error) {\n\tbegin := time.Now()\n\n\tvar resList []aadpodid.AzureIdentity\n\n\tlist := c.IDInformer.GetStore().List()\n\tfor _, id := range list {\n\t\to, ok := id.(*aadpodv1.AzureIdentity)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to cast %T to %s\", id, aadpodv1.AzureIDResource)\n\t\t}\n\t\t// Note: List items returned from cache have empty Kind and API version..\n\t\t// Work around this issue since we need that for event recording to work.\n\t\to.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\tGroup: aadpodv1.SchemeGroupVersion.Group,\n\t\t\tVersion: aadpodv1.SchemeGroupVersion.Version,\n\t\t\tKind: reflect.TypeOf(*o).String()})\n\n\t\tout := aadpodv1.ConvertV1IdentityToInternalIdentity(*o)\n\n\t\tresList = append(resList, out)\n\t\tklog.V(6).Infof(\"appending AzureIdentity %s/%s to list.\", o.Namespace, o.Name)\n\t}\n\n\tstats.Aggregate(stats.AzureIdentityList, time.Since(begin))\n\treturn &resList, nil\n}", "func (o *ViewMilestone) GetTasklistIds() []int32 {\n\tif o == nil || o.TasklistIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.TasklistIds\n}", "func (o *MicrosoftGraphItemReference) GetShareId() string {\n\tif o == nil || o.ShareId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ShareId\n}", "func (m *SharepointIds) GetWebId()(*string) {\n val, err := m.GetBackingStore().Get(\"webId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func getRelatedSites(siteID int) []int {\n\n\tvar relatedSites []int\n\tDB.SQL(`select id from site where parent_site=$1`, siteID).QuerySlice(&relatedSites)\n\trelatedSites = append(relatedSites, siteID)\n\treturn relatedSites\n}", "func (m *RiskyServicePrincipalsDismissPostRequestBody) GetServicePrincipalIds()([]string) {\n val, err := m.GetBackingStore().Get(\"servicePrincipalIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func getTeamsIds(context context.Context, githubClient github.Client, githubOrganization string, githubTeams string) []int64 {\n\tgithubTeamsArr := strings.Split(githubTeams, \",\")\n\tteams, _, err := githubClient.Teams.ListTeams(context, githubOrganization, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\", err)\n\t}\n\tvar teamsIds = make([]int64, 0)\n\tfor _, team := range teams {\n\t\tif len(githubTeams) == 0 || contains(githubTeamsArr, *team.Name) {\n\t\t\tteamsIds = append(teamsIds, *team.ID)\n\t\t}\n\t}\n\treturn teamsIds\n}", "func CreateSharepointIdsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSharepointIds(), nil\n}", "func (client ListManagementImageClient) GetAllImageIds(ctx context.Context, listID string) (result ImageIds, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListManagementImageClient.GetAllImageIds\")\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.GetAllImageIdsPreparer(ctx, listID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"GetAllImageIds\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetAllImageIdsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"GetAllImageIds\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetAllImageIdsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"GetAllImageIds\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (m *Market) GetIDs() []string {\n\treturn m.ids\n}", "func (taskService TaskService) getTaskSites(ctx context.Context, managedEndpoints []gocql.UUID, siteIDs map[string]struct{}, partnerID string) map[string]struct{} {\n\tif len(managedEndpoints) == 0 {\n\t\treturn siteIDs\n\t}\n\n\tvar (\n\t\twg sync.WaitGroup\n\t\tmu sync.Mutex\n\t)\n\twg.Add(len(managedEndpoints))\n\n\tfor _, endpointID := range managedEndpoints {\n\t\tgo func(ctx context.Context, endpointID gocql.UUID) {\n\t\t\tdefer wg.Done()\n\n\t\t\tsiteID, _, err := taskService.assetsService.GetSiteIDByEndpointID(ctx, partnerID, endpointID)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log.WarnfCtx(ctx, \"cannot get siteID for ManagedEndpoint[%v]: %v\", endpointID, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tsiteIDs[siteID] = struct{}{}\n\t\t\tmu.Unlock()\n\t\t}(ctx, endpointID)\n\t}\n\n\twg.Wait()\n\treturn siteIDs\n}", "func (o *FiltersSecurityGroup) GetSecurityGroupIds() []string {\n\tif o == nil || o.SecurityGroupIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupIds\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetTransactionIds(opts *bind.CallOpts, from *big.Int, to *big.Int, pending bool, executed bool) ([]*big.Int, error) {\n\tvar (\n\t\tret0 = new([]*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getTransactionIds\", from, to, pending, executed)\n\treturn *ret0, err\n}", "func (pw *PlayerWalker) GetGameIDList(ctx context.Context, region region.Region, accountID string, opts *apiclient.GetMatchlistOptions) ([]int64, error) {\n\tvar gameIDList []int64\n\tmatchlist, err := pw.client.GetMatchlist(ctx, region, accountID, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, match := range matchlist.Matches {\n\t\tgameIDList = append(gameIDList, match.GameID)\n\t}\n\treturn gameIDList, nil\n}", "func (c *CampaignsListCall) Ids(ids ...int64) *CampaignsListCall {\n\tvar ids_ []string\n\tfor _, v := range ids {\n\t\tids_ = append(ids_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"ids\", ids_)\n\treturn c\n}", "func (driver *SQLDriver) ListIDs() ([]string, error) {\n\t// Execute a SELECT query to retrieve all the paste IDs\n\trows, err := driver.database.Query(\"SELECT id FROM ?\", driver.table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// Scan the rows into a slice of IDs and return it\n\tvar ids []string\n\terr = rows.Scan(&ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ids, nil\n}", "func (m *EntityMutation) SplitsIDs() (ids []int) {\n\tfor id := range m.splits {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (o *DataExportQuery) GetCampaignIds() []string {\n\tif o == nil || o.CampaignIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.CampaignIds\n}", "func (o GetServiceIdentityOutput) IdentityIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetServiceIdentity) []string { return v.IdentityIds }).(pulumi.StringArrayOutput)\n}", "func getTeamIDs(d *schema.ResourceData) []int {\n\tset := d.Get(\"team_ids\").(*schema.Set)\n\tteamIDs := make([]int, set.Len())\n\tfor i, teamID := range set.List() {\n\t\tteamIDs[i] = teamID.(int)\n\t}\n\treturn teamIDs\n}", "func fetchStoryIDs(feedType *string) []int {\n\turl := fmt.Sprintf(storiesFeedURL, *feedType)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tvar m []int\n\terr = json.Unmarshal(body, &m)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn m\n}", "func (s *Store) ShardIDs() []uint64 {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.shardIDs()\n}", "func (o GetFoldersResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetFoldersResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (o LookupNetworkPacketCoreControlPlaneResultOutput) SiteIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupNetworkPacketCoreControlPlaneResult) []string { return v.SiteIds }).(pulumi.StringArrayOutput)\n}", "func GetMenuItemsIds(output *[]int, dishIds []int, date int, db *sqlx.DB) error {\n\t// Build sql query\n\tq, a, _ := squirrel.Select(RowId).From(Table).Where(squirrel.Eq{DishId: dishIds, Date: date}).ToSql()\n\n\treturn db.Select(output, q, a...)\n}", "func (m *SharepointIds) SetListItemId(value *string)() {\n err := m.GetBackingStore().Set(\"listItemId\", value)\n if err != nil {\n panic(err)\n }\n}", "func getPlaylistSongIds(playlistIds []string) []string {\n\tclient := &http.Client{}\n\n\tvar ids []string\n\n\tfor _, plId := range playlistIds {\n\t\turl := \"https://api.spotify.com/v1/playlists/\" + plId + \"/tracks?market=US&fields=items(track(id))&limit=50&offset=0\"\n\t\tplaylistRequest, err := http.NewRequest(\"GET\", url, nil)\n\t\tplaylistRequest.Header.Add(\"Authorization\", key)\n\t\tresponse, err := client.Do(playlistRequest)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Request failed with error:\", err)\n\t\t} else {\n\t\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\t\titems := gjson.Get(string(data), \"items\")\n\t\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\t\tid := gjson.Get(items.Array()[i].String(), \"track.id\")\n\t\t\t\tids = append(ids, id.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn ids\n}", "func (m *ServicePrincipalRiskDetection) GetKeyIds()([]string) {\n val, err := m.GetBackingStore().Get(\"keyIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func (o GetFlowlogsResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetFlowlogsResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (p *ioThrottlerPool) GetIDs() []string {\n\tvar ids []string\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tfor id := range p.connections {\n\t\tids = append(ids, id)\n\t}\n\treturn ids\n}", "func (c *restClient) ListCollectionIds(ctx context.Context, req *firestorepb.ListCollectionIdsRequest, opts ...gax.CallOption) *StringIterator {\n\tit := &StringIterator{}\n\treq = proto.Clone(req).(*firestorepb.ListCollectionIdsRequest)\n\tm := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) {\n\t\tresp := &firestorepb.ListCollectionIdsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tjsonReq, err := m.Marshal(req)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v:listCollectionIds\", req.GetParent())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"POST\", baseUrl.String(), bytes.NewReader(jsonReq))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetCollectionIds(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *Client) FindSaleReportIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(SaleReportModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (c *Client) FindReportSaleReportSaleproformaIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(ReportSaleReportSaleproformaModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (a *App) GetIdentitiesList(ctx *fiber.Ctx) {\n\tidentities, err := a.store.GetIdentitiesList()\n\tif err != nil {\n\t\tctx.Send(err)\n\t}\n\terr = ctx.Status(fiber.StatusOK).JSON(identities)\n\tif err != nil {\n\t\tctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{\n\t\t\t\"error\": model.Errors{\n\t\t\t\tCode: fiber.StatusInternalServerError,\n\t\t\t\tDebug: \"Cannot get identities\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t\tRequest: ctx.Body(),\n\t\t\t\tStatus: \"Bad Request\",\n\t\t\t},\n\t\t})\n\t}\n}", "func (o *MicrosoftGraphMailSearchFolder) GetSourceFolderIds() []string {\n\tif o == nil || o.SourceFolderIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SourceFolderIds\n}", "func (m *SharepointIds) SetListId(value *string)() {\n err := m.GetBackingStore().Set(\"listId\", value)\n if err != nil {\n panic(err)\n }\n}", "func GetFavoriteItemIDs(w http.ResponseWriter, r *http.Request) {\n\tuser := UnmarshalUser(r.Body)\n\tfavoriteItems := dbP.GetFavoriteItemIDs(user.ID)\n\tresponse := marshalToJSON(favoriteItems, w)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(response)\n}", "func (c *Cgroups) ListPids(hs []string) []int {\n\tall := []int{}\n\tencountered := make(map[int]bool)\n\tfor _, h := range hs {\n\t\tall = append(all, c.listPids(h)...)\n\t}\n\n\tmerged := []int{}\n\tfor _, pid := range all {\n\t\tif !encountered[pid] {\n\t\t\tencountered[pid] = true\n\t\t\tmerged = append(merged, pid)\n\t\t}\n\t}\n\n\tsort.Ints(merged)\n\n\treturn merged\n}", "func ShareLists(hrcSrvShare unsafe.Pointer, hrcSrvSource unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpShareLists, 2, uintptr(hrcSrvShare), uintptr(hrcSrvSource), 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func (c *Client) FindSaleOrderLineIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(SaleOrderLineModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (o *V1SciNameAndIds) GetSciNameAndIds() []V1SciNameAndIdsSciNameAndId {\n\tif o == nil || o.SciNameAndIds == nil {\n\t\tvar ret []V1SciNameAndIdsSciNameAndId\n\t\treturn ret\n\t}\n\treturn *o.SciNameAndIds\n}", "func (pms MapState) getIdentities(log *logrus.Logger, denied bool) (ingIdentities, egIdentities []int64) {\n\tfor policyMapKey, policyMapValue := range pms {\n\t\tif denied != policyMapValue.IsDeny {\n\t\t\tcontinue\n\t\t}\n\t\tif policyMapKey.DestPort != 0 {\n\t\t\t// If the port is non-zero, then the Key no longer only applies\n\t\t\t// at L3. AllowedIngressIdentities and AllowedEgressIdentities\n\t\t\t// contain sets of which identities (i.e., label-based L3 only)\n\t\t\t// are allowed, so anything which contains L4-related policy should\n\t\t\t// not be added to these sets.\n\t\t\tcontinue\n\t\t}\n\t\tswitch trafficdirection.TrafficDirection(policyMapKey.TrafficDirection) {\n\t\tcase trafficdirection.Ingress:\n\t\t\tingIdentities = append(ingIdentities, int64(policyMapKey.Identity))\n\t\tcase trafficdirection.Egress:\n\t\t\tegIdentities = append(egIdentities, int64(policyMapKey.Identity))\n\t\tdefault:\n\t\t\ttd := trafficdirection.TrafficDirection(policyMapKey.TrafficDirection)\n\t\t\tlog.WithField(logfields.TrafficDirection, td).\n\t\t\t\tErrorf(\"Unexpected traffic direction present in policy map state for endpoint\")\n\t\t}\n\t}\n\treturn ingIdentities, egIdentities\n}", "func (s *Service) ListSharedAccess() *ListSharedAccessOp {\n\treturn &ListSharedAccessOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"GET\",\n\t\tPath: \"shared_access\",\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv2,\n\t}\n}", "func (m *DeviceManagementComplexSettingDefinition) SetPropertyDefinitionIds(value []string)() {\n err := m.GetBackingStore().Set(\"propertyDefinitionIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o ServiceIdentityOutput) IdentityIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceIdentity) []string { return v.IdentityIds }).(pulumi.StringArrayOutput)\n}", "func (o GetSecondaryIndexesResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetSecondaryIndexesResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigSession) GetTransactionIds(from *big.Int, to *big.Int, pending bool, executed bool) ([]*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetTransactionIds(&_ReserveSpenderMultiSig.CallOpts, from, to, pending, executed)\n}", "func (c *Client) ListPodIds(podns, podname string) (map[string][]aadpodid.AzureIdentity, error) {\n\tlist, err := c.ListAssignedIDs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidStateMap := make(map[string][]aadpodid.AzureIdentity)\n\tfor _, v := range *list {\n\t\tif v.Spec.Pod == podname && v.Spec.PodNamespace == podns {\n\t\t\tidStateMap[v.Status.Status] = append(idStateMap[v.Status.Status], *v.Spec.AzureIdentityRef)\n\t\t}\n\t}\n\treturn idStateMap, nil\n}", "func (mcr *MiddlewareClusterRepo) GetMiddlewareServerIDList(clusterID int) ([]int, error) {\n\tsql := `select id from t_meta_middleware_server_info\n where del_flag = 0\n and cluster_id = ?\n\t\t order by id;\n\t`\n\tlog.Debugf(\"metadata MiddlewareCLusterRepo.GetMiddlewareServerIDList() select sql: %s\", sql)\n\tresult, err := mcr.Execute(sql, clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresultNum := result.RowNumber()\n\tserverIDList := make([]int, resultNum)\n\tfor row := 0; row < resultNum; row++ {\n\t\tserverID, err := result.GetInt(row, constant.ZeroInt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserverIDList[row] = serverID\n\t}\n\treturn serverIDList, nil\n}", "func (m *OrganizationMutation) StaffsIDs() (ids []int) {\n\tfor id := range m.staffs {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (m *UserMutation) SpouseIDs() (ids []int) {\n\tif id := m.spouse; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (s *Server) GetUserFollowingIds(ctx context.Context, req *pbApi.GetBasicUserDataRequest) (*pbApi.UserList, error) {\n\tif s.dbHandler == nil {\n\t\treturn nil, status.Error(codes.Internal, \"No database connection\")\n\t}\n\tpbUser, err := s.dbHandler.User(req.UserId)\n\tif err != nil {\n\t\tif errors.Is(err, dbmodel.ErrUserNotFound) {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\treturn &pbApi.UserList{\n\t\tIds: pbUser.FollowingIds,\n\t}, nil\n}", "func (c *PlacementsListCall) SiteIds(siteIds ...int64) *PlacementsListCall {\n\tvar siteIds_ []string\n\tfor _, v := range siteIds {\n\t\tsiteIds_ = append(siteIds_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"siteIds\", siteIds_)\n\treturn c\n}", "func (c *Channel) GetMSPIDs() []string {\n\tac, ok := c.Resources().ApplicationConfig()\n\tif !ok || ac.Organizations() == nil {\n\t\treturn nil\n\t}\n\n\tvar mspIDs []string\n\tfor _, org := range ac.Organizations() {\n\t\tmspIDs = append(mspIDs, org.MSPID())\n\t}\n\n\treturn mspIDs\n}", "func getNewsItems() []string {\n\turl := baseURL + \"/newstories.json\"\n\tbody := fmtRes(url)\n\tstoryIds := strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(string(body)), \"[\"), \"]\")\n\tidSlice := strings.Split(storyIds, \",\")\n\treturn idSlice\n}", "func (o GetTlsActivationIdsResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetTlsActivationIdsResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (c *Client) GetEndpointsByGroupIDs(ctx context.Context, targetIDs []string, createdBy, partnerID string, hasNOCAccess bool) (ids []gocql.UUID, err error) {\n\tvar (\n\t\tuserSites entities.UserSites\n\t\tpayload []dgResponse\n\t\twg sync.WaitGroup\n\t\tuserSitesMap = make(map[string]struct{})\n\t\terrChan = make(chan error, 2)\n\t\tdone = make(chan int)\n\t)\n\n\tif !hasNOCAccess {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tuserSites, err = c.userRepo.Sites(ctx, partnerID, createdBy)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- fmt.Errorf(\"error while getting user sites fron Cassandra, err: %v\", err)\n\t\t\t}\n\n\t\t\tfor _, siteID := range userSites.SiteIDs {\n\t\t\t\tsiteIDstr := strconv.FormatInt(siteID, 10)\n\t\t\t\tuserSitesMap[siteIDstr] = struct{}{}\n\t\t\t}\n\t\t}()\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\turl := fmt.Sprintf(\"%s/partners/%s/dynamic-groups/managed-endpoints/set?expression=%s\",\n\t\t\tconfig.Config.DynamicGroupsMsURL, partnerID, strings.Join(targetIDs, dgDelimiter))\n\n\t\tif err := integration.GetDataByURL(ctx, &payload, c.httpClient, url, \"\", true); err != nil {\n\t\t\terrChan <- err\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor e := range errChan {\n\t\t\terr = fmt.Errorf(\"%v %v\", err, e)\n\t\t}\n\t\tdone <- 1\n\t}()\n\n\twg.Wait()\n\tclose(errChan)\n\t<-done\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.filterResponse(payload, userSitesMap, hasNOCAccess), nil\n}", "func (keyRing *KeyRing) KeyIds() []uint64 {\n\tvar res []uint64\n\tfor _, e := range keyRing.entities {\n\t\tres = append(res, e.PrimaryKey.KeyId)\n\t}\n\treturn res\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCallerSession) GetTransactionIds(from *big.Int, to *big.Int, pending bool, executed bool) ([]*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetTransactionIds(&_ReserveSpenderMultiSig.CallOpts, from, to, pending, executed)\n}", "func (o *FiltersVmGroup) GetSecurityGroupIds() []string {\n\tif o == nil || o.SecurityGroupIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupIds\n}", "func GetSnapshotIds(ctx *pulumi.Context, args *GetSnapshotIdsArgs, opts ...pulumi.InvokeOption) (*GetSnapshotIdsResult, error) {\n\tvar rv GetSnapshotIdsResult\n\terr := ctx.Invoke(\"aws:ebs/getSnapshotIds:getSnapshotIds\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func getRouteIds(data map[string]string) []string {\n\tids := make([]string, len(data))\n\tindex := 0\n\tfor id, _ := range data {\n\t\tids[index] = id\n\t\tindex++\n\t}\n\n\treturn ids\n}", "func (c *Client) ShardIDs() []uint64 {\n\tvar a []uint64\n\tfor _, dbi := range c.data().Data.Databases {\n\t\tfor _, rpi := range dbi.RetentionPolicies {\n\t\t\tfor _, sgi := range rpi.ShardGroups {\n\t\t\t\tfor _, si := range sgi.Shards {\n\t\t\t\t\ta = append(a, si.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(uint64Slice(a))\n\treturn a\n}", "func (m *MockResolver) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]dbstore.Upload, error) {\n\tr0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...)\n\tm.GetUploadsByIDsFunc.appendCall(ResolverGetUploadsByIDsFuncCall{v0, v1, r0, r1})\n\treturn r0, r1\n}", "func (s *Service) ListClientID() []string {\n\tlistIDs := []string{}\n\tfor _, client := range s.Clients {\n\t\tlistIDs = append(listIDs, client.ID.String())\n\t}\n\treturn listIDs\n}", "func (o ResourcePolicyExemptionOutput) PolicyDefinitionReferenceIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyExemption) pulumi.StringArrayOutput { return v.PolicyDefinitionReferenceIds }).(pulumi.StringArrayOutput)\n}", "func GetAllMultiTokenIds() (lups []Lookup, err error) {\n\treturn getAllTokensOfType(2)\n}", "func GetIdentities(accessToken string) ([]client.Identity, error) {\n\tif provider != nil {\n\t\treturn provider.GetIdentities(accessToken)\n\t}\n\treturn []client.Identity{}, fmt.Errorf(\"No auth provider configured\")\n}", "func GetPids() (pids []string, err error) {\n\tp, err := os.Open(util.ProcLocation)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer p.Close()\n\n\tpids = make([]string, 0)\n\tfor {\n\t\tfileInfos, err := p.Readdir(10)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, fileInfo := range fileInfos {\n\t\t\t// We only care about directories, since all pids are dirs\n\t\t\tif !fileInfo.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// We only care if the name starts with a numeric\n\t\t\tname := fileInfo.Name()\n\t\t\tif pid, err := strconv.Atoi(name); err == nil {\n\t\t\t\tspid := strconv.Itoa(pid)\n\t\t\t\tpids = append(pids, spid)\n\t\t\t}\n\t\t}\n\t}\n\treturn pids, err\n}", "func (u *AccountRow) GetBookmarkCollectionIDs() (*BookmarkRow, error) {\n\tquery := `\n\t\tselect id, location_ids from bookmarks where id = $1`\n\n\trowData := &BookmarkRow{}\n\trow := GlobalConn.QueryRow(query, u.ID)\n\n\tif err := row.Scan(&rowData.ID, &rowData.LocationIDs); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn rowData, nil\n}", "func (o *ViewUserDashboard) GetDashboardPanelIds() []int32 {\n\tif o == nil || o.DashboardPanelIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.DashboardPanelIds\n}", "func (o GetAlarmContactsResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetAlarmContactsResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (m *MockUploadService) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) {\n\tr0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...)\n\tm.GetUploadsByIDsFunc.appendCall(UploadServiceGetUploadsByIDsFuncCall{v0, v1, r0, r1})\n\treturn r0, r1\n}" ]
[ "0.8100934", "0.79997236", "0.7919966", "0.67751956", "0.6737591", "0.6716384", "0.66700727", "0.64469844", "0.6421894", "0.62926507", "0.6288443", "0.614765", "0.5920941", "0.5585824", "0.5475095", "0.54425955", "0.5382097", "0.5301088", "0.5294862", "0.5176188", "0.51289743", "0.51190025", "0.5097825", "0.50607044", "0.49863636", "0.49861476", "0.4976786", "0.49594185", "0.49509576", "0.49367857", "0.48744443", "0.48730922", "0.48563495", "0.48118123", "0.4782558", "0.47710624", "0.4764778", "0.47614318", "0.4760126", "0.47419825", "0.47264284", "0.47070095", "0.47018299", "0.46985188", "0.4684871", "0.46710885", "0.46667945", "0.46524453", "0.46524024", "0.46519125", "0.4642974", "0.4640618", "0.46397465", "0.46204215", "0.46094143", "0.4607804", "0.45923606", "0.4590722", "0.45795387", "0.45652258", "0.45648837", "0.45648706", "0.45602864", "0.455754", "0.45550576", "0.45376098", "0.4528312", "0.45276624", "0.45219713", "0.45087934", "0.4502369", "0.4485789", "0.44856766", "0.44807732", "0.44790477", "0.44733086", "0.44723734", "0.445984", "0.44560882", "0.44511473", "0.44488755", "0.44392917", "0.44374537", "0.4431899", "0.44290578", "0.44260547", "0.44229317", "0.4422877", "0.44162023", "0.44149742", "0.44010526", "0.43994245", "0.4393256", "0.4392611", "0.43911827", "0.4390067", "0.4381833", "0.43727905", "0.43661794", "0.43635353" ]
0.80914927
1
GetSubscriptions gets the subscriptions property value. The set of subscriptions on the list.
GetSubscriptions получает значение свойства subscriptions. Сет subscriptions на списке.
func (m *List) GetSubscriptions()([]Subscriptionable) { return m.subscriptions }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (svc *SubscriptionService) GetSubscriptions(params *param.GetParams) ([]*nimbleos.Subscription, error) {\n\tsubscriptionResp, err := svc.objectSet.GetObjectListFromParams(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn subscriptionResp, nil\n}", "func (c *Client) GetSubscriptions(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET SUBSCRIPTIONS ==========\")\n\turl := buildURL(path[\"subscriptions\"])\n\n\treturn c.do(\"GET\", url, \"\", queryParams)\n}", "func (p *PubsubValueStore) GetSubscriptions() []string {\n\tp.mx.Lock()\n\tdefer p.mx.Unlock()\n\n\tvar res []string\n\tfor sub := range p.topics {\n\t\tres = append(res, sub)\n\t}\n\n\treturn res\n}", "func (client *Client) Subscriptions() (*Subscriptions, error) {\n\tsubscriptions := new(Subscriptions)\n\tif err := client.apiGet(MARATHON_API_SUBSCRIPTION, nil, subscriptions); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn subscriptions, nil\n\t}\n}", "func (a Accessor) GetSubscriptionList(service, servicePath string, subscriptions *[]Subscription) error {\n\treturn a.access(&AccessParameter{\n\t\tEpID: EntryPointIDs.Subscriptions,\n\t\tMethod: gohttp.HttpMethods.GET,\n\t\tService: service,\n\t\tServicePath: servicePath,\n\t\tPath: \"\",\n\t\tReceivedBody: subscriptions,\n\t})\n}", "func (subscriptions *Subscriptions) Get() ([]*SubscriptionInfo, error) {\n\tclient := NewHTTPClient(subscriptions.client)\n\tresp, err := client.Get(subscriptions.endpoint, subscriptions.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata, _ := NormalizeODataCollection(resp)\n\tvar subs []*SubscriptionInfo\n\tif err := json.Unmarshal(data, &subs); err != nil {\n\t\treturn nil, err\n\t}\n\treturn subs, nil\n}", "func (k *Kraken) GetSubscriptions() ([]wshandler.WebsocketChannelSubscription, error) {\n\treturn k.Websocket.GetSubscriptions(), nil\n}", "func (m *SubscriptionManager) Subscriptions() graphqlws.Subscriptions {\n\treturn m.inner.Subscriptions()\n}", "func (r *SubscriptionsService) Get(subscription string) *SubscriptionsGetCall {\n\tc := &SubscriptionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.subscription = subscription\n\treturn c\n}", "func (client *ClientImpl) ListSubscriptions(ctx context.Context, args ListSubscriptionsArgs) (*[]Subscription, error) {\n\tqueryParams := url.Values{}\n\tif args.PublisherId != nil {\n\t\tqueryParams.Add(\"publisherId\", *args.PublisherId)\n\t}\n\tif args.EventType != nil {\n\t\tqueryParams.Add(\"eventType\", *args.EventType)\n\t}\n\tif args.ConsumerId != nil {\n\t\tqueryParams.Add(\"consumerId\", *args.ConsumerId)\n\t}\n\tif args.ConsumerActionId != nil {\n\t\tqueryParams.Add(\"consumerActionId\", *args.ConsumerActionId)\n\t}\n\tlocationId, _ := uuid.Parse(\"fc50d02a-849f-41fb-8af1-0a5216103269\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.1\", nil, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []Subscription\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (r *SubscriptionsService) List() *SubscriptionsListCall {\n\tc := &SubscriptionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}", "func (c *Client) Subscriptions() []string {\n\tresult := []string{}\n\tfor subscription, subscriber := range c.subscriptions {\n\t\tif subscriber != nil {\n\t\t\tresult = append(result, subscription)\n\t\t}\n\t}\n\treturn result\n}", "func (r *SubscriptionsService) List() *SubscriptionsListCall {\n\treturn &SubscriptionsListCall{\n\t\ts: r.s,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"subscriptions\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}", "func (m *GraphBaseServiceClient) Subscriptions()(*idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.SubscriptionsRequestBuilder) {\n return idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.NewSubscriptionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Subscriptions()(*idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.SubscriptionsRequestBuilder) {\n return idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.NewSubscriptionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (ss *SubscriptionsService) Get(ctx context.Context, cID, sID string) (res *Response, s *Subscription, err error) {\n\tu := fmt.Sprintf(\"v2/customers/%s/subscriptions/%s\", cID, sID)\n\n\tres, err = ss.client.get(ctx, u, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &s); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *T) Subscriptions() <-chan map[string][]string {\n\treturn s.subscriptionsCh\n}", "func getSubscriptions(request router.Request) (int, []byte) {\n\n\tquery := datastore.NewQuery(SUBSCRIPTION_KEY).Filter(\"Project =\", request.GetPathParams()[\"project_id\"])\n\tsubscriptions := make([]Subscription, 0)\n\t_, err := query.GetAll(request.GetContext(), &subscriptions)\n\n\tif err != nil {\n\t\tlog.Errorf(request.GetContext(), \"Error retriving Subscriptions: %v\", err)\n\t\treturn http.StatusInternalServerError, []byte(err.Error())\n\t}\n\n\tsubscriptionBytes, err := json.MarshalIndent(subscriptions, \"\", \"\t\")\n\n\tif err != nil {\n\t\tlog.Errorf(request.GetContext(), \"Error retriving Subscriptions: %v\", err)\n\t\treturn http.StatusInternalServerError, []byte(err.Error())\n\t}\n\n\treturn http.StatusOK, subscriptionBytes\n\n}", "func (m *List) SetSubscriptions(value []Subscriptionable)() {\n m.subscriptions = value\n}", "func (r *SubscriptionsService) Get(customerId string, subscriptionId string) *SubscriptionsGetCall {\n\treturn &SubscriptionsGetCall{\n\t\ts: r.s,\n\t\tcustomerId: customerId,\n\t\tsubscriptionId: subscriptionId,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"customers/{customerId}/subscriptions/{subscriptionId}\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}", "func GetChatSubscriptions(db *models.DatabaseConfig, chatID int64) ([]*models.Subscription, error) {\n\n\tif db == nil {\n\t\tlog.Println(\"The DB model is nil\")\n\t\treturn nil, errors.New(\"the DB model passed is nil, can't operate\")\n\t}\n\n\tcursor, err := db.MongoClient.Collection(\"subscription\").Find(db.Ctx, bson.M{\"chatid\": chatID})\n\tif err != nil {\n\t\tlog.Println(\"There was an error trying to look for this chat's subscriptions: \", err)\n\t\treturn nil, err\n\t}\n\n\tsubs := make([]*models.Subscription, 0)\n\terr = cursor.All(db.Ctx, &subs)\n\tif err != nil {\n\t\tlog.Println(\"There was an error trying to decode subscriptions into a subscriptions slice: \", err)\n\t\treturn nil, err\n\t}\n\n\treturn subs, nil\n}", "func (r *ProjectsLocationsDataExchangesService) ListSubscriptions(resource string) *ProjectsLocationsDataExchangesListSubscriptionsCall {\n\tc := &ProjectsLocationsDataExchangesListSubscriptionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\treturn c\n}", "func (s *API) ListSubscriptions(status SubscriptionStatus) (data SubscriptionsResponse, err error) {\n\tif status == \"\" {\n\t\tstatus = SubscriptionStatusAll\n\t}\n\tendpoint := zoho.Endpoint{\n\t\tName: \"subscriptions\",\n\t\tURL: fmt.Sprintf(\"https://subscriptions.zoho.%s/api/v1/subscriptions\", s.ZohoTLD),\n\t\tMethod: zoho.HTTPGet,\n\t\tResponseData: &SubscriptionsResponse{},\n\t\tURLParameters: map[string]zoho.Parameter{\n\t\t\t\"filter_by\": zoho.Parameter(status),\n\t\t},\n\t\tHeaders: map[string]string{\n\t\t\tZohoSubscriptionsEndpointHeader: s.OrganizationID,\n\t\t},\n\t}\n\n\terr = s.Zoho.HTTPRequest(&endpoint)\n\tif err != nil {\n\t\treturn SubscriptionsResponse{}, fmt.Errorf(\"Failed to retrieve subscriptions: %s\", err)\n\t}\n\n\tif v, ok := endpoint.ResponseData.(*SubscriptionsResponse); ok {\n\t\treturn *v, nil\n\t}\n\n\treturn SubscriptionsResponse{}, fmt.Errorf(\"Data retrieved was not 'SubscriptionsResponse'\")\n}", "func (r *ProjectsLocationsDataExchangesListingsService) ListSubscriptions(resource string) *ProjectsLocationsDataExchangesListingsListSubscriptionsCall {\n\tc := &ProjectsLocationsDataExchangesListingsListSubscriptionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\treturn c\n}", "func (w *AuthWorker) Subscriptions() []*worker.Subscription {\n\treturn make([]*worker.Subscription, 0)\n}", "func (m *MockSession) GetSubscriptions() []*nats.Subscription {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\")\n\tret0, _ := ret[0].([]*nats.Subscription)\n\treturn ret0\n}", "func (c *Client) ListSubscriptions(namespace string) (*v1alpha1.SubscriptionList, error) {\n\tif err := c.initClient(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubscriptionList := &v1alpha1.SubscriptionList{}\n\tif err := c.crClient.List(\n\t\tcontext.TODO(),\n\t\tsubscriptionList,\n\t\t&client.ListOptions{\n\t\t\tNamespace: namespace,\n\t\t},\n\t); err != nil {\n\t\treturn subscriptionList, err\n\t}\n\treturn subscriptionList, nil\n}", "func (c *conn) Subscriptions() map[int]*Subscription {\n\treturn c.subcriptions\n}", "func (client NotificationDataPlaneClient) ListSubscriptions(ctx context.Context, request ListSubscriptionsRequest) (response ListSubscriptionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listSubscriptions, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tresponse = ListSubscriptionsResponse{RawResponse: ociResponse.HTTPResponse()}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListSubscriptionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListSubscriptionsResponse\")\n\t}\n\treturn\n}", "func ListSubscriptions(db bun.IDB, offset, limit uint32) ([]*domain.Subscription, error) {\n\tmodel := []Subscription{}\n\n\tif err := db.NewSelect().Model(&model).Scan(context.Background()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := []*domain.Subscription{}\n\n\tfor _, subscription := range model {\n\t\tres = append(res, &domain.Subscription{\n\t\t\tPK: subscription.PK,\n\t\t\tSubscriberPK: subscription.SubscriberPK,\n\t\t\tListPK: subscription.ListPK,\n\t\t\tEmailAddress: domain.EmailAddress(subscription.EmailAddress),\n\t\t\tData: subscription.Data,\n\t\t\tVersion: subscription.Version,\n\t\t})\n\t}\n\n\treturn res, nil\n}", "func (c *Client) Subscriptions(ctx context.Context) *SubscriptionIterator {\n\treturn &SubscriptionIterator{c.Client.Subscriptions(ctx), c.projectID, c.sensor}\n}", "func (o UserDefinedResourcesPropertiesResponseOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v UserDefinedResourcesPropertiesResponse) []string { return v.QuerySubscriptions }).(pulumi.StringArrayOutput)\n}", "func (o GetTopicSubscriptionsResultOutput) Subscriptions() GetTopicSubscriptionsSubscriptionArrayOutput {\n\treturn o.ApplyT(func(v GetTopicSubscriptionsResult) []GetTopicSubscriptionsSubscription { return v.Subscriptions }).(GetTopicSubscriptionsSubscriptionArrayOutput)\n}", "func (o UserDefinedResourcesPropertiesOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v UserDefinedResourcesProperties) []string { return v.QuerySubscriptions }).(pulumi.StringArrayOutput)\n}", "func (sns *SNS) ListSubscriptions(NextToken *string) (resp *ListSubscriptionsResp, err error) {\n\tresp = &ListSubscriptionsResp{}\n\tparams := makeParams(\"ListSubscriptions\")\n\tif NextToken != nil {\n\t\tparams[\"NextToken\"] = *NextToken\n\t}\n\terr = sns.query(params, resp)\n\treturn\n}", "func (c *consulCoordinator) GetSubscribers(topic StreamID) ([]string, error) {\n\ttags := ParseTags(topic)\n\tlog.Println(\"Publisher tags:\", tags, topic)\n\ttopic = StripTags(topic)\n\tprefix := fmt.Sprintf(\"dagger/subscribers/%s/\", topic)\n\n\tc.subscribersLock.RLock()\n\tsubsList := c.subscribers[prefix]\n\tc.subscribersLock.RUnlock()\n\tif subsList == nil {\n\t\tc.subscribersLock.Lock()\n\t\tsubsList = c.subscribers[prefix]\n\t\t// check again, otherwise someone might have already acquired write lock before us\n\t\tif subsList == nil {\n\t\t\tsubsList = &subscribersList{prefix: prefix, tags: tags, c: c}\n\t\t\terr := subsList.fetch()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.subscribers[prefix] = subsList\n\t\t\t// keep subscribers updated and clean up if unused\n\t\t\tgo subsList.sync()\n\t\t}\n\t\tc.subscribersLock.Unlock()\n\t}\n\treturn subsList.get(), nil\n}", "func (_m *DBClient) GetSubscriptions() ([]models.Subscription, error) {\n\tret := _m.Called()\n\n\tvar r0 []models.Subscription\n\tif rf, ok := ret.Get(0).(func() []models.Subscription); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]models.Subscription)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (s *MemoryStore) Subscriptions() []subscription.Subscription {\n\ts.subsMux.RLock()\n\tdefer s.subsMux.RUnlock()\n\n\tsubs := make([]subscription.Subscription, 0, len(s.subscriptions))\n\tfor _, sub := range s.subscriptions {\n\t\tsubs = append(subs, sub)\n\t}\n\treturn subs\n}", "func (d *DatastoreSubscription) List() ([]*Subscription, error) {\n\treturn d.collectByField(func(s *Subscription) bool {\n\t\treturn true\n\t})\n}", "func (c *Contributor) GetSubscriptionsURL() string {\n\tif c == nil || c.SubscriptionsURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *c.SubscriptionsURL\n}", "func (c *Client) Subscriptions() map[string]*Subscription {\n\tsubs := make(map[string]*Subscription)\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tfor k, v := range c.subs {\n\t\tsubs[k] = v\n\t}\n\treturn subs\n}", "func (u *UserLDAPMapping) GetSubscriptionsURL() string {\n\tif u == nil || u.SubscriptionsURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *u.SubscriptionsURL\n}", "func (pager *SubscriptionsPager) GetAll() (allItems []SubscriptionListItem, err error) {\n\treturn pager.GetAllWithContext(context.Background())\n}", "func (ss *SubscriptionsService) List(ctx context.Context, cID string, opts *SubscriptionListOptions) (\n\tres *Response,\n\tsl *SubscriptionList,\n\terr error,\n) {\n\tu := fmt.Sprintf(\"v2/customers/%s/subscriptions\", cID)\n\n\tres, err = ss.list(ctx, u, opts)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &sl); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *DefaultApiService) ListSubscription(params *ListSubscriptionParams) (*ListSubscriptionResponse, error) {\n\tpath := \"/v1/Subscriptions\"\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.SinkSid != nil {\n\t\tdata.Set(\"SinkSid\", *params.SinkSid)\n\t}\n\tif params != nil && params.PageSize != nil {\n\t\tdata.Set(\"PageSize\", fmt.Sprint(*params.PageSize))\n\t}\n\n\tresp, err := c.requestHandler.Get(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &ListSubscriptionResponse{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (m *MockDB) GetSubscriptions(address, network string) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\", address, network)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (o UserDefinedResourcesPropertiesResponsePtrOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *UserDefinedResourcesPropertiesResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QuerySubscriptions\n\t}).(pulumi.StringArrayOutput)\n}", "func (s *Subscription) GetSubscribed() bool {\n\tif s == nil || s.Subscribed == nil {\n\t\treturn false\n\t}\n\treturn *s.Subscribed\n}", "func (prefs *UserPreferences) ChannelSubscriptions() ([]string, error) {\n\tvar subs []string\n\tif prefs.ChannelSubs != nil {\n\t\tif err := json.Unmarshal(prefs.ChannelSubs, &subs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn subs, nil\n}", "func (u *User) GetSubscriptionsURL() string {\n\tif u == nil || u.SubscriptionsURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *u.SubscriptionsURL\n}", "func (o UserDefinedResourcesPropertiesPtrOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *UserDefinedResourcesProperties) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QuerySubscriptions\n\t}).(pulumi.StringArrayOutput)\n}", "func (client NotificationDataPlaneClient) listSubscriptions(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/subscriptions\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListSubscriptionsResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func getOutlookSubscriptions(outlookClient *http.Client) (SubscriptionsWrapper, error) {\n\tfullUrl := fmt.Sprintf(\"https://graph.microsoft.com/v1.0/subscriptions\")\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfullUrl,\n\t\tnil,\n\t)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tres, err := outlookClient.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"suberror Client: %s\", err)\n\t\treturn SubscriptionsWrapper{}, err\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Suberror Body: %s\", err)\n\t\treturn SubscriptionsWrapper{}, err\n\t}\n\n\tnewSubs := SubscriptionsWrapper{}\n\terr = json.Unmarshal(body, &newSubs)\n\tif err != nil {\n\t\treturn SubscriptionsWrapper{}, err\n\t}\n\n\treturn newSubs, nil\n}", "func (s *Simple) Subscriptions() []plugin.Subscription {\n\treturn []plugin.Subscription{\n\t\tplugin.Subscription{\n\t\t\tEventType: event.SystemEventReceivedType,\n\t\t\tType: plugin.Sync,\n\t\t},\n\t}\n}", "func (eventNotifications *EventNotificationsV1) ListSubscriptions(listSubscriptionsOptions *ListSubscriptionsOptions) (result *SubscriptionList, response *core.DetailedResponse, err error) {\n\treturn eventNotifications.ListSubscriptionsWithContext(context.Background(), listSubscriptionsOptions)\n}", "func (mr *MockSessionMockRecorder) GetSubscriptions() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetSubscriptions\", reflect.TypeOf((*MockSession)(nil).GetSubscriptions))\n}", "func (tm *topicManager) SubscribedList() []string {\n\ttm.locker.RLock()\n\tlist := make([]string, 0, len(tm.allTopics))\n\tfor name := range tm.allTopics {\n\t\tlist = append(list, name)\n\t}\n\ttm.locker.RUnlock()\n\treturn list\n}", "func (a *StreamsApiService) GetSubscriptionsExecute(r ApiGetSubscriptionsRequest) (JsonSuccessBase, *_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 JsonSuccessBase\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"StreamsApiService.GetSubscriptions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/users/me/subscriptions\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.includeSubscribers != nil {\n\t\tlocalVarQueryParams.Add(\"include_subscribers\", parameterToString(*r.includeSubscribers, \"\"))\n\t}\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\treq, err := a.client.prepareRequest(r.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(req)\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\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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 (p *Proxy) List() (data [][]string) {\n\tlumber.Trace(\"Proxy listing subscriptions...\")\n\tp.RLock()\n\tdata = p.subscriptions.ToSlice()\n\tp.RUnlock()\n\n\treturn\n}", "func (s *server) ListTopicSubscriptions(ctx context.Context, in *empty.Empty) (*pb.ListTopicSubscriptionsResponse, error) {\n\treturn &pb.ListTopicSubscriptionsResponse{\n\t\tSubscriptions: []*pb.TopicSubscription{\n\t\t\t{Topic: \"TopicA\"},\n\t\t},\n\t}, nil\n}", "func (m *MockISubscription) GetSubscriptions(address, network string) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\", address, network)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetSubscription(ctx context.Context, client k8sclient.Client, installation *integreatlyv1alpha1.RHMI) (*operatorsv1alpha1.Subscription, error) {\n\tfor subscriptionName := range runTypesBySubscription {\n\t\tsubscription := &operatorsv1alpha1.Subscription{}\n\t\terr := client.Get(ctx, k8sclient.ObjectKey{\n\t\t\tName: subscriptionName,\n\t\t\tNamespace: installation.Namespace,\n\t\t}, subscription)\n\t\tif err != nil && errors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn subscription, nil\n\t}\n\n\t// If subscription is not found, it could be because the CPaaS CVP build has put a non deterministic name on it.\n\t// This code may be temporary if CPaaS changes to deterministic Subscription names\n\tsubscription, err := GetRhoamCPaaSSubscription(ctx, client, installation.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif subscription != nil {\n\t\treturn subscription, nil\n\t}\n\n\treturn nil, nil\n}", "func getNodeSubscriptions(ctx echo.Context) error {\n\tglog.Infof(\"calling getNodeSubscriptions from %s\", ctx.Request().RemoteAddr)\n\n\tnodeName := ctx.Param(\"nodeName\")\n\tif nodeName == \"\" {\n\t\treturn ctx.JSON(http.StatusBadRequest,\n\t\t\t&response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: \"Invalid parameter\",\n\t\t\t})\n\t}\n\n\tconfig := ctx.(*apiContext).config\n\thosts := config.MustString(\"condutor\", \"mongo\")\n\tsession, err := mgo.Dial(hosts)\n\tif err != nil {\n\t\tglog.Errorf(\"getNodeSubscriptions:%v\", err)\n\t\treturn ctx.JSON(http.StatusInternalServerError,\n\t\t\t&response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t}\n\tc := session.DB(\"iothub\").C(\"subscriptions\")\n\tdefer session.Close()\n\n\tsubs := []collector.Subscription{}\n\tif err := c.Find(bson.M{\"NodeName\": nodeName}).Limit(100).Iter().All(&subs); err != nil {\n\t\tglog.Errorf(\"getNodeSubscriptions:%v\", err)\n\t\treturn ctx.JSON(http.StatusNotFound,\n\t\t\t&response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t}\n\treturn ctx.JSON(http.StatusOK, &response{\n\t\tSuccess: true,\n\t\tResult: subs,\n\t})\n}", "func (a *Accessor) GetSubscription(service, servicePath, id string, subscription *Subscription) error {\n\treturn a.access(&AccessParameter{\n\t\tEpID: EntryPointIDs.Subscriptions,\n\t\tMethod: gohttp.HttpMethods.GET,\n\t\tService: service,\n\t\tServicePath: servicePath,\n\t\tPath: fmt.Sprintf(\"/%s\", id),\n\t\tReceivedBody: subscription,\n\t})\n}", "func (eventNotifications *EventNotificationsV1) GetSubscription(getSubscriptionOptions *GetSubscriptionOptions) (result *Subscription, response *core.DetailedResponse, err error) {\n\treturn eventNotifications.GetSubscriptionWithContext(context.Background(), getSubscriptionOptions)\n}", "func GetSubscription(db bun.IDB, listPK, pk uuid.UUID) (*domain.Subscription, error) {\n\tmodel := Subscription{\n\t\tPK: pk,\n\t\tListPK: listPK,\n\t}\n\n\tif err := db.NewSelect().Model(&model).WherePK().Scan(context.Background()); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &domain.Subscription{\n\t\tPK: model.PK,\n\t\tEmailAddress: domain.EmailAddress(model.EmailAddress),\n\t\tVersion: model.Version,\n\t}, nil\n}", "func (r *reconciler) getSubscription(ctx context.Context, t *v1alpha1.Trigger) (*v1alpha1.Subscription, error) {\n\tlist := &v1alpha1.SubscriptionList{}\n\topts := &runtimeclient.ListOptions{\n\t\tNamespace: t.Namespace,\n\t\tLabelSelector: labels.SelectorFromSet(resources.SubscriptionLabels(t)),\n\t\t// Set Raw because if we need to get more than one page, then we will put the continue token\n\t\t// into opts.Raw.Continue.\n\t\tRaw: &metav1.ListOptions{},\n\t}\n\n\terr := r.client.List(ctx, opts, list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, s := range list.Items {\n\t\tif metav1.IsControlledBy(&s, t) {\n\t\t\treturn &s, nil\n\t\t}\n\t}\n\n\treturn nil, k8serrors.NewNotFound(schema.GroupResource{}, \"\")\n}", "func (r *ProjectsLocationsSubscriptionsService) Get(name string) *ProjectsLocationsSubscriptionsGetCall {\n\tc := &ProjectsLocationsSubscriptionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *PublisherClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest) *StringIterator {\n\tctx = metadata.NewContext(ctx, c.metadata)\n\tit := &StringIterator{}\n\tit.apiCall = func() error {\n\t\tvar resp *pubsubpb.ListTopicSubscriptionsResponse\n\t\terr := gax.Invoke(ctx, func(ctx context.Context) error {\n\t\t\tvar err error\n\t\t\treq.PageToken = it.nextPageToken\n\t\t\treq.PageSize = it.pageSize\n\t\t\tresp, err = c.client.ListTopicSubscriptions(ctx, req)\n\t\t\treturn err\n\t\t}, c.CallOptions.ListTopicSubscriptions...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif resp.NextPageToken == \"\" {\n\t\t\tit.atLastPage = true\n\t\t}\n\t\tit.nextPageToken = resp.NextPageToken\n\t\tit.items = resp.Subscriptions\n\t\treturn nil\n\t}\n\treturn it\n}", "func (client BaseClient) GetSubscription(ctx context.Context, subscriptionID uuid.UUID, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.GetSubscription\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetSubscriptionPreparer(ctx, subscriptionID, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscription\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetSubscriptionSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscription\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetSubscriptionResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscription\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (a *App) getSubscribersOnline(w http.ResponseWriter, r *http.Request) {\n\n\tsubs, err := models.GetSubscribersOnline(a.jsonrpcHTTPAddr, a.httpClient)\n\tif err != nil {\n\t\trespond.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\trespond.JSON(w, http.StatusOK, subs)\n\treturn\n}", "func (r *SubscriptionRepository) Get(id string) (*domain.Subscription, error) {\n\ts, err := r.applyOperation(func() (interface{}, error) {\n\t\treturn r.get(id)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ToDomain(s.(*Subscription)), err\n}", "func (m *UserResource) ListUserSubscriptions(ctx context.Context, userId string) ([]*Subscription, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/subscriptions\", userId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar subscription []*Subscription\n\n\tresp, err := rq.Do(ctx, req, &subscription)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn subscription, resp, nil\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 (subscription *Subscription) Get() (*SubscriptionInfo, error) {\n\tclient := NewHTTPClient(subscription.client)\n\tresp, err := client.Get(subscription.endpoint, subscription.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn subscription.parseResponse(resp)\n}", "func (c *Client) GetSubscription(subscriptionID string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET SUBSCRIPTION ==========\")\n\turl := buildURL(path[\"subscriptions\"], subscriptionID)\n\n\treturn c.do(\"GET\", url, \"\", nil)\n}", "func (session Session) GetWebhooks() (result []SubscriptionInfo, err error) {\n\treq, err := getWebhooksSubscriptions(nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsession.addTokenAuth(req)\n\tres, err := session.client.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"Error while executing GetWebhooks request: %s\", err)\n\t\treturn\n\t}\n\n\tif res.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Request returned: %d\", res.StatusCode)\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading response body: %s\", err)\n\t\treturn\n\t}\n\n\tvar d dataResult\n\tif err = json.Unmarshal(body, &d); err != nil {\n\t\tlog.Printf(\"Error while parsing response body: %s\", err)\n\t\tlog.Printf(\"Body: %s\", body)\n\t\treturn\n\t}\n\n\tfor _, inner := range d.Data {\n\t\tvar sub SubscriptionInfo\n\t\tif err = json.Unmarshal(inner, &sub); err != nil {\n\t\t\tlog.Printf(\"Error while parsing internal JSON: %s\", err)\n\t\t\tlog.Printf(\"Invalid JSON: %s\", inner)\n\t\t\terr = nil\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, sub)\n\t}\n\n\treturn\n}", "func (e *FbEvent) Subscribers() []*Subscription {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\treturn e.subscribers[:]\n}", "func (col *CCPrinterSubscriptionCollection) GetPrinterSubscriptions(ctx context.Context, printerId string) ([]*CCPrinterSubscriptionModel, error) {\n\n\tqueryInput := &dynamodb.QueryInput{\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\":printerId\": {\n\t\t\t\tS: aws.String(printerId),\n\t\t\t},\n\t\t},\n\t\tKeyConditionExpression: aws.String(\"PrinterID = :printerId\"),\n\t\tTableName: aws.String(col.tableName),\n\t}\n\n\tresult, err := col.QueryWithContext(ctx, queryInput)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(result.Items) == 0 {\n\t\treturn nil, NotFoundErr\n\t}\n\n\tvar subscriptionsArr []*CCPrinterSubscriptionModel\n\n\tfor _, item := range result.Items {\n\t\tsubscription := CCPrinterSubscriptionModel{}\n\t\terr := dynamodbattribute.UnmarshalMap(item, &subscription)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsubscriptionsArr = append(subscriptionsArr, &subscription)\n\t}\n\n\treturn subscriptionsArr, nil\n}", "func getSubscribers() (subs []common.SubscriberEntry, retErr error) {\n\n\tvar subList []common.SubscriberEntry\n\n\t// Creazione DynamoDB client\n\tsvc := dynamodb.New(common.Sess)\n\n\t// Determino l'input della query\n\tinput := &dynamodb.ScanInput{\n\t\tTableName: aws.String(subTableName),\n\t}\n\n\t// Effettuo la query\n\tresult, err := svc.Scan(input)\n\tif err != nil {\n\t\tcommon.Fatal(\"[BROKER] Errore nell'esecuzione della Query\\n\" + err.Error())\n\t\treturn nil, err\n\t}\n\n\tfor _, r := range result.Items {\n\n\t\tvar subID = common.SubscriberEntry{}\n\n\t\t// Unmarshaling del dato ottenuto\n\t\terr = dynamodbattribute.UnmarshalMap(r, &subID)\n\t\tif err != nil {\n\t\t\tcommon.Fatal(\"Errore nell'unmarshaling della entry\\n\" + err.Error())\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsubList = append(subList, subID)\n\n\t}\n\n\n\treturn subList, nil\n\n}", "func (s *subscriberdbServicer) ListSubscribers(ctx context.Context, req *lte_protos.ListSubscribersRequest) (*lte_protos.ListSubscribersResponse, error) {\n\tgateway := protos.GetClientGateway(ctx)\n\tif gateway == nil {\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"missing gateway identity\")\n\t}\n\tif !gateway.Registered() {\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"gateway is not registered\")\n\t}\n\tnetworkID := gateway.NetworkId\n\n\tapnsByName, apnResourcesByAPN, err := loadAPNs(gateway)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsubProtos, nextToken, err := subscriberdb.LoadSubProtosPage(req.PageSize, req.PageToken, networkID, apnsByName, apnResourcesByAPN)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflatDigest := &lte_protos.Digest{Md5Base64Digest: \"\"}\n\tperSubDigests := []*lte_protos.SubscriberDigestWithID{}\n\t// The digests are sent back during the request for the first page of subscriber data\n\tif req.PageToken == \"\" {\n\t\tflatDigest, _ = s.getDigestInfo(&lte_protos.Digest{Md5Base64Digest: \"\"}, networkID)\n\t\tperSubDigests, err = s.perSubDigestStore.GetDigest(networkID)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to get per-sub digests from store for network %+v: %+v\", networkID, err)\n\t\t}\n\t}\n\n\tlistRes := &lte_protos.ListSubscribersResponse{\n\t\tSubscribers: subProtos,\n\t\tNextPageToken: nextToken,\n\t\tFlatDigest: flatDigest,\n\t\tPerSubDigests: perSubDigests,\n\t}\n\treturn listRes, nil\n}", "func (psc *PubSubChannel) NumSubscriptions() int {\n psc.subsMutex.RLock()\n defer psc.subsMutex.RUnlock()\n return len(psc.subscriptions)\n}", "func (m *consulMetadataReport) GetSubscribedURLs(subscriberMetadataIdentifier *identifier.SubscriberMetadataIdentifier) ([]string, error) {\n\tk := subscriberMetadataIdentifier.GetIdentifierKey()\n\tkv, _, err := m.client.KV().Get(k, nil)\n\tif err != nil || kv == nil {\n\t\treturn emptyStrSlice, err\n\t}\n\treturn []string{string(kv.Value)}, nil\n}", "func (h *Handler) ActiveSubscriptions() int {\n\treturn h.subCancellations.Len()\n}", "func (a *AmsiApiService) SubGET(ctx context.Context, subscriptionType string) (SubscriptionLinkList, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SubscriptionLinkList\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/subscriptions\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tlocalVarQueryParams.Add(\"subscriptionType\", parameterToString(subscriptionType, \"\"))\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, 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\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v SubscriptionLinkList\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 406 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (client BaseClient) GetSubscriptionOperations(ctx context.Context, subscriptionID uuid.UUID, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.GetSubscriptionOperations\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetSubscriptionOperationsPreparer(ctx, subscriptionID, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscriptionOperations\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetSubscriptionOperationsSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscriptionOperations\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetSubscriptionOperationsResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscriptionOperations\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (s *subscription) Topics() []string {\n\treturn s.topics\n}", "func (client IdentityClient) ListRegionSubscriptions(ctx context.Context, request ListRegionSubscriptionsRequest) (response ListRegionSubscriptionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listRegionSubscriptions, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListRegionSubscriptionsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListRegionSubscriptionsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListRegionSubscriptionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListRegionSubscriptionsResponse\")\n\t}\n\treturn\n}", "func (st *SubTree)GetSubscribers(topic string)([]*Subscriber,error){\n\ttopicArray,err := PubTopicCheckAndSpilt(topic)\n\tif err!=nil{\n\t\treturn nil,err\n\t}\n\tst.lock.Lock()\n\tdefer st.lock.Unlock()\n\tsubers:=make([]*Subscriber,0)\n\tcurrentLevel :=st.root\n\tif len(topicArray)>0{\n\t\tif topicArray[0] == \"/\" {\n\t\t\tif _, exist := currentLevel.nodes[\"#\"]; exist {\n\t\t\t\tsubers = append(subers,currentLevel.nodes[\"#\"].subList...)\n\t\t\t}\n\t\t\tif _, exist := currentLevel.nodes[\"+\"]; exist {\n\t\t\t\tmatchLevel(currentLevel.nodes[\"/\"].children, topicArray[1:], &subers)\n\t\t\t}\n\t\t\tif _, exist := currentLevel.nodes[\"/\"]; exist {\n\t\t\t\tmatchLevel(currentLevel.nodes[\"/\"].children, topicArray[1:], &subers)\n\t\t\t}\n\t\t} else {\n\t\t\tmatchLevel(st.root, topicArray, &subers)\n\t\t}\n\t}\n\treturn subers,nil\n }", "func (mr *MockDBMockRecorder) GetSubscriptions(address, network interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetSubscriptions\", reflect.TypeOf((*MockDB)(nil).GetSubscriptions), address, network)\n}", "func (m *MockDB) ListSubscriptions(userID uint) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListSubscriptions\", userID)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (ss *SubscriptionsService) All(ctx context.Context, opts *SubscriptionListOptions) (\n\tres *Response,\n\tsl *SubscriptionList,\n\terr error,\n) {\n\tu := \"v2/subscriptions\"\n\n\tres, err = ss.list(ctx, u, opts)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &sl); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func getSubscribersID() (subsID []string, retErr error) {\n\n\tvar subList []string\n\n\t// Creazione DynamoDB client\n\tsvc := dynamodb.New(common.Sess)\n\n\t// Determino l'input della query\n\tinput := &dynamodb.ScanInput{\n\t\tTableName: aws.String(subTableName),\n\t}\n\n\t// Effettuo la query\n\tresult, err := svc.Scan(input)\n\tif err != nil {\n\t\tcommon.Fatal(\"[BROKER] Errore nell'esecuzione della Query\\n\" + err.Error())\n\t\treturn nil, err\n\t}\n\n\tfor _, r := range result.Items {\n\n\t\tvar subID = common.SubscriberEntry{}\n\n\t\t// Unmarshaling del dato ottenuto\n\t\terr = dynamodbattribute.UnmarshalMap(r, &subID)\n\t\tif err != nil {\n\t\t\tcommon.Fatal(\"Errore nell'unmarshaling della entry\\n\" + err.Error())\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsubList = append(subList, subID.SubID)\n\n\t}\n\n\n\treturn subList, nil\n\n}", "func NewWeaveSubscriptionsGet(ctx *middleware.Context, handler WeaveSubscriptionsGetHandler) *WeaveSubscriptionsGet {\n\treturn &WeaveSubscriptionsGet{Context: ctx, Handler: handler}\n}", "func (o *ClusterAuthorizationResponse) GetSubscription() ObjectReference {\n\tif o == nil || o.Subscription == nil {\n\t\tvar ret ObjectReference\n\t\treturn ret\n\t}\n\treturn *o.Subscription\n}", "func getSubs(mapper *gosubscribe.Mapper) []*gosubscribe.User {\n\tusers := []*gosubscribe.User{}\n\tsubs := []gosubscribe.Subscription{}\n\tgosubscribe.DB.Table(\"subscriptions\").Where(\"mapper_id = ?\", mapper.ID).Find(&subs)\n\tfor _, sub := range subs {\n\t\tuser, err := gosubscribe.GetUser(sub.UserID)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"No user found for %d\\n\", sub.UserID)\n\t\t} else {\n\t\t\tusers = append(users, user)\n\t\t}\n\t}\n\tlog.Printf(\"Retrieved %d subscriber(s) for %s\\n\", len(users), mapper.Username)\n\treturn users\n}", "func (repo *feedRepository) GetChannels(f *feed.Feed, sortBy string, sortOrder string) ([]*feed.Channel, error) {\n\tchannelSubscriptions := make([]*feed.Channel, 0)\n\trows, err := repo.db.Query(fmt.Sprintf(`\n\t\tSELECT username, name, subscription_time\n\t\tFROM (\n\t\t\t(\n\t\t\t\tSELECT channel_username, subscription_time\n\t\t\t\tFROM feed_subscriptions\n\t\t\t\tWHERE feed_id = $1\n\t\t\t) AS S (username, subscription_time)\n\t\t\tNATURAL JOIN\n\t\t\tchannels\n\t\t)\n\t\tORDER BY %s %s NULLS LAST`, sortBy, sortOrder), f.ID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"querying for feed_subscriptions failed because of: %s\", err.Error())\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tc := new(feed.Channel)\n\t\terr := rows.Scan(&c.Channelname, &c.Name, &c.SubscriptionTime)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"scanning from rows failed because: %s\", err.Error())\n\t\t}\n\t\tchannelSubscriptions = append(channelSubscriptions, c)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"scanning from rows faulty because: %s\", err.Error())\n\t}\n\treturn channelSubscriptions, nil\n}", "func GetSubscribers() (Items, error) {\n\tvar response Response\n\t//nuova GET con query params\n\treq, err := http.NewRequest(\"GET\", \"https://www.googleapis.com/youtube/v3/channels\", nil)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn Items{}, err\n\t}\n\n\t//da qui definiamo i query param\n\tqueryparam := req.URL.Query()\n\tqueryparam.Add(\"key\", os.Getenv(\"YOUTUBE_KEY\"))\n\tqueryparam.Add(\"id\", os.Getenv(\"CHANNEL_ID\"))\n\tqueryparam.Add(\"part\", \"statistics\")\n\t//prearo il nuovo URL\n\treq.URL.RawQuery = queryparam.Encode()\n\n\t//eseguiamo la request con tutti i parametri\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tfmt.Println(\"ERRORE NELLA CHIAMATA: \", err)\n\t\treturn Items{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"Response Status: \", resp.Status)\n\t//se arriviamo qui è perchè abbiamo ottenuto un 200\n\t//leggo l'ogggetto arrivato\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\t//alla fine unmarshal del risultato dentro nostra struct\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn Items{}, err\n\t}\n\n\t//mandiamo indietro solo il primo elemento\n\treturn response.Items[0], nil\n}", "func (o *GetSubscriptionsParams) WithPageSize(pageSize *int32) *GetSubscriptionsParams {\n\to.SetPageSize(pageSize)\n\treturn o\n}", "func (m *GraphBaseServiceClient) SubscriptionsById(id string)(*if405c95e51d6685837bc60276ac44a0be46f00a5930cc59ce198c3a5119099a0.SubscriptionItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"subscription%2Did\"] = id\n }\n return if405c95e51d6685837bc60276ac44a0be46f00a5930cc59ce198c3a5119099a0.NewSubscriptionItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}" ]
[ "0.7868426", "0.7729767", "0.7729074", "0.7635478", "0.75740594", "0.74823356", "0.7409729", "0.7403774", "0.7206823", "0.71313256", "0.7025433", "0.7023735", "0.69475216", "0.6929064", "0.6929064", "0.69113976", "0.6910021", "0.68576664", "0.6846115", "0.6791046", "0.6753372", "0.6744555", "0.67294186", "0.67060715", "0.6703233", "0.66073", "0.6584021", "0.65816045", "0.65784806", "0.6565604", "0.65477335", "0.6515876", "0.64940774", "0.648313", "0.6451298", "0.64440703", "0.64429635", "0.64191985", "0.6387902", "0.6387561", "0.6373621", "0.63700235", "0.6345708", "0.6325786", "0.63249373", "0.63153166", "0.6286452", "0.6271136", "0.6266406", "0.6265164", "0.6222942", "0.6222374", "0.61291796", "0.61238354", "0.6121104", "0.6109342", "0.6089806", "0.60471576", "0.60407335", "0.60140955", "0.59885275", "0.5972139", "0.59587497", "0.59586036", "0.5957837", "0.59341586", "0.5925849", "0.5914213", "0.5891211", "0.5870116", "0.586186", "0.5818522", "0.5814893", "0.5809699", "0.5807262", "0.5805765", "0.579935", "0.5787223", "0.57867837", "0.57575595", "0.57098293", "0.5707426", "0.5673956", "0.5672702", "0.5661634", "0.5652127", "0.5645628", "0.56442785", "0.5616718", "0.5609315", "0.5605694", "0.5594208", "0.5580893", "0.55723304", "0.5560775", "0.5557863", "0.5545962", "0.55378246", "0.55335814", "0.5530565" ]
0.8141
0
SetColumns sets the columns property value. The collection of field definitions for this list.
SetColumns задает значение свойства columns. Коллекция определений полей для этого списка.
func (m *List) SetColumns(value []ColumnDefinitionable)() { m.columns = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Creater) SetColumns(c1 []builder.Columns) builder.Creater {\n\n\tcolumnDefs := make([]string, 0, len(c1))\n\n\tfor _, item := range c1 {\n\t\tcolumnDefs = append(columnDefs, fmt.Sprintf(\"%s %s %s\", item.Name, item.Datatype, item.Constraint))\n\t}\n\n\tcolumns := strings.Join(columnDefs, seperator)\n\tc.sql.WriteString(fmt.Sprintf(\"%s %s %s\", \"(\", columns, \");\"))\n\n\treturn c\n}", "func (t *Table) SetColumns(columns []string) *Table {\n\tt.Clear(true)\n\tif t.showIndex {\n\t\tcolumns = append([]string{\"#\"}, columns...)\n\t\tif len(columns) >= 2 {\n\t\t\tt.sortCol = 1\n\t\t\tt.sortType = SortAsc\n\t\t}\n\t} else {\n\t\tif len(columns) >= 1 {\n\t\t\tt.sortCol = 0\n\t\t\tt.sortType = SortAsc\n\t\t}\n\t}\n\tfor i := 0; i < len(columns); i++ {\n\t\tcell := cview.NewTableCell(columns[i])\n\t\tif t.addCellFunc != nil {\n\t\t\tt.addCellFunc(cell, true, 0)\n\t\t}\n\t\tt.Table.SetCell(0, i, cell)\n\t}\n\tt.columns = columns\n\treturn t\n}", "func (o *InlineResponse20075Stats) SetColumns(v InlineResponse20075StatsColumns) {\n\to.Columns = &v\n}", "func SetColumns(names []string) {\n\tvar (\n\t\tn int\n\t\tcurColStr = ColumnsString()\n\t\tnewColumns = make([]*Column, len(GlobalColumns))\n\t)\n\n\tlock.Lock()\n\n\t// add enabled columns by name\n\tfor _, name := range names {\n\t\tnewColumns[n] = popColumn(name)\n\t\tnewColumns[n].Enabled = true\n\t\tn++\n\t}\n\n\t// extend with omitted columns as disabled\n\tfor _, col := range GlobalColumns {\n\t\tnewColumns[n] = col\n\t\tnewColumns[n].Enabled = false\n\t\tn++\n\t}\n\n\tGlobalColumns = newColumns\n\tlock.Unlock()\n\n\tlog.Noticef(\"config change [columns]: %s -> %s\", curColStr, ColumnsString())\n}", "func (o *TelemetryDruidScanRequestAllOf) SetColumns(v []string) {\n\to.Columns = v\n}", "func (o *SummaryResponse) SetColumns(v SummaryColumnResponse) {\n\to.Columns = &v\n}", "func (v *IconView) SetColumns(columns int) {\n\tC.gtk_icon_view_set_columns(v.native(), C.gint(columns))\n}", "func (s *Session) Columns(columns ...string) *Session {\n\ts.initStatemnt()\n\ts.statement.Columns(columns...)\n\treturn s\n}", "func (b *Blueprint) Set(column string, allowed []string) *ColumnDefinition {\n\treturn b.addColumn(\"set\", column, &ColumnOptions{\n\t\tAllowed: allowed,\n\t})\n}", "func (ts *STableSpec) Columns() []IColumnSpec {\n\tif ts._columns == nil {\n\t\tval := reflect.Indirect(reflect.New(ts.structType))\n\t\tts.struct2TableSpec(val)\n\t}\n\treturn ts._columns\n}", "func (v *nicerButSlowerFilmListViewType) Columns() []string {\n\treturn []string{\n\t\t\"FID\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"category\",\n\t\t\"price\",\n\t\t\"length\",\n\t\t\"rating\",\n\t\t\"actors\",\n\t}\n}", "func Columns() *ColumnsType {\n\ttable := qbColumnsTable\n\treturn &ColumnsType{\n\t\tqbColumnsFColumnName.Copy(&table),\n\t\tqbColumnsFTableSchema.Copy(&table),\n\t\tqbColumnsFTableName.Copy(&table),\n\t\tqbColumnsFCharacterMaximumLength.Copy(&table),\n\t\t&table,\n\t}\n}", "func (db *DB) InitColumns(param *Params) {\n\n\tvar (\n\t\tname = conf.Get[string](cons.ConfDBName)\n\t\ttables = []string{param.Table}\n\t)\n\n\ttables = append(tables, param.InnerTable...)\n\ttables = append(tables, param.LeftTable...)\n\n\tfor _, v := range tables {\n\t\tif v == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := TableCols[v]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tvar columns []string\n\t\tparam.Data = &columns\n\t\ttb := TableOnly(v)\n\t\tdb.get(&GT{\n\t\t\tParams: &Params{Data: &columns},\n\t\t\tsql: \"SELECT COLUMN_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_NAME = ? and TABLE_SCHEMA = ?\",\n\t\t\tArgs: []any{tb, name},\n\t\t})\n\t\tTableCols[tb] = columns\n\t}\n}", "func (m *List) GetColumns()([]ColumnDefinitionable) {\n return m.columns\n}", "func (q *Query) Columns(names ...string) *Query {\n\tq.headers = append(q.headers, \"Columns: \"+strings.Join(names, \" \"))\n\tq.columns = names\n\treturn q\n}", "func (b CreateIndexBuilder) Columns(columns ...string) CreateIndexBuilder {\n\treturn builder.Set(b, \"Columns\", columns).(CreateIndexBuilder)\n}", "func (r *Reader) SetColumnNames(cols []string) {\n\tif r.ColumnNamesInFirstRow {\n\t\tpanic(\"Should not assign column names when they are expected in the first row\")\n\t}\n\tr.cols = cols\n}", "func (f *fileHelper) setHeaderColumns (str string, col int) {\n\tswitch str {\n\tcase colName:\n\t\tf.nameCol = col\n\tcase colDepartment:\n\t\tf.departCol = col\n\tcase colClient:\n\t\tf.clientCol = col\n\tcase colSede:\n\t\tf.sedeCol = col\n\tcase status:\n\t\tf.statusCol = col\n\t\tf.firstDateCol = col + 1\n\t\tf.fieldsSet = true\n\t}\n}", "func setColumnValues(b *Battery) {\n\tvar remainingFloors int\n\n\t//calculating the remaining floors\n\tif b.numberOfBasements > 0 { //if there are basement floors\n\t\tremainingFloors = b.numberOfFloors % (b.numberOfColumns - 1)\n\t} else { //if there is no basement\n\t\tremainingFloors = b.numberOfFloors % b.numberOfColumns\n\t}\n\n\t//setting the minFloor and maxFloor of each column\n\tif b.numberOfColumns == 1 { //if there is just one column, it serves all the floors of the building\n\t\tinitializeUniqueColumnFloors(b)\n\t} else { //for more than 1 column\n\t\tinitializeMultiColumnFloors(b)\n\n\t\t//adjusting the number of served floors of the columns if there are remaining floors\n\t\tif remainingFloors != 0 { //if the remainingFloors is not zero, then it adds the remaining floors to the last column\n\t\t\tb.columnsList[len(b.columnsList)-1].numberServedFloors = b.numberOfFloorsPerColumn + remainingFloors\n\t\t\tb.columnsList[len(b.columnsList)-1].maxFloor = b.columnsList[len(b.columnsList)-1].minFloor + b.columnsList[len(b.columnsList)-1].numberServedFloors\n\t\t}\n\t\t//if there is a basement, then the first column will serve the basements + RDC\n\t\tif b.numberOfBasements > 0 {\n\t\t\tinitializeBasementColumnFloors(b)\n\t\t}\n\t}\n}", "func (mc *MultiCursor) SetColumn() {\n\tcol := mc.cursors[0].col\n\tminRow, maxRow := mc.MinMaxRow()\n\tmc.cursors = []Cursor{}\n\tfor row := minRow; row <= maxRow; row++ {\n\t\tcursor := Cursor{row: row, col: col, colwant: col}\n\t\tmc.Append(cursor)\n\t}\n}", "func (qr *QueryResponse) Columns() []ColumnItem {\n\treturn qr.ColumnList\n}", "func Columns(columns ...ColumnMap) *MappedColumns {\n\treturn &MappedColumns{columns, func() error { return nil }}\n}", "func (i *Inserter) Columns(s []string) builder.Inserter {\n\tsort.Strings(s)\n\ti.sql.WriteString(strings.Join(s, seperator))\n\ti.sql.WriteString(\" ) values \")\n\treturn i\n}", "func (w *TableWriters) WriteColumns(columns []model.TableColumn) {\n\tfor _, s := range w.writers {\n\t\ts.WriteColumns(columns)\n\t}\n}", "func (fw *FileWriter) Columns() []*Column {\n\treturn fw.schemaWriter.Columns()\n}", "func (l *universalLister) SetSelectedColumns(selectedColumns []string) {\n\tl.selectedColumns = strings.Join(selectedColumns, \", \")\n}", "func (t *Type) SetFields(fields []*Field)", "func (v *actorInfoViewType) Columns() []string {\n\treturn []string{\n\t\t\"actor_id\",\n\t\t\"first_name\",\n\t\t\"last_name\",\n\t\t\"film_info\",\n\t}\n}", "func (r *Iter_UServ_UpdateNameToFoo) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (v *permutationTableType) Columns() []string {\n\treturn []string{\"uuid\", \"data\"}\n}", "func (matrix Matrix4) SetColumn(columnIndex int, columnData vector.Vector) Matrix4 {\n\tfor i := range matrix {\n\t\tmatrix[i][columnIndex] = columnData[i]\n\t}\n\treturn matrix\n}", "func (m *ItemItemsItemWorkbookTablesWorkbookTableItemRequestBuilder) Columns()(*ItemItemsItemWorkbookTablesItemColumnsRequestBuilder) {\n return NewItemItemsItemWorkbookTablesItemColumnsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (a *SqlAgent) SetUpdateColumns(updateBuilder sq.UpdateBuilder, model interface{}, ignoreColumns ...string) sq.UpdateBuilder {\n\tfieldMap := a.db.Mapper.TypeMap(reflect.TypeOf(model))\n\tvalueMap := a.db.Mapper.FieldMap(reflect.Indirect(reflect.ValueOf(model)))\n\tclauses := make(map[string]interface{})\n\n\tfor _, v := range fieldMap.Index {\n\t\tname := v.Name\n\t\tif isIgnoreFields(name, ignoreColumns) {\n\t\t\tcontinue\n\t\t}\n\t\tif data, ok := valueMap[name]; ok {\n\t\t\tclauses[name] = data.Interface()\n\t\t}\n\t}\n\treturn updateBuilder.SetMap(clauses)\n}", "func (t *Table) SetColumnWidths(widths []int) {\n\tt.columnWidths = widths\n}", "func (ref *UIElement) Columns() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ColumnsAttribute)\n}", "func (o CassandraSchemaOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchema) []Column { return v.Columns }).(ColumnArrayOutput)\n}", "func (d *dbBase) setColsValues(mi *modelInfo, ind *reflect.Value, cols []string, values []interface{}, tz *time.Location) {\n\tfor i, column := range cols {\n\t\tval := reflect.Indirect(reflect.ValueOf(values[i])).Interface()\n\n\t\tfi := mi.fields.GetByColumn(column)\n\n\t\tfield := ind.FieldByIndex(fi.fieldIndex)\n\n\t\tvalue, err := d.convertValueFromDB(fi, val, tz)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Raw value: `%v` %s\", val, err.Error()))\n\t\t}\n\n\t\t_, err = d.setFieldValue(fi, value, field)\n\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Raw value: `%v` %s\", val, err.Error()))\n\t\t}\n\t}\n}", "func (t *NodesTable) Columns() []table.ColumnDefinition {\n\treturn t.columns\n}", "func (d *Dataset) UpdateColumns(a *config.AppContext, cols []models.Node) ([]models.Node, error) {\n\tds := models.Dataset(*d)\n\tres, err := (&ds).UpdateColumns(a.Log, a.Db, cols)\n\t*d = Dataset(ds)\n\treturn res, err\n}", "func (v *coachTableType) Columns() []string {\n\treturn []string{\n\t\t\"id\",\n\t\t\"name\",\n\t\t\"created_at\",\n\t\t\"updated_at\",\n\t}\n}", "func buildGridColumnsData(columns []ColumnSchema ,index int, cols []interface{})[]interface{}{\n\tcols = append(cols, ColumnDefinition{\n\t\tText: columns[index].Name,\n\t\tDataIndex: columns[index].Field,\n\t\tWidth : 120,\n\t\tSortable:true,\n\t\tDataType: columns[index].Type,\n\t})\n\treturn cols;\n}", "func (v *templateTableType) Columns() []string {\n\treturn []string{\n\t\t\"id\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"type\",\n\t\t\"note\",\n\t\t\"coach_id\",\n\t\t\"place_id\",\n\t\t\"weekday\",\n\t\t\"start_time\",\n\t\t\"duration\",\n\t\t\"created_at\",\n\t\t\"updated_at\",\n\t}\n}", "func (m *Schema) SetProperties(value []Propertyable)() {\n m.properties = value\n}", "func (m *AccessReviewSet) SetDefinitions(value []AccessReviewScheduleDefinitionable)() {\n m.definitions = value\n}", "func (k *CustomResourceKind) Columns() []*printer.TableColumn {\n\tif k.Spec == nil {\n\t\treturn nil\n\t}\n\n\treturn []*printer.TableColumn{\n\t\t{\n\t\t\tName: \"JSONSchema\",\n\t\t\tValue: k.Spec.JSONSchema,\n\t\t},\n\t}\n}", "func (o CassandraSchemaResponseOutput) Columns() ColumnResponseArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchemaResponse) []ColumnResponse { return v.Columns }).(ColumnResponseArrayOutput)\n}", "func (s *DbRecorder) Columns(includeKeys bool) []string {\n\treturn s.colList(includeKeys, false)\n}", "func (t Table) Columns() []*Column {\n\treturn t.columns\n}", "func (i *PermissionIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *filter) Columns() []string {\n\treturn r.input.Columns()\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (i *UserPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *Iter_UServ_CreateUsersTable) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (i *UserIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (i *UserGroupsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (d *Driver) SetColumn(idx int, c int, rV byte) error {\n\tfor r := 0; r < 8; r++ {\n\t\tvar on bool\n\t\tif (rV>>byte(7-r))&0x01 == 1 {\n\t\t\ton = true\n\t\t}\n\t\tif err := d.SetLed(idx, r, c, on); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *Table) SetColumnExpansions(expansions []int) {\n\tt.columnExpansions = expansions\n}", "func (r *Iter_UServ_UpdateUserName) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func Columns(cols ...ColumnCreator) []ColumnCreator {\n\treturn cols\n}", "func (db *DB) Columns(table string) ([]string, error) {\n\tif err := db.db.RLock(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.db.RUnlock()\n\n\ts, err := db.db.Schema(table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cols []string\n\tfor _, c := range s.Columns {\n\t\tcols = append(cols, c.Column)\n\t}\n\treturn cols, nil\n}", "func (xs *Sheet) SetCol(colFirst int, colLast int, width float64, format *Format, hidden int) int {\n\tfo := uintptr(0)\n\tif nil != format {\n\t\tfo = format.self\n\t}\n\ttmp, _, _ := xs.xb.lib.NewProc(\"xlSheetSetColW\").\n\t\tCall(xs.self, I(colFirst), I(colLast), F(width), fo, I(hidden))\n\n\treturn int(tmp)\n}", "func (v *pgStatDatabaseViewType) Columns() []string {\n\treturn []string{\n\t\t\"datid\",\n\t\t\"datname\",\n\t}\n}", "func (r *Iter_UServ_InsertUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (r *Iter_UServ_GetAllUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (fn *formulaFuncs) COLUMNS(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"COLUMNS requires 1 argument\")\n\t}\n\tmin, max := calcColumnsMinMax(argsList)\n\tif max == MaxColumns {\n\t\treturn newNumberFormulaArg(float64(MaxColumns))\n\t}\n\tresult := max - min + 1\n\tif max == min {\n\t\tif min == 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"invalid reference\")\n\t\t}\n\t\treturn newNumberFormulaArg(float64(1))\n\t}\n\treturn newNumberFormulaArg(float64(result))\n}", "func (o CassandraSchemaPtrOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v *CassandraSchema) []Column {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(ColumnArrayOutput)\n}", "func (o DataSetGeoSpatialColumnGroupOutput) Columns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v DataSetGeoSpatialColumnGroup) []string { return v.Columns }).(pulumi.StringArrayOutput)\n}", "func (i *GroupPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (dao *PagesDao) Columns() PagesColumns {\n\treturn dao.columns\n}", "func (v *pgUserViewType) Columns() []string {\n\treturn []string{\n\t\t\"usesysid\",\n\t\t\"usename\",\n\t}\n}", "func (r *rows) Columns() (c []string) {\n\tif trace {\n\t\tdefer func() {\n\t\t\ttracer(r, \"Columns(): %v\", c)\n\t\t}()\n\t}\n\treturn r.columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (m *ItemSitesSiteItemRequestBuilder) Columns()(*ItemSitesItemColumnsRequestBuilder) {\n return NewItemSitesItemColumnsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (v *productTableType) Columns() []string {\n\treturn []string{\"product_id\", \"party_id\", \"created_at\", \"serial\", \"addr\"}\n}", "func (m *SiteItemRequestBuilder) Columns()(*ItemColumnsRequestBuilder) {\n return NewItemColumnsRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (c *ProjectsInstancesTablesModifyColumnFamiliesCall) Fields(s ...googleapi.Field) *ProjectsInstancesTablesModifyColumnFamiliesCall {\n\tc.urlParams_.Set(\"fields\", googleapi.CombineFields(s))\n\treturn c\n}", "func (view *CrosstabView) Columns() ([]string, error) {\n\tif view.err != nil {\n\t\treturn nil, view.err\n\t}\n\tcols := make([]string, len(view.hkeys)+1)\n\tcols[0] = view.v\n\tfor i := 0; i < len(view.hkeys); i++ {\n\t\tcols[i+1] = view.hkeys[i].v\n\t}\n\treturn cols, nil\n}", "func (r *Reader) Columns() []Column {\n\treturn r.cols\n}", "func createColumnsList(b *Battery) {\n\tname := 'A'\n\tfor i := 1; i <= b.numberOfColumns; i++ {\n\t\tc := newColumn(i, name, columnActive, b.numberOfElevatorsPerColumn, b.numberOfFloorsPerColumn, b.numberOfBasements, b)\n\t\tb.columnsList = append(b.columnsList, c)\n\t\tname++\n\t}\n}", "func (*__tbl_iba_servers) GetColumns() []string {\n\treturn []string{\"id\", \"name\", \"zex\", \"stort\", \"comment\"}\n}", "func (dao *SysConfigDao) Columns() SysConfigColumns {\n\treturn dao.columns\n}", "func (_m *RepositoryMock) GetColumns() []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\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_article *Article) UpdateColumns(am map[string]interface{}) error {\n\tif _article.Id == 0 {\n\t\treturn errors.New(\"Invalid Id field: it can't be a zero value\")\n\t}\n\terr := UpdateArticle(_article.Id, am)\n\treturn err\n}", "func (m *Model) GetColumns() []Column {\n\treturn m.Columns\n}", "func (r *result) Columns() []string {\n\treturn r.columns\n}", "func (t *table) SetHeaders(h []string) {\n\tt.Headers = h\n}", "func (o CassandraSchemaResponsePtrOutput) Columns() ColumnResponseArrayOutput {\n\treturn o.ApplyT(func(v *CassandraSchemaResponse) []ColumnResponse {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(ColumnResponseArrayOutput)\n}", "func (f *Fields) Set(s []*Field)", "func (r *Iter_UServ_Drop) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (fb *FlowBox) SetColumnSpacing(spacing uint) {\n\tC.gtk_flow_box_set_column_spacing(fb.native(), C.guint(spacing))\n}", "func (q Query) Columns() []string {\n\treturn q.columns\n}", "func (m *MockDriver) Columns(schema, tableName string, whitelist, blacklist []string) ([]drivers.Column, error) {\n\treturn map[string][]drivers.Column{\n\t\t\"pilots\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"name\", Type: \"string\", DBType: \"character\"},\n\t\t},\n\t\t\"airports\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"size\", Type: \"null.Int\", DBType: \"integer\", Nullable: true},\n\t\t},\n\t\t\"jets\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"pilot_id\", Type: \"int\", DBType: \"integer\", Nullable: true, Unique: true},\n\t\t\t{Name: \"airport_id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"name\", Type: \"string\", DBType: \"character\", Nullable: false},\n\t\t\t{Name: \"color\", Type: \"null.String\", DBType: \"character\", Nullable: true},\n\t\t\t{Name: \"uuid\", Type: \"string\", DBType: \"uuid\", Nullable: true},\n\t\t\t{Name: \"identifier\", Type: \"string\", DBType: \"uuid\", Nullable: false},\n\t\t\t{Name: \"cargo\", Type: \"[]byte\", DBType: \"bytea\", Nullable: false},\n\t\t\t{Name: \"manifest\", Type: \"[]byte\", DBType: \"bytea\", Nullable: true, Unique: true},\n\t\t},\n\t\t\"licenses\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"pilot_id\", Type: \"int\", DBType: \"integer\"},\n\t\t},\n\t\t\"hangars\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"name\", Type: \"string\", DBType: \"character\", Nullable: true, Unique: true},\n\t\t},\n\t\t\"languages\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"language\", Type: \"string\", DBType: \"character\", Nullable: false, Unique: true},\n\t\t},\n\t\t\"pilot_languages\": {\n\t\t\t{Name: \"pilot_id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"language_id\", Type: \"int\", DBType: \"integer\"},\n\t\t},\n\t}[tableName], nil\n}", "func (d *PrefsDialog) populateColumns() {\n\t// First add selected columns\n\tselColSpecs := config.GetConfig().QueueColumns\n\tfor _, colSpec := range selColSpecs {\n\t\td.addQueueColumn(colSpec.ID, colSpec.Width, true)\n\t}\n\n\t// Add all unselected columns\n\tfor _, id := range config.MpdTrackAttributeIds {\n\t\t// Check if the ID is already in the list of selected IDs\n\t\tisSelected := false\n\t\tfor _, selSpec := range selColSpecs {\n\t\t\tif id == selSpec.ID {\n\t\t\t\tisSelected = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// If not, add it\n\t\tif !isSelected {\n\t\t\td.addQueueColumn(id, 0, false)\n\t\t}\n\t}\n\td.ColumnsListBox.ShowAll()\n}", "func (b *SelectBuilder) AddColumns(columns ...string) *SelectBuilder {\n\tb.Columns = append(b.Columns, columns...)\n\treturn b\n}", "func (info *ModelInfo) SetColumnName() {\n\tfor table_index, table := range info.TableList {\n\t\tfor col_index, col := range table.ColumnList {\n\t\t\tif strings.EqualFold(\"-\", col.ColumnName) { // 指明不生成表字段\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcol.ColumnName = col.PropName\n\t\t\ttable.ColumnList[col_index] = col\n\t\t}\n\t\tinfo.TableList[table_index] = table\n\t}\n}", "func (r *rows) Columns() []string {\n\treturn r.parent.columns\n}", "func (v *libraryTableType) Columns() []string {\n\treturn []string{\"id\", \"user_id\", \"volume_id\", \"created_at\", \"updated_at\"}\n}", "func (i *GroupIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}" ]
[ "0.69769454", "0.6804708", "0.67329115", "0.65630496", "0.6390641", "0.6051947", "0.6024405", "0.5607218", "0.5591005", "0.556967", "0.55185026", "0.5513934", "0.5410269", "0.539816", "0.53536016", "0.5328212", "0.52258617", "0.52192163", "0.52094", "0.51368654", "0.5131282", "0.51265967", "0.5082629", "0.5059485", "0.5049625", "0.50261617", "0.50241125", "0.5011801", "0.50109303", "0.50031376", "0.49956384", "0.4980662", "0.4977849", "0.49719882", "0.49666774", "0.49625155", "0.49606866", "0.49562782", "0.49543703", "0.4941839", "0.4921603", "0.49167234", "0.48991227", "0.4872158", "0.48587295", "0.4857346", "0.4848547", "0.4847016", "0.48416835", "0.48409924", "0.4833213", "0.4833213", "0.4823057", "0.48215", "0.48130357", "0.48065925", "0.480118", "0.47733977", "0.476567", "0.47571632", "0.47564727", "0.47546577", "0.47529897", "0.47365603", "0.4735436", "0.47300097", "0.471253", "0.4707334", "0.4705093", "0.4703362", "0.4701374", "0.46865958", "0.46856567", "0.46856567", "0.46761915", "0.46757978", "0.4675394", "0.46713573", "0.4653086", "0.46499547", "0.46468425", "0.46319893", "0.4630998", "0.46268174", "0.46222273", "0.46149603", "0.4614886", "0.46004966", "0.45961547", "0.45920637", "0.45788088", "0.4574054", "0.4570474", "0.4563992", "0.45610535", "0.4554142", "0.45470765", "0.45448327", "0.4544562", "0.45406583" ]
0.7975869
0
SetContentTypes sets the contentTypes property value. The collection of content types present in this list.
SetContentTypes задает значение свойства contentTypes. Коллекция типов содержимого, присутствующих в этом списке.
func (m *List) SetContentTypes(value []ContentTypeable)() { m.contentTypes = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *LastMileAccelerationOptions) SetContentTypes(v []string) {\n\to.ContentTypes = &v\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypes(contentTypes *string) {\n\to.ContentTypes = contentTypes\n}", "func ContentTypes(types []string, blacklist bool) Option {\n\treturn func(c *config) error {\n\t\tc.contentTypes = []parsedContentType{}\n\t\tfor _, v := range types {\n\t\t\tmediaType, params, err := mime.ParseMediaType(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.contentTypes = append(c.contentTypes, parsedContentType{mediaType, params})\n\t\t}\n\t\tc.blacklist = blacklist\n\t\treturn nil\n\t}\n}", "func (o *LastMileAccelerationOptions) GetContentTypes() []string {\n\tif o == nil || o.ContentTypes == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.ContentTypes\n}", "func ContentTypes(contentTypes ...string) Option {\n\treturn ArrayOpt(\"content_types\", contentTypes...)\n}", "func (s *ChannelSpecification) SetSupportedContentTypes(v []*string) *ChannelSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (ht HTMLContentTypeBinder) ContentTypes() []string {\n\treturn []string{\n\t\t\"application/html\",\n\t\t\"text/html\",\n\t\t\"application/x-www-form-urlencoded\",\n\t\t\"html\",\n\t}\n}", "func (s *RecommendationJobPayloadConfig) SetSupportedContentTypes(v []*string) *RecommendationJobPayloadConfig {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (set *ContentTypeSet) Types() (types []ContentType) {\n\tif set == nil || len(set.set) == 0 {\n\t\treturn []ContentType{}\n\t}\n\treturn append(make([]ContentType, 0, len(set.set)), set.set...)\n}", "func (s *InferenceSpecification) SetSupportedContentTypes(v []*string) *InferenceSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func SetOfContentTypes(types ...ContentType) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == t {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, t)\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIe(contentTypesIe *string) {\n\to.ContentTypesIe = contentTypesIe\n}", "func (ycp *YamlContentParser) ContentTypes() []string {\n\treturn []string{\"text/x-yaml\", \"application/yaml\", \"text/yaml\", \"application/x-yaml\"}\n}", "func (s *AdditionalInferenceSpecificationDefinition) SetSupportedContentTypes(v []*string) *AdditionalInferenceSpecificationDefinition {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (s *CaptureContentTypeHeader) SetCsvContentTypes(v []*string) *CaptureContentTypeHeader {\n\ts.CsvContentTypes = v\n\treturn s\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypes(contentTypes *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypes(contentTypes)\n\treturn o\n}", "func (m *List) GetContentTypes()([]ContentTypeable) {\n return m.contentTypes\n}", "func (m *SiteItemRequestBuilder) ContentTypes()(*ItemContentTypesRequestBuilder) {\n return NewItemContentTypesRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func NewContentTypeSet(types ...string) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\tmediaType, _, err := mime.ParseMediaType(t)\n\t\tif err != nil {\n\t\t\t// skip types that can not be parsed\n\t\t\tcontinue\n\t\t}\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == ContentType(mediaType) {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, ContentType(mediaType))\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (m *ItemSitesSiteItemRequestBuilder) ContentTypes()(*ItemSitesItemContentTypesRequestBuilder) {\n return NewItemSitesItemContentTypesRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (o *LastMileAccelerationOptions) HasContentTypes() bool {\n\tif o != nil && o.ContentTypes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIc(contentTypesIc *string) {\n\to.ContentTypesIc = contentTypesIc\n}", "func (s *QueryFilters) SetTypes(v []*string) *QueryFilters {\n\ts.Types = v\n\treturn s\n}", "func (s *CaptureContentTypeHeader) SetJsonContentTypes(v []*string) *CaptureContentTypeHeader {\n\ts.JsonContentTypes = v\n\treturn s\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNiew(contentTypesNiew *string) {\n\to.ContentTypesNiew = contentTypesNiew\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (s *LogSetup) SetTypes(v []*string) *LogSetup {\n\ts.Types = v\n\treturn s\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNisw(contentTypesNisw *string) {\n\to.ContentTypesNisw = contentTypesNisw\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIsw(contentTypesIsw *string) {\n\to.ContentTypesIsw = contentTypesIsw\n}", "func (s *Channel) SetContentType(v string) *Channel {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *PluginConfigInterface) SetTypes(v []PluginInterfaceType) {\n\to.Types = v\n}", "func (o *MicrosoftGraphListItem) SetContentType(v AnyOfmicrosoftGraphContentTypeInfo) {\n\to.ContentType = &v\n}", "func (s *StartChatContactInput) SetSupportedMessagingContentTypes(v []*string) *StartChatContactInput {\n\ts.SupportedMessagingContentTypes = v\n\treturn s\n}", "func (s *ClarifyInferenceConfig) SetFeatureTypes(v []*string) *ClarifyInferenceConfig {\n\ts.FeatureTypes = v\n\treturn s\n}", "func (_BaseLibrary *BaseLibraryCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *AutoMLChannel) SetContentType(v string) *AutoMLChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *SchemaDefinitionRestDto) SetTypes(v map[string]SchemaType) {\n\to.Types = &v\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesn(contentTypesn *string) {\n\to.ContentTypesn = contentTypesn\n}", "func (o *MicrosoftGraphWorkbookComment) SetContentType(v string) {\n\to.ContentType = &v\n}", "func (_Container *ContainerCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Container.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_AccessIndexor *AccessIndexorCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (s *UtteranceBotResponse) SetContentType(v string) *UtteranceBotResponse {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *AutoMLJobChannel) SetContentType(v string) *AutoMLJobChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *ChatMessage) SetContentType(v string) *ChatMessage {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *MetricsSource) SetContentType(v string) *MetricsSource {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *SendNotificationActionDefinition) SetContentType(v string) *SendNotificationActionDefinition {\n\ts.ContentType = &v\n\treturn s\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *FileSource) SetContentType(v string) *FileSource {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNic(contentTypesNic *string) {\n\to.ContentTypesNic = contentTypesNic\n}", "func (o *InlineResponse20049Post) SetContentType(v string) {\n\to.ContentType = &v\n}", "func (o *CreateWidgetParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (o *MarketDataSubscribeMarketDataParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *InlineResponse200115) SetContentType(v string) {\n\to.ContentType = &v\n}", "func (fc *FileCreate) SetContentType(s string) *FileCreate {\n\tfc.mutation.SetContentType(s)\n\treturn fc\n}", "func (o *BranchingModelSettings) SetBranchTypes(v []BranchingModelSettingsBranchTypes) {\n\to.BranchTypes = &v\n}", "func PossibleContentTypes(firstByte byte) (ct ContentTypeOptions) {\n\tif firstByte == 0 {\n\t\treturn 0\n\t}\n\n\tswitch {\n\tcase firstByte < '\\t' /* 9 */ :\n\t\t// not a text\n\t\tif firstByte&^maskWireType == 0 {\n\t\t\treturn 0\n\t\t}\n\tcase firstByte >= legalUtf8:\n\t\tct |= ContentOptionText\n\tcase firstByte < illegalUtf8FirstByte:\n\t\tct |= ContentOptionText\n\t}\n\n\tswitch WireType(firstByte & maskWireType) {\n\tcase WireVarint:\n\t\tif ct&ContentOptionText == 0 && firstByte >= illegalUtf8FirstByte {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t\tct |= ContentOptionMessage\n\tcase WireFixed64, WireBytes, WireFixed32, WireStartGroup:\n\t\tct |= ContentOptionMessage\n\tcase WireEndGroup:\n\t\tif ct&ContentOptionText == 0 {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t}\n\treturn ct\n}", "func (o *GetContentSourcesUsingGETParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (s *PostAgentProfileInput) SetContentType(v string) *PostAgentProfileInput {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *InferenceExperimentDataStorageConfig) SetContentType(v *CaptureContentTypeHeader) *InferenceExperimentDataStorageConfig {\n\ts.ContentType = v\n\treturn s\n}", "func (s *GetProfileOutput) SetContentType(v string) *GetProfileOutput {\n\ts.ContentType = &v\n\treturn s\n}", "func (c *CreativesListCall) Types(types ...string) *CreativesListCall {\n\tc.urlParams_.SetMulti(\"types\", append([]string{}, types...))\n\treturn c\n}", "func (o *UpdateWidgetParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (s *ListContactReferencesInput) SetReferenceTypes(v []*string) *ListContactReferencesInput {\n\ts.ReferenceTypes = v\n\treturn s\n}", "func (s *TransformInput) SetContentType(v string) *TransformInput {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *BranchingModel) SetBranchTypes(v []BranchingModelBranchTypes) {\n\to.BranchTypes = &v\n}", "func (o *CreateScriptParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIew(contentTypesIew *string) {\n\to.ContentTypesIew = contentTypesIew\n}", "func (o *TradingTableSubscribeTradingTableParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (_BaseContent *BaseContentFilterer) FilterSetContentType(opts *bind.FilterOpts) (*BaseContentSetContentTypeIterator, error) {\n\n\tlogs, sub, err := _BaseContent.contract.FilterLogs(opts, \"SetContentType\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseContentSetContentTypeIterator{contract: _BaseContent.contract, event: \"SetContentType\", logs: logs, sub: sub}, nil\n}", "func (h *ResponseHeader) SetContentType(contentType string) {\n\th.contentType = append(h.contentType[:0], contentType...)\n}", "func (req *Request) SetContentType(val string) {\n\treq.contentType = val\n}", "func (gau *GithubAssetUpdate) SetContentType(s string) *GithubAssetUpdate {\n\tgau.mutation.SetContentType(s)\n\treturn gau\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesIe(contentTypesIe *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesIe(contentTypesIe)\n\treturn o\n}", "func (m *SiteItemRequestBuilder) ContentTypesById(id string)(*ItemContentTypesContentTypeItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"contentType%2Did\"] = id\n }\n return NewItemContentTypesContentTypeItemRequestBuilderInternal(urlTplParams, m.requestAdapter)\n}", "func (d *cephobject) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\treturn nil\n}", "func (o *PostApplyManifestParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesNisw(contentTypesNisw *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesNisw(contentTypesNisw)\n\treturn o\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesIc(contentTypesIc *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesIc(contentTypesIc)\n\treturn o\n}", "func (s *CreateSubscriberInput) SetAccessTypes(v []*string) *CreateSubscriberInput {\n\ts.AccessTypes = v\n\treturn s\n}", "func (r *Request) SetContentType() *Request {\n\tif nil != r.err {\n\t\treturn r\n\t}\n\tr.contentTypeFlag = true\n\treturn r\n}", "func (m *AttachmentItem) SetContentType(value *string)() {\n m.contentType = value\n}", "func (ctx *Context) SetContentType(contentType string) {\n\tctx.AddHeader(HeaderContentType, contentType)\n}", "func (s *SubscriberResource) SetAccessTypes(v []*string) *SubscriberResource {\n\ts.AccessTypes = v\n\treturn s\n}", "func (gauo *GithubAssetUpdateOne) SetContentType(s string) *GithubAssetUpdateOne {\n\tgauo.mutation.SetContentType(s)\n\treturn gauo\n}", "func (b *HTTPCompressionPolicyApplyConfiguration) WithMimeTypes(values ...v1.CompressionMIMEType) *HTTPCompressionPolicyApplyConfiguration {\n\tfor i := range values {\n\t\tb.MimeTypes = append(b.MimeTypes, values[i])\n\t}\n\treturn b\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesNiew(contentTypesNiew *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesNiew(contentTypesNiew)\n\treturn o\n}", "func (b *builder) SetQuotaTypes(quotaTypes map[string]*quota.Type) {\n\tb.quotaTypes = quotaTypes\n}", "func (h *RequestHeader) SetContentType(contentType string) {\n\th.contentType = append(h.contentType[:0], contentType...)\n}", "func SetContentTypeHeader(w http.ResponseWriter, filePath string) {\n\tw.Header().Set(\n\t\t\"Content-Type\",\n\t\tcontentTypes[strings.ToLower(path.Ext(filePath))],\n\t)\n}", "func (o *TradingTableUnsubscribeTradingTableParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *GetContentSourcesUsingGETParams) SetTypeIds(typeIds []string) {\n\to.TypeIds = typeIds\n}", "func (c *Action) SetContentType(val string) string {\n\tvar ctype string\n\tif strings.ContainsRune(val, '/') {\n\t\tctype = val\n\t} else {\n\t\tif !strings.HasPrefix(val, \".\") {\n\t\t\tval = \".\" + val\n\t\t}\n\t\tctype = mime.TypeByExtension(val)\n\t}\n\tif ctype != \"\" {\n\t\tc.SetHeader(\"Content-Type\", ctype)\n\t}\n\treturn ctype\n}", "func (m *WorkbookCommentReply) SetContentType(value *string)() {\n m.contentType = value\n}", "func (*AccountSetContentSettingsRequest) TypeName() string {\n\treturn \"account.setContentSettings\"\n}", "func (o *FiltersVirtualGateway) SetConnectionTypes(v []string) {\n\to.ConnectionTypes = &v\n}", "func (d *ceph) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\tvar rsyncFeatures []string\n\n\t// Do not pass compression argument to rsync if the associated\n\t// config key, that is rsync.compression, is set to false.\n\tif shared.IsFalse(d.Config()[\"rsync.compression\"]) {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"bidirectional\"}\n\t} else {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"compress\", \"bidirectional\"}\n\t}\n\n\tif refresh {\n\t\tvar transportType migration.MigrationFSType\n\n\t\tif IsContentBlock(contentType) {\n\t\t\ttransportType = migration.MigrationFSType_BLOCK_AND_RSYNC\n\t\t} else {\n\t\t\ttransportType = migration.MigrationFSType_RSYNC\n\t\t}\n\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: transportType,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\tif contentType == ContentTypeBlock {\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t\t},\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_BLOCK_AND_RSYNC,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\treturn []migration.Type{\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t},\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RSYNC,\n\t\t\tFeatures: rsyncFeatures,\n\t\t},\n\t}\n}", "func (_options *ToneOptions) SetContentType(contentType string) *ToneOptions {\n\t_options.ContentType = core.StringPtr(contentType)\n\treturn _options\n}", "func UtteranceContentType_Values() []string {\n\treturn []string{\n\t\tUtteranceContentTypePlainText,\n\t\tUtteranceContentTypeCustomPayload,\n\t\tUtteranceContentTypeSsml,\n\t\tUtteranceContentTypeImageResponseCard,\n\t}\n}", "func (o *GetAOrderStatusParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}" ]
[ "0.8701873", "0.81465465", "0.7151172", "0.70922256", "0.67580223", "0.6733916", "0.672834", "0.6628651", "0.65903586", "0.6576717", "0.6566702", "0.64906377", "0.64708567", "0.64687985", "0.643722", "0.63983715", "0.634481", "0.59890896", "0.59173846", "0.5863382", "0.5862911", "0.57626194", "0.5745951", "0.5733736", "0.57226926", "0.56553864", "0.5624121", "0.562204", "0.5612955", "0.5606856", "0.5573394", "0.5566497", "0.55468655", "0.54874617", "0.5485388", "0.5481515", "0.54725456", "0.5465591", "0.54609114", "0.5429692", "0.54262304", "0.5413263", "0.5403812", "0.5398439", "0.5366545", "0.53573436", "0.53433675", "0.5329195", "0.5326385", "0.52792764", "0.5263121", "0.5255185", "0.52521235", "0.52346903", "0.52256525", "0.52218", "0.5215369", "0.51991206", "0.5196988", "0.51804906", "0.5170642", "0.5156085", "0.51348734", "0.51036084", "0.50974077", "0.5094694", "0.50919586", "0.5081819", "0.50776154", "0.50771654", "0.50769913", "0.5034279", "0.503035", "0.5028191", "0.50190395", "0.50155103", "0.5011351", "0.49837467", "0.497627", "0.4974733", "0.49711138", "0.49677294", "0.4965642", "0.4954936", "0.49525303", "0.49462107", "0.49346215", "0.4908835", "0.48975497", "0.48935467", "0.4873314", "0.48638344", "0.48471776", "0.48443124", "0.48352396", "0.48325044", "0.48256606", "0.48242357", "0.4823492", "0.48116872" ]
0.82240343
1
SetDrive sets the drive property value. Only present on document libraries. Allows access to the list as a [drive][] resource with [driveItems][driveItem].
SetDrive задает значение свойства drive. Наличие свойства ограничено документными библиотеками. Позволяет получить доступ к списку как к ресурсу [drive][] с элементами [driveItems][driveItem].
func (m *List) SetDrive(value Driveable)() { m.drive = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Group) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (m *User) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (o *User) SetDrive(v AnyOfmicrosoftGraphDrive) {\n\to.Drive = &v\n}", "func (o *User) SetDrive(v Drive) {\n\to.Drive = &v\n}", "func (m *Drive) SetDriveType(value *string)() {\n m.driveType = value\n}", "func (m *User) SetDrives(value []Driveable)() {\n m.drives = value\n}", "func (m *Group) SetDrives(value []Driveable)() {\n m.drives = value\n}", "func (h *stubDriveHandler) SetDrives(offset int64, d []models.Drive) {\n\th.drives = d\n\th.stubDriveIndex = offset\n}", "func (device *DCV2Bricklet) SetDriveMode(mode DriveMode) (err error) {\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.LittleEndian, mode)\n\n\tresultBytes, err := device.device.Set(uint8(FunctionSetDriveMode), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (o *VirtualizationIweClusterAllOf) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (o *StorageFlexUtilVirtualDrive) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (repo Repository) Drive(driveID resource.ID) drivestream.DriveReference {\n\treturn Drive{\n\t\tdb: repo.db,\n\t\tdrive: driveID,\n\t}\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (o *MicrosoftGraphListItem) SetDriveItem(v AnyOfmicrosoftGraphDriveItem) {\n\to.DriveItem = &v\n}", "func (o *MicrosoftGraphItemReference) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (o *StoragePhysicalDisk) SetDriveFirmware(v string) {\n\to.DriveFirmware = &v\n}", "func (ref FileView) Drive() resource.ID {\n\treturn ref.drive\n}", "func NewDrive()(*Drive) {\n m := &Drive{\n BaseItem: *NewBaseItem(),\n }\n odataTypeValue := \"#microsoft.graph.drive\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func (o *StoragePhysicalDiskAllOf) SetDriveFirmware(v string) {\n\to.DriveFirmware = &v\n}", "func (o *StoragePhysicalDisk) SetDriveState(v string) {\n\to.DriveState = &v\n}", "func WatchDrive(client *Client, env *util.Env) {\n\tpull := func() {\n\t\tUpdateMenu(client, env)\n\t}\n\tutil.SetInterval(pull, time.Duration(env.CFG.Frequency)*time.Millisecond)\n\tpull()\n}", "func (m *List) GetDrive()(Driveable) {\n return m.drive\n}", "func (o *StorageFlexFlashVirtualDrive) SetDriveScope(v string) {\n\to.DriveScope = &v\n}", "func (o *StoragePhysicalDiskAllOf) SetDriveState(v string) {\n\to.DriveState = &v\n}", "func NewDrive(object dbus.BusObject) *Drive {\n\treturn &Drive{object}\n}", "func (m *Machine) attachDrive(ctx context.Context, dev models.Drive) error {\n\thostPath := StringValue(dev.PathOnHost)\n\tm.logger.Infof(\"Attaching drive %s, slot %s, root %t.\", hostPath, StringValue(dev.DriveID), BoolValue(dev.IsRootDevice))\n\trespNoContent, err := m.client.PutGuestDriveByID(ctx, StringValue(dev.DriveID), &dev)\n\tif err == nil {\n\t\tm.logger.Printf(\"Attached drive %s: %s\", hostPath, respNoContent.Error())\n\t} else {\n\t\tm.logger.Errorf(\"Attach drive failed: %s: %s\", hostPath, err)\n\t}\n\treturn err\n}", "func ExportDrive(conn *dbus.Conn, path dbus.ObjectPath, v Driveer) error {\n\treturn conn.ExportSubtreeMethodTable(map[string]interface{}{\n\t\t\"Eject\": v.Eject,\n\t\t\"SetConfiguration\": v.SetConfiguration,\n\t\t\"PowerOff\": v.PowerOff,\n\t}, path, InterfaceDrive)\n}", "func (o *User) SetDrives(v []MicrosoftGraphDrive) {\n\to.Drives = &v\n}", "func (m *Drive) SetList(value Listable)() {\n m.list = value\n}", "func (o *User) SetDrives(v []Drive) {\n\to.Drives = v\n}", "func (o *MicrosoftGraphItemReference) SetDriveId(v string) {\n\to.DriveId = &v\n}", "func (r ApiUpdateHyperflexDriveRequest) HyperflexDrive(hyperflexDrive HyperflexDrive) ApiUpdateHyperflexDriveRequest {\n\tr.hyperflexDrive = &hyperflexDrive\n\treturn r\n}", "func (m *Drive) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetBundles() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetBundles())\n err = writer.WriteCollectionOfObjectValues(\"bundles\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"driveType\", m.GetDriveType())\n if err != nil {\n return err\n }\n }\n if m.GetFollowing() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowing())\n err = writer.WriteCollectionOfObjectValues(\"following\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"list\", m.GetList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"owner\", m.GetOwner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"quota\", m.GetQuota())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"root\", m.GetRoot())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sharePointIds\", m.GetSharePointIds())\n if err != nil {\n return err\n }\n }\n if m.GetSpecial() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSpecial())\n err = writer.WriteCollectionOfObjectValues(\"special\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"system\", m.GetSystem())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (r ApiPatchHyperflexDriveRequest) HyperflexDrive(hyperflexDrive HyperflexDrive) ApiPatchHyperflexDriveRequest {\n\tr.hyperflexDrive = &hyperflexDrive\n\treturn r\n}", "func (m *SiteItemRequestBuilder) Drive()(*ItemDriveRequestBuilder) {\n return NewItemDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (m *Drive) SetRoot(value DriveItemable)() {\n m.root = value\n}", "func (o *Block) GetDrive(ctx context.Context) (drive dbus.ObjectPath, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"Drive\").Store(&drive)\n\treturn\n}", "func (m *Drive) SetItems(value []DriveItemable)() {\n m.items = value\n}", "func (o *StorageFlexUtilVirtualDrive) SetDriveStatus(v string) {\n\to.DriveStatus = &v\n}", "func (ref *Config) SetPartition(val int32) {\n\tref.Partition = val\n}", "func (o *StorageFlexFlashVirtualDrive) SetDriveStatus(v string) {\n\to.DriveStatus = &v\n}", "func (m *ItemSitesSiteItemRequestBuilder) Drive()(*ItemSitesItemDriveRequestBuilder) {\n return NewItemSitesItemDriveRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (s *BasicStore) SetRobot(r *Robot) {\n\ts.Robot = r\n}", "func Drive(driveS *drive.Service, callArgs *[]string, driveRoot *string, localList *[]string, driveList *map[string]string) error {\r\n\r\n\tfor i := range *localList {\r\n\r\n\t\t//open file\r\n\t\tfLink, err := os.Open((*localList)[i])\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t//trims file location to include target folder\r\n\t\ttempIn := strings.LastIndex((*callArgs)[2], (*callArgs)[0])\r\n\t\ttempName := (*callArgs)[2][:tempIn]\r\n\r\n\t\t//C:\\Users\\game_game\\go gets cut out leaving \\test\\level two\\level two - two\r\n\t\t//cuts off entry text to only get part we care about\r\n\t\t//mapName name of the to-be map\r\n\t\ttempPath := strings.Replace((*localList)[i], tempName, \"\", 1)\r\n\t\tfmt.Println(tempPath)\r\n\r\n\t\t//finds last slash to get map name\r\n\t\t//map name is called from driveList to get parent id\r\n\t\t//parent id ex driveList[mapName]\r\n\t\ttempIn = strings.LastIndex(tempPath, (*callArgs)[0])\r\n\t\tmapName := tempPath[:tempIn]\r\n\r\n\t\t//gets relative file path - split counts the other side of a slash ex \\foo is length two\r\n\t\t//folder & file length\r\n\t\ttempLen := len(strings.Split(tempPath, (*callArgs)[0]))\r\n\r\n\t\t//gets stats\r\n\t\tfStat, err := fLink.Stat()\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\tswitch {\r\n\r\n\t\t//Seems like a sitched together thing, but the slash causes issues with split\r\n\t\t//resulting in \\foo always being two and \\foo\\whatever being three\r\n\t\t//however, there needs to be slash as this is necessary for building the internal folder tree\r\n\t\tcase fStat.IsDir() && tempLen == 2:\r\n\t\t\terr := driveFolder(driveS, callArgs, *driveRoot, fStat.Name(), tempPath, driveList)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tfLink.Close()\r\n\t\t\tcontinue\r\n\r\n\t\t\t//this is here in case a single file is uploaded\r\n\t\tcase !fStat.IsDir() && tempLen == 2:\r\n\t\t\terr := driveFile(driveS, callArgs, *driveRoot, fStat.Name(), fLink)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tcontinue\r\n\r\n\t\tcase fStat.IsDir() && tempLen > 2:\r\n\t\t\terr := driveFolder(driveS, callArgs, (*driveList)[mapName], fStat.Name(), tempPath, driveList)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tfLink.Close()\r\n\t\t\tcontinue\r\n\r\n\t\tcase !fStat.IsDir() && tempLen > 2:\r\n\t\t\terr := driveFile(driveS, callArgs, (*driveList)[mapName], fStat.Name(), fLink)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn nil\r\n\r\n}", "func Drive(car Car) Car {\n\tpanic(\"Please implement the Drive function\")\n}", "func (howtoplay *howtoplay) Drive() {\n\tif howtoplay.nextScene != nil {\n\t\tsimra.GetInstance().SetScene(howtoplay.nextScene)\n\t}\n}", "func (h *stubDriveHandler) InDriveSet(path string) bool {\n\tfor _, d := range h.GetDrives() {\n\t\tif firecracker.StringValue(d.PathOnHost) == path {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (computersystem *ComputerSystem) SetBoot(b Boot) error { //nolint\n\tt := struct {\n\t\tBoot Boot\n\t}{Boot: b}\n\treturn computersystem.Patch(computersystem.ODataID, t)\n}", "func (c *FakePortalDocumentClient) SetSorter(sorter func([]*pkg.PortalDocument)) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tc.sorter = sorter\n}", "func (c *CmdReal) SetDir(dir string) {\n\tc.cmd.Dir = dir\n}", "func (o *User) GetDrive() AnyOfmicrosoftGraphDrive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret AnyOfmicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (o *StorageFlexUtilVirtualDrive) SetVirtualDrive(v string) {\n\to.VirtualDrive = &v\n}", "func (m *User) GetDrive()(Driveable) {\n return m.drive\n}", "func (m *SynchronizationSchema) SetDirectories(value []DirectoryDefinitionable)() {\n err := m.GetBackingStore().Set(\"directories\", value)\n if err != nil {\n panic(err)\n }\n}", "func (t *Title) Drive() {\n\tselect {\n\tcase <-t.sceneChangeCh:\n\t\tt.simra.SetScene(&Game{})\n\tdefault:\n\t\t// nop\n\t}\n}", "func OpenDrive() *OpenDriveOptions {\n\treturn &OpenDriveOptions{}\n}", "func (o *StorageAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (m *Drive) SetSystem(value SystemFacetable)() {\n m.system = value\n}", "func (o *User) GetDrive() Drive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret Drive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (g Graph) CreateDrive(w http.ResponseWriter, r *http.Request) {\n\tus, ok := ctxpkg.ContextGetUser(r.Context())\n\tif !ok {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"invalid user\")\n\t\treturn\n\t}\n\n\t// TODO determine if the user tries to create his own personal space and pass that as a boolean\n\tif !canCreateSpace(r.Context(), false) {\n\t\t// if the permission is not existing for the user in context we can assume we don't have it. Return 401.\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"insufficient permissions to create a space.\")\n\t\treturn\n\t}\n\n\tclient := g.GetGatewayClient()\n\tdrive := libregraph.Drive{}\n\tif err := json.NewDecoder(r.Body).Decode(&drive); err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, \"invalid schema definition\")\n\t\treturn\n\t}\n\tspaceName := *drive.Name\n\tif spaceName == \"\" {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"invalid name\")\n\t\treturn\n\t}\n\n\tvar driveType string\n\tif drive.DriveType != nil {\n\t\tdriveType = *drive.DriveType\n\t}\n\tswitch driveType {\n\tcase \"\", \"project\":\n\t\tdriveType = \"project\"\n\tdefault:\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, fmt.Sprintf(\"drives of type %s cannot be created via this api\", driveType))\n\t\treturn\n\t}\n\n\tcsr := storageprovider.CreateStorageSpaceRequest{\n\t\tOwner: us,\n\t\tType: driveType,\n\t\tName: spaceName,\n\t\tQuota: getQuota(drive.Quota, g.config.Spaces.DefaultQuota),\n\t}\n\n\tif drive.Description != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"description\", *drive.Description)\n\t}\n\n\tif drive.DriveAlias != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"spaceAlias\", *drive.DriveAlias)\n\t}\n\n\tresp, err := client.CreateStorageSpace(r.Context(), &csr)\n\tif err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tif resp.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tnewDrive, err := g.cs3StorageSpaceToDrive(r.Context(), wdu, resp.StorageSpace)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing space\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trender.Status(r, http.StatusCreated)\n\trender.JSON(w, r, newDrive)\n}", "func (m *Group) GetDrive()(Driveable) {\n return m.drive\n}", "func (o *User) SetDriveExplicitNull(b bool) {\n\to.Drive = nil\n\to.isExplicitNullDrive = b\n}", "func (m *Drive) SetFollowing(value []DriveItemable)() {\n m.following = value\n}", "func (me *TxsdRedefineTimeSyncTokenTypeComplexContentRestrictionDeviceType) Set(s string) {\n\t(*sac.TDeviceTypeType)(me).Set(s)\n}", "func (o *StorageFlexFlashVirtualDrive) SetVirtualDrive(v string) {\n\to.VirtualDrive = &v\n}", "func (c *Client) SetBootDevice(ctx context.Context, bootDevice string, setPersistent, efiBoot bool) (ok bool, err error) {\n\tok, metadata, err := bmc.SetBootDeviceFromInterfaces(ctx, bootDevice, setPersistent, efiBoot, c.Registry.GetDriverInterfaces())\n\tc.setMetadata(metadata)\n\treturn ok, err\n}", "func (c *Client) SetDir(prefix, name string) {\n\tc.Lock()\n\tc.dir = &models.Directory{\n\t\tBase: fmt.Sprintf(\"%v/%v\", prefix, name),\n\t\tElection: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryElection),\n\t\tRunning: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryRunning),\n\t\tQueue: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryQueue),\n\t\tNodes: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryNodes),\n\t\tMasters: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryMasters),\n\t}\n\tc.Unlock()\n}", "func (d *Drive) setBrakeMode(brakeMode bool) {\n\t// Set brake mode on motors\n\tif d.brakeModeValid != true {\n\t\td.brakeModeValid = true\n\t\td.brakeMode = !brakeMode // This causes the next section to run\n\t}\n\tif brakeMode != d.brakeMode {\n\t\t// We need to actually set the motor's brake mode\n\t\tif brakeMode == true {\n\t\t\t// Hit the brakes\n\t\t\tMotor.EnableBrakeMode(d.leftMotor)\n\t\t\tMotor.EnableBrakeMode(d.rightMotor)\n\t\t} else {\n\t\t\t// Coast\n\t\t\tMotor.DisableBrakeMode(d.leftMotor)\n\t\t\tMotor.DisableBrakeMode(d.rightMotor)\n\t\t}\n\t\td.brakeMode = brakeMode\n\t} else {\n\t\t// Motor's brake mode already set to what we want, don't do anything\n\t}\n}", "func (h *stubDriveHandler) PatchStubDrive(ctx context.Context, client firecracker.MachineIface, pathOnHost string) (*string, error) {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\t// Check to see if stubDriveIndex has increased more than the drive amount.\n\tif h.stubDriveIndex >= int64(len(h.drives)) {\n\t\treturn nil, ErrDrivesExhausted\n\t}\n\n\td := h.drives[h.stubDriveIndex]\n\td.PathOnHost = &pathOnHost\n\n\tif d.DriveID == nil {\n\t\t// this should never happen, but we want to ensure that we never nil\n\t\t// dereference\n\t\treturn nil, ErrDriveIDNil\n\t}\n\n\th.drives[h.stubDriveIndex] = d\n\n\terr := client.UpdateGuestDrive(ctx, firecracker.StringValue(d.DriveID), pathOnHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th.stubDriveIndex++\n\treturn d.DriveID, nil\n}", "func (c *Client) SetDriver(driver string) {\n\tc.driver = driver\n}", "func (o *DataPlaneAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (g *GitDriver) SetFilesystem(fs billy.Filesystem) {\n\tg.Filesystem = fs\n}", "func UnexportDrive(conn *dbus.Conn, path dbus.ObjectPath) error {\n\treturn conn.Export(nil, path, InterfaceDrive)\n}", "func (o *MicrosoftGraphItemReference) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (o *Partition) SetFlags(ctx context.Context, flags uint64, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfacePartition+\".SetFlags\", 0, flags, options).Store()\n\treturn\n}", "func (a *HyperflexApiService) UpdateHyperflexDrive(ctx context.Context, moid string) ApiUpdateHyperflexDriveRequest {\n\treturn ApiUpdateHyperflexDriveRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (vuu *VacUserUpdate) SetPartition(s string) *VacUserUpdate {\n\tvuu.mutation.SetPartition(s)\n\treturn vuu\n}", "func (vuuo *VacUserUpdateOne) SetPartition(s string) *VacUserUpdateOne {\n\tvuuo.mutation.SetPartition(s)\n\treturn vuuo\n}", "func (o *MicrosoftGraphItemReference) SetDriveTypeExplicitNull(b bool) {\n\to.DriveType = nil\n\to.isExplicitNullDriveType = b\n}", "func (d Display) SetDriver(driver string) int {\n\treturn int(C.caca_set_display_driver(d.Dp, C.CString(driver)))\n}", "func (m *Machine) UpdateGuestDrive(ctx context.Context, driveID, pathOnHost string, opts ...PatchGuestDriveByIDOpt) error {\n\tif _, err := m.client.PatchGuestDriveByID(ctx, driveID, pathOnHost, opts...); err != nil {\n\t\tm.logger.Errorf(\"PatchGuestDrive failed: %v\", err)\n\t\treturn err\n\t}\n\n\tm.logger.Printf(\"PatchGuestDrive successful\")\n\treturn nil\n}", "func NewWebDAVDrive(ctx context.Context, config types.SM,\n\tutils drive_util.DriveUtils) (types.IDrive, error) {\n\tu := config[\"url\"]\n\tusername := config[\"username\"]\n\tpassword := config[\"password\"]\n\n\tcacheTtl := config.GetDuration(\"cache_ttl\", -1)\n\n\tu = strings.TrimRight(u, \"/\")\n\n\tuu, e := url.Parse(u)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tpathPrefix := uu.Path\n\n\tw := &WebDAVDrive{\n\t\tusername: username, password: password,\n\t\tcacheTTL: cacheTtl, pathPrefix: pathPrefix,\n\t}\n\n\tif cacheTtl <= 0 {\n\t\tw.cache = drive_util.DummyCache()\n\t} else {\n\t\tw.cache = utils.CreateCache(w.deserializeEntry, nil)\n\t}\n\n\tclient, e := req.NewClient(u, w.beforeRequest, w.afterRequest, &http.Client{})\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tw.c = client\n\n\t// check\n\t_, e = w.Get(ctx, \"/\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn w, nil\n}", "func (v *IADsNameTranslate) Set(adsPath string, setType uint32) (err error) {\n\treturn ole.NewError(ole.E_NOTIMPL)\n}", "func (o *VirtualizationIweClusterAllOf) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (ref *Config) SetPartitioner(val string) {\n\tswitch val {\n\tdefault:\n\t\tref.Errorf(\"Invalid partitioner %s - defaulting to ''\", val)\n\t\tfallthrough\n\tcase \"\":\n\t\tif ref.Partition >= 0 {\n\t\t\tref.Partitioner = sarama.NewManualPartitioner\n\t\t} else {\n\t\t\tref.Partitioner = sarama.NewHashPartitioner\n\t\t}\n\tcase Hash:\n\t\tref.Partitioner = sarama.NewHashPartitioner\n\t\tref.Partition = -1\n\tcase Random:\n\t\tref.Partitioner = sarama.NewRandomPartitioner\n\t\tref.Partition = -1\n\tcase Manual:\n\t\tref.Partitioner = sarama.NewManualPartitioner\n\t\tif ref.Partition < 0 {\n\t\t\tref.Infof(\"Invalid partition %d - defaulting to 0\", ref.Partition)\n\t\t\tref.Partition = 0\n\t\t}\n\t}\n}", "func (v Vehicle) DriveState() (*DriveState, error) {\n\tstateRequest, err := fetchState(\"/drive_state\", v.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stateRequest.Response.DriveState, nil\n}", "func (m *Drive) SetQuota(value Quotaable)() {\n m.quota = value\n}", "func SetBusiness(biz *types.Business) {\n\tif biz == nil {\n\t\tbiz = types.DefaultBusiness()\n\t} else {\n\t\tbiz.Init()\n\t}\n\tglobalBusiness = biz\n}", "func (o *CredentialProviderAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (o *WeaviateAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (c *CmdReal) SetPath(path string) {\n\tc.cmd.Path = path\n}", "func (o *OpenDriveOptions) SetDirectory(dir string) *OpenDriveOptions {\n\tif len(dir) == 0 {\n\t\to.Directory = nil\n\t\treturn o\n\t}\n\to.Directory = &dir\n\treturn o\n}", "func (d *Driver) SetLed(idx int, r, c int, on bool) error {\n\tif err := d.checkIdx(idx); err != nil {\n\t\treturn err\n\t}\n\n\tbuffIdx := (idx-1)*d.Drivers + r\n\tval := byte(0x80) >> byte(c) // 0B10000000 >> c\n\n\tif on {\n\t\td.buff[buffIdx] |= val\n\t} else {\n\t\td.buff[buffIdx] &= ^val\n\n\t}\n\n\treturn nil\n}", "func (o *CloudTidesAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (m *SharepointIds) SetTenantId(value *string)() {\n err := m.GetBackingStore().Set(\"tenantId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (rb *ResourceBuilder) SetDeviceID(val string) {\n\tif rb.config.DeviceID.Enabled {\n\t\trb.res.Attributes().PutStr(\"device.id\", val)\n\t}\n}", "func (m *Win32LobAppFileSystemDetection) SetPath(value *string)() {\n err := m.GetBackingStore().Set(\"path\", value)\n if err != nil {\n panic(err)\n }\n}", "func (a *HyperflexApiService) PatchHyperflexDrive(ctx context.Context, moid string) ApiPatchHyperflexDriveRequest {\n\treturn ApiPatchHyperflexDriveRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}" ]
[ "0.7992977", "0.78732735", "0.7630548", "0.7536296", "0.69157124", "0.6463099", "0.6364722", "0.62700015", "0.6150766", "0.5855303", "0.5782538", "0.57769513", "0.5764786", "0.5764786", "0.57268894", "0.57063174", "0.56432295", "0.55852723", "0.5579085", "0.55205274", "0.5448137", "0.54276675", "0.5421545", "0.5403223", "0.53710896", "0.52889085", "0.52362806", "0.52357626", "0.5211051", "0.5204756", "0.51860315", "0.51611847", "0.5160898", "0.5114724", "0.50795776", "0.5075082", "0.5031512", "0.50270116", "0.49643332", "0.49365494", "0.49281955", "0.4906391", "0.48988026", "0.4856782", "0.48214325", "0.47900835", "0.47858056", "0.47728047", "0.47574756", "0.4756179", "0.47557154", "0.47465056", "0.4744288", "0.47429535", "0.47424018", "0.47228742", "0.47104934", "0.469997", "0.46990734", "0.46905378", "0.46698764", "0.4664836", "0.46541014", "0.46515724", "0.46453363", "0.46316928", "0.46309662", "0.46201545", "0.4617068", "0.46139297", "0.46120286", "0.4609935", "0.4598056", "0.45882663", "0.45871094", "0.45440394", "0.45222646", "0.45199364", "0.45184693", "0.45180827", "0.45175377", "0.45119643", "0.44996482", "0.44973448", "0.4492858", "0.4492558", "0.44913524", "0.44891196", "0.44823483", "0.44611222", "0.44571468", "0.4450749", "0.4436335", "0.44347775", "0.44236732", "0.44187722", "0.44176713", "0.44162342", "0.44155672", "0.44059247" ]
0.8223476
0
SetList sets the list property value. Provides additional details about the list.
SetList устанавливает значение свойства списка. Предоставляет дополнительные сведения о списке.
func (m *List) SetList(value ListInfoable)() { m.list = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Drive) SetList(value Listable)() {\n m.list = value\n}", "func (this *Iter) SetList(l *[]interface{}) {\n\tthis.list = l\n\tthis.index = -1\n\tthis.currentPage = 1\n}", "func (options *ListJobsOptions) SetList(list string) *ListJobsOptions {\n\toptions.List = core.StringPtr(list)\n\treturn options\n}", "func (a *ForjFlag) setList(ol *ForjObjectList, instance, field string) {\n\ta.list = ol\n\ta.setObjectField(ol.obj, field)\n\ta.setObjectInstance(instance)\n}", "func (o *AdminDeleteProfanityFilterParams) SetList(list string) {\n\to.List = list\n}", "func (a *adapter) setList(l []*net.IPNet) {\n\ta.atomicList.Store(l)\n}", "func (s *Storage) SetList(key string, value []string, expirationSec uint64) {\n\ts.set(key, value, expirationSec)\n}", "func (o *ViewProjectActivePages) SetList(v bool) {\n\to.List = &v\n}", "func (c *UsageController) setList(list []models.Usage) {\n\tc.Usage = list\n\tc.parseNewID()\n}", "func (m *EntityMutation) SetListDate(t time.Time) {\n\tm.list_date = &t\n}", "func (pane *TaskPane) SetList(tasks []model.Task) {\n\tpane.ClearList()\n\tpane.tasks = tasks\n\n\tfor i := range pane.tasks {\n\t\tpane.addTaskToList(i)\n\t}\n}", "func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListParam(v [][]byte) *InputService4TestShapeInputService4TestCaseOperation1Input {\n\ts.ListParam = v\n\treturn s\n}", "func (s *GetServersOutput) SetServerList(v []*Server) *GetServersOutput {\n\ts.ServerList = v\n\treturn s\n}", "func (m *SharepointIds) SetListId(value *string)() {\n err := m.GetBackingStore().Set(\"listId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *ServerGroup) SetServerList(v []*Server) *ServerGroup {\n\ts.ServerList = v\n\treturn s\n}", "func (lbu *LoadBalanceUpdate) SetIPList(s string) *LoadBalanceUpdate {\n\tlbu.mutation.SetIPList(s)\n\treturn lbu\n}", "func (obj *Object) SetChildList(children *enigma.ChildList) {\n\tobj.lockData.Lock()\n\tdefer obj.lockData.Unlock()\n\tif obj.data == nil {\n\t\tobj.data = &objectData{\n\t\t\tchildlist: children,\n\t\t}\n\t\treturn\n\t}\n\tobj.data.childlist = children\n}", "func (s *DataValue) SetListValue(v []*DataValue) *DataValue {\n\ts.ListValue = v\n\treturn s\n}", "func (element *Element) List(value string) *Element {\n\treturn element.Attr(\"list\", value)\n}", "func (o *ClaimInList) SetListClaim(exec boil.Executor, insert bool, related *Claim) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(exec, boil.Infer()); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE `claim_in_list` SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, []string{\"list_claim_id\"}),\n\t\tstrmangle.WhereClause(\"`\", \"`\", 0, claimInListPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ClaimID, o.ID}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\to.ListClaimID = related.ClaimID\n\tif o.R == nil {\n\t\to.R = &claimInListR{\n\t\t\tListClaim: related,\n\t\t}\n\t} else {\n\t\to.R.ListClaim = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &claimR{\n\t\t\tListClaimClaimInLists: ClaimInListSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.ListClaimClaimInLists = append(related.R.ListClaimClaimInLists, o)\n\t}\n\n\treturn nil\n}", "func (lbuo *LoadBalanceUpdateOne) SetIPList(s string) *LoadBalanceUpdateOne {\n\tlbuo.mutation.SetIPList(s)\n\treturn lbuo\n}", "func (o *GetListParams) SetListID(listID int64) {\n\to.ListID = listID\n}", "func List(list proto.Message) StateMappingOpt {\n\treturn func(sm *StateMapping, smm StateMappings) {\n\t\tsm.list = list\n\t}\n}", "func (list *List) Set(value string) error {\n\tnewHeader, err := NewHeader(value)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tflag.PrintDefaults()\n\t}\n\t*list = append(*list, newHeader)\n\treturn nil\n}", "func WithListURL(listURL string) Options {\n\treturn func(s *SPDX) { s.listURL = listURL }\n}", "func (fi *funcInfo) emitSetList(line, a, b, c int) {\r\n\tfi.emitABC(line, OP_SETLIST, a, b, c)\r\n}", "func (r *repairInfo) SetRepairTableList(list []string) {\n\tfor i, one := range list {\n\t\tlist[i] = strings.ToLower(one)\n\t}\n\tr.Lock()\n\tdefer r.Unlock()\n\tr.repairTableList = list\n}", "func (m *ClientCertificateAuthentication) SetCertificateList(value []Pkcs12CertificateInformationable)() {\n err := m.GetBackingStore().Set(\"certificateList\", value)\n if err != nil {\n panic(err)\n }\n}", "func (client *ClientImpl) UpdateList(ctx context.Context, args UpdateListArgs) (*PickList, error) {\n\tif args.Picklist == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.Picklist\"}\n\t}\n\trouteValues := make(map[string]string)\n\tif args.ListId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ListId\"}\n\t}\n\trouteValues[\"listId\"] = (*args.ListId).String()\n\n\tbody, marshalErr := json.Marshal(*args.Picklist)\n\tif marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\tlocationId, _ := uuid.Parse(\"01e15468-e27c-4e20-a974-bd957dcccebc\")\n\tresp, err := client.Client.Send(ctx, http.MethodPut, locationId, \"6.0-preview.1\", 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 PickList\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (o *PostBatchParams) SetIntentList(intentList *models.BatchRequest) {\n\to.IntentList = intentList\n}", "func (l *Loader) SetAttrOnList(i Sym, v bool) {\n\tif v {\n\t\tl.attrOnList.Set(i)\n\t} else {\n\t\tl.attrOnList.Unset(i)\n\t}\n}", "func (stor *arrayGroupStorage) SetGroupList(Groups ...Group) {\n\tstor.lock.Lock()\n\tdefer stor.lock.Unlock()\n\tstor.db = Groups\n}", "func NewList()(*List) {\n m := &List{\n BaseItem: *NewBaseItem(),\n }\n odataTypeValue := \"#microsoft.graph.list\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func WithList() Option {\n\treturn func(o *Options) {\n\t\to.list = true\n\t}\n}", "func (lbu *LoadBalanceUpdate) SetWeightList(s string) *LoadBalanceUpdate {\n\tlbu.mutation.SetWeightList(s)\n\treturn lbu\n}", "func (db *Mysql) UpdateList(args *models.UpdateListArgs, user *models.User) error {\n\tlist, err := db.getList(args.ID)\n\tif err != nil {\n\t\tlog.Printf(\"Error while getting list\\n%v\", err)\n\t\treturn err\n\t}\n\n\tif list.UserID != user.ID {\n\t\treturn errors.New(\"Not user's list\")\n\t}\n\n\tif args.Heading != nil {\n\t\tlist.Heading = *args.Heading\n\t}\n\tif args.Archived != nil {\n\t\tlist.Archived = *args.Archived\n\t}\n\n\terr = db.Client.Save(list).Error\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"func\": \"UpdateList\",\n\t\t\t\"subFunc\": \"list.Save\",\n\t\t\t\"userID\": user.ID,\n\t\t\t\"listID\": args.ID,\n\t\t}).Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *Writer) WriteList(lst *list.List) {\n\tptr := unsafe.Pointer(lst)\n\ttyp := reflect.TypeOf(lst)\n\tif writeRef(w, ptr, typ) {\n\t\treturn\n\t}\n\tsetWriterRef(w, ptr, typ)\n\tcount := lst.Len()\n\tif count == 0 {\n\t\twriteEmptyList(w)\n\t\treturn\n\t}\n\twriteListHeader(w, count)\n\tfor e := lst.Front(); e != nil; e = e.Next() {\n\t\tw.Serialize(e.Value)\n\t}\n\twriteListFooter(w)\n}", "func (h *Header) SetAddressList(key string, addrs []*Address) {\n\th.Set(key, formatAddressList(addrs))\n}", "func setSharelist(stub shim.ChaincodeStubInterface, args []string) pb.Response{\n\tvar err error\n\tfmt.Println(\"starting set_sharelist\")\n\n\tif len(args) !=3 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 3\")\n\t}\n\n\treceiptId := args[0]\n\townerId := args[1]\n\townerName := args[2]\n\n\t// get receipt's current state\n\treceiptAsBytes, err := stub.GetState(receiptId)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get Receipt\")\n\t}\n\tres := Receipt{}\n\tjson.Unmarshal(receiptAsBytes, &res)\n\n\towner := Owner{}\n\towner.Id = ownerId\n\towner.Username = ownerName\n\tres.ShareList = append(res.ShareList, owner)\n\n\tresAsBytes, _ := json.Marshal(res)\n\terr = stub.PutState(receiptId, resAsBytes)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"end set_sharelist\")\n\treturn shim.Success(nil)\n}", "func (a *alphaMock) UpdateList(ctx context.Context, in *alpha.UpdateListRequest, opts ...grpc.CallOption) (*alpha.List, error) {\n\t// TODO(#2716): Implement me!\n\treturn nil, errors.Errorf(\"Unimplemented -- UpdateList coming soon\")\n}", "func (s *Service) UpdateList(userInformationList *model.UserInformationList) *UpdateListOp {\n\treturn &UpdateListOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"PUT\",\n\t\tPath: \"users\",\n\t\tPayload: userInformationList,\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv21,\n\t}\n}", "func testList(t *testing.T) *List {\n\tc := testClient()\n\tc.BaseURL = mockResponse(\"lists\", \"list-api-example.json\").URL\n\tlist, err := c.GetList(\"4eea4ff\", Defaults())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn list\n}", "func (lbu *LoadBalanceUpdate) SetForbidList(s string) *LoadBalanceUpdate {\n\tlbu.mutation.SetForbidList(s)\n\treturn lbu\n}", "func (o *UpdatesV3Request) SetPackageList(v []string) {\n\to.PackageList = v\n}", "func (s *GetProductsOutput) SetPriceList(v []aws.JSONValue) *GetProductsOutput {\n\ts.PriceList = v\n\treturn s\n}", "func (lbuo *LoadBalanceUpdateOne) SetWeightList(s string) *LoadBalanceUpdateOne {\n\tlbuo.mutation.SetWeightList(s)\n\treturn lbuo\n}", "func (r *FakeClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {\n\t// TODO (covariance) implement me!\n\tpanic(\"not implemented\")\n}", "func (s *GetCurrentUserDataOutput) SetUserDataList(v []*UserData) *GetCurrentUserDataOutput {\n\ts.UserDataList = v\n\treturn s\n}", "func (s *Connector) SetCapabilityList(v []*string) *Connector {\n\ts.CapabilityList = v\n\treturn s\n}", "func (s *SlotDefaultValueSpecification) SetDefaultValueList(v []*SlotDefaultValue) *SlotDefaultValueSpecification {\n\ts.DefaultValueList = v\n\treturn s\n}", "func (l *List) SetProperty(p sparta.Property, v interface{}) {\n\tswitch p {\n\tcase sparta.Childs:\n\t\tif v == nil {\n\t\t\tl.scroll = nil\n\t\t}\n\tcase sparta.Data:\n\t\tl.data = v\n\tcase sparta.Geometry:\n\t\tval := v.(image.Rectangle)\n\t\tif !l.geometry.Eq(val) {\n\t\t\tl.win.SetProperty(sparta.Geometry, val)\n\t\t}\n\tcase sparta.Parent:\n\t\tif v == nil {\n\t\t\tl.parent = nil\n\t\t}\n\tcase sparta.Name:\n\t\tval := v.(string)\n\t\tif l.name != val {\n\t\t\tl.name = val\n\t\t}\n\tcase sparta.Foreground:\n\t\tval := v.(color.RGBA)\n\t\tif l.fore != val {\n\t\t\tl.fore = val\n\t\t\tl.win.SetProperty(sparta.Foreground, val)\n\t\t}\n\tcase sparta.Background:\n\t\tval := v.(color.RGBA)\n\t\tif l.back != val {\n\t\t\tl.back = val\n\t\t\tl.win.SetProperty(sparta.Background, val)\n\t\t}\n\tcase sparta.Target:\n\t\tval := v.(sparta.Widget)\n\t\tif val == nil {\n\t\t\tval = l.parent\n\t\t}\n\t\tif l.target == val {\n\t\t\tbreak\n\t\t}\n\t\tl.target = val\n\tcase ListList:\n\t\tif v == nil {\n\t\t\tl.list = nil\n\t\t\tl.scroll.SetProperty(ScrollSize, 0)\n\t\t} else {\n\t\t\tval := v.(ListData)\n\t\t\tl.list = val\n\t\t\tl.scroll.SetProperty(ScrollSize, 0)\n\t\t\tl.scroll.SetProperty(ScrollSize, val.Len())\n\t\t}\n\t\tl.scroll.SetProperty(ScrollPage, l.geometry.Dy()/sparta.HeightUnit)\n\t\tl.Update()\n\t}\n}", "func NewList() List {\n\tl := List{}\n\tl.Set = make(map[string]int)\n\treturn l\n}", "func (m *List) SetItems(value []ListItemable)() {\n m.items = value\n}", "func ExampleListType_set() {\n\ttype SomeAPI struct {\n\t\t// +listType=set\n\t\tkeys []string\n\t}\n}", "func NewList(g ...Getter) *List {\n\tlist := &List{\n\t\tlist: g,\n\t}\n\tlist.GetProxy = NewGetProxy(list) // self\n\treturn list\n}", "func (o *FileExtractOptions) SetVarsList(split string) *FileExtractOptions {\n\t// create empty map and header list\n\tm := map[string]Types{}\n\th := []string{}\n\n\t// construct map from split\n\tfields := strings.Split(split, \",\")\n\tif len(fields)%3 != 0 {\n\t\tlog.Fatalf(\"Check the pa list: %s, invalid number of parameters, not modulo 3\", split)\n\t}\n\tfor i := 0; i < len(fields); i += 3 {\n\t\tif v, err := strconv.Atoi(fields[i+1]); err == nil {\n\t\t\tm[fields[i]] = Types{column: v, types: fields[i+2]}\n\t\t\t//pf(\"%#v -> %#v\\n\", h, fields[i])\n\t\t\th = append(h, fields[i])\n\t\t} else {\n\t\t\tlog.Fatalf(\"Check the input of SetVars: [%v]: %v -> %v\\n\",\n\t\t\t\tfields[i], fields[i+1], err)\n\t\t}\n\t}\n\t// copy map and header list to FileExtractOptions object\n\to.varsList = m\n\to.hdr = h\n\treturn o\n}", "func (s *GetConnectorsOutput) SetConnectorList(v []*Connector) *GetConnectorsOutput {\n\ts.ConnectorList = v\n\treturn s\n}", "func (stor *arrayUserStorage) SetUserList(users ...User) {\n\tstor.lock.Lock()\n\tdefer stor.lock.Unlock()\n\tstor.db = users\n}", "func (lbuo *LoadBalanceUpdateOne) SetForbidList(s string) *LoadBalanceUpdateOne {\n\tlbuo.mutation.SetForbidList(s)\n\treturn lbuo\n}", "func (m *User) SetShowInAddressList(value *bool)() {\n m.showInAddressList = value\n}", "func (client *BaseClient) SetURIList(uriList []string) {\n\tclient.index = 0\n\tclient.failround = 0\n\tclient.uriList = shuffleStringSlice(uriList)\n\tif len(client.uriList) > 0 {\n\t\tclient.uri = client.uriList[0]\n\t\tclient.url, _ = url.Parse(client.uri)\n\t}\n}", "func (v *vertex) PropertyList(key, value string) interfaces.Vertex {\n\treturn v.Add(NewSimpleQB(\".property(list,\\\"%s\\\",\\\"%s\\\")\", key, Escape(value)))\n}", "func setFlagList(ctx *context) {\n\tctx.src = flag.String(\"src\", \"\", \"Source file specification\")\n\tctx.dst = flag.String(\"dst\", \"\", \"Target path\")\n\tctx.limitstring = flag.String(\"limit\", \"32k\", \"Bytes per second limit (default 32KB/s)\")\n\tctx.verbose = flag.Bool(\"verbose\", false, \"Verbose mode\")\n\tctx.flagNoColor = flag.Bool(\"no-color\", false, \"Disable color output\")\n\tflag.Parse()\n}", "func NewList(initial []W) UpdatableList {\n\tul := &updatableList{}\n\tul.Update(initial)\n\treturn ul\n}", "func (mmIsInList *mListRepositoryMockIsInList) Set(f func(ip net.IP) (b1 bool)) *ListRepositoryMock {\n\tif mmIsInList.defaultExpectation != nil {\n\t\tmmIsInList.mock.t.Fatalf(\"Default expectation is already set for the ListRepository.IsInList method\")\n\t}\n\n\tif len(mmIsInList.expectations) > 0 {\n\t\tmmIsInList.mock.t.Fatalf(\"Some expectations are already set for the ListRepository.IsInList method\")\n\t}\n\n\tmmIsInList.mock.funcIsInList = f\n\treturn mmIsInList.mock\n}", "func (s *ListSchemaMappingsOutput) SetSchemaList(v []*SchemaMappingSummary) *ListSchemaMappingsOutput {\n\ts.SchemaList = v\n\treturn s\n}", "func (s *ListRecommendedIntentsOutput) SetSummaryList(v []*RecommendedIntentSummary) *ListRecommendedIntentsOutput {\n\ts.SummaryList = v\n\treturn s\n}", "func WithListNamespace(val string) ListOption {\n\treturn func(cfg *listConfig) {\n\t\tcfg.Namespace = val\n\t}\n}", "func (fkw *FakeClientWrapper) List(ctx context.Context, list runtime.Object, opts ...k8sCl.ListOption) error {\n\tif fkw.shouldPatchNS(list) {\n\t\topts = fkw.removeNSFromListOptions(opts)\n\t}\n\treturn fkw.client.List(ctx, list, opts...)\n}", "func (cr CommonWriter) WriteList(op thrift.TProtocol, lIst *idltypes.List, data []interface{}) error {\n\tif err := op.WriteListBegin(thrift.LIST, len(data)); err != nil {\n\t\treturn fmt.Errorf(\"error writing list begin: %s\", err)\n\t}\n\tfor _, v := range data {\n\t\tif err := cr.writeFieldValue(op, v, lIst.ValueType()); err != nil {\n\t\t\treturn fmt.Errorf(\"%s field write error: %s\", lIst.ValueType().Name(), err)\n\t\t}\n\t}\n\tif err := op.WriteListEnd(); err != nil {\n\t\treturn fmt.Errorf(\"error writing list end: %s\", err)\n\t}\n\treturn nil\n}", "func WSList(set *config.Setup, secure bool) error {\n\twsClient := &wSList{\n\t\tUrl: \"/ws_list\",\n\t\tSetup: set,\n\t\tSecure: secure, // only for admins!\n\t}\n\tset.Route.HandleFunc(wsClient.Url, wsClient.HandleConnection)\n\treturn nil\n}", "func WithListMode(v ListMode) (p Pair) {\n\treturn Pair{Key: \"list_mode\", Value: v}\n}", "func NewList() List {\n\treturn List{}\n}", "func (s *InputService5TestShapeRecursiveStructType) SetRecursiveList(v []*InputService5TestShapeRecursiveStructType) *InputService5TestShapeRecursiveStructType {\n\ts.RecursiveList = v\n\treturn s\n}", "func SetPortList(ports []int) []*uint16 {\n\tp := make([]*uint16, len(ports))\n\tfor i, port := range ports {\n\t\tpp := uint16(port)\n\t\tp[i] = &pp\n\t}\n\treturn p\n}", "func WithListOption(value ListOption) Option {\n\treturn func(o *outputOpts) (*outputOpts, error) {\n\t\tif value >= listOptionMax {\n\t\t\treturn nil, fmt.Errorf(\"invalid option value %v\", value)\n\t\t}\n\t\tc := o.copy()\n\t\tc.listOption = value\n\t\treturn c, nil\n\t}\n}", "func (opts *ListOpts) Set(value string) error {\n if opts.validator != nil {\n v, err := opts.validator(value)\n if err != nil {\n return err\n }\n value = v\n }\n (*opts.values) = append((*opts.values), value)\n return nil\n}", "func (l *List) Set(val interface{}) (err error) {\n\tslice, ok := val.([]interface{})\n\tif !ok {\n\t\treturn newError(ErrType, \"expected a list value\")\n\t}\n\n\tnewList := make([]Item, len(slice))\n\n\tfor i, item := range slice {\n\t\tnewItem := MakeZeroValue(l.valType)\n\t\tif err := newItem.Set(item); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewList[i] = newItem\n\t}\n\n\tl.value = newList\n\n\treturn nil\n}", "func NewList(cfg *Configuration) *List {\n\treturn &List{\n\t\tStateMask: ListExecuted,\n\t\tcfg: cfg,\n\t}\n}", "func NewList(list uint32, mode uint32) {\n\tsyscall.Syscall(gpNewList, 2, uintptr(list), uintptr(mode), 0)\n}", "func saveLists() {\n\ttmpArticleList = articleList\n}", "func (o *UpdatePriceListParams) SetPriceList(priceList UpdatePriceListBody) {\n\to.PriceList = priceList\n}", "func (o *CreateListParams) SetCreateList(createList *models.CreateList) {\n\to.CreateList = createList\n}", "func (_CRLv0 *CRLv0Transactor) SetTBSCertList(opts *bind.TransactOpts, ref common.Address) (*types.Transaction, error) {\n\treturn _CRLv0.contract.Transact(opts, \"setTBSCertList\", ref)\n}", "func (l *List) Set(i *Item, value interface{}) {\n\ti.value = l.valueToPointer(value)\n}", "func (_CRLv0 *CRLv0Session) SetTBSCertList(ref common.Address) (*types.Transaction, error) {\n\treturn _CRLv0.Contract.SetTBSCertList(&_CRLv0.TransactOpts, ref)\n}", "func GiveMemberList(pc net.PacketConn, addr net.Addr, memberList *[]MemberID) {\n\treply, _ := json.Marshal(*memberList)\n\tpc.WriteTo(reply, addr)\n}", "func (o *ClaimInList) SetListClaimP(exec boil.Executor, insert bool, related *Claim) {\n\tif err := o.SetListClaim(exec, insert, related); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (m *List) SetSharepointIds(value SharepointIdsable)() {\n m.sharepointIds = value\n}", "func (s *ListTrustStoreCertificatesOutput) SetCertificateList(v []*CertificateSummary) *ListTrustStoreCertificatesOutput {\n\ts.CertificateList = v\n\treturn s\n}", "func NewList(vs ...Value) List {\n\treturn List{&vs}\n}", "func (c *CustomList) Set(value string) error {\n\tvalues := fileutil.LoadCidrsFromSliceOrFileWithMaxRecursion(value, \",\", maxRecursion)\n\t*c = append(*c, values...)\n\treturn nil\n}", "func setList(i Instruction, ls *LuaState) {\n\ta, b, c := i.ABC()\n\ta += 1\n\n\tif c > 0 {\n\t\tc = c - 1\n\t} else {\n\t\tc = Instruction(ls.fetch()).Ax()\n\t}\n\n\tbIsZero := b == 0\n\tif bIsZero {\n\t\tb = int(luaToInteger(ls, -1)) - a - 1\n\t\tluaPop(ls, 1)\n\t}\n\n\tluaCheckStack(ls, 1)\n\tidx := int64(c * LFIELDS_PER_FLUSH)\n\tfor j := 1; j <= b; j++ {\n\t\tidx++\n\t\tluaPushValue(ls, a+j)\n\t\tluaSetI(ls, a, idx)\n\t}\n\n\tif bIsZero {\n\t\tfor j := ls.registerCount() + 1; j <= luaGetTop(ls); j++ {\n\t\t\tidx++\n\t\t\tluaPushValue(ls, j)\n\t\t\tluaSetI(ls, a, idx)\n\t\t}\n\n\t\t// clear stack\n\t\tluaSetTop(ls, ls.registerCount())\n\t}\n}", "func (o *VulnerabilitiesRequest) SetPackageList(v []string) {\n\to.PackageList = v\n}", "func NewList() *list.List {\n\treturn list.New()\n}", "func (s *ListAccountsOutput) SetAccountList(v []*AccountInfo) *ListAccountsOutput {\n\ts.AccountList = v\n\treturn s\n}", "func (feature Feature) SetFieldIntegerList(index int, value []int) {\n\tC.OGR_F_SetFieldIntegerList(\n\t\tfeature.cval,\n\t\tC.int(index),\n\t\tC.int(len(value)),\n\t\t(*C.int)(unsafe.Pointer(&value[0])),\n\t)\n}", "func CallList(list uint32) {\n\tsyscall.Syscall(gpCallList, 1, uintptr(list), 0, 0)\n}", "func (o *IscsiInterfaceGetIterResponseResult) SetAttributesList(newValue IscsiInterfaceGetIterResponseResultAttributesList) *IscsiInterfaceGetIterResponseResult {\n\to.AttributesListPtr = &newValue\n\treturn o\n}", "func NewList() *List {\n\treturn &List{}\n}" ]
[ "0.7852837", "0.7834302", "0.7707903", "0.76114416", "0.7607494", "0.75335294", "0.7371298", "0.7231533", "0.7130639", "0.68794", "0.68399435", "0.67001563", "0.66798425", "0.66119003", "0.65419525", "0.6505559", "0.6407199", "0.6404088", "0.6371527", "0.6308061", "0.62936723", "0.62416595", "0.62228966", "0.6171606", "0.61162627", "0.61132807", "0.60916257", "0.60896856", "0.6079551", "0.6005064", "0.60017604", "0.5997184", "0.5963884", "0.59406066", "0.5939567", "0.5908787", "0.5894123", "0.5893622", "0.58343005", "0.5834161", "0.58195776", "0.5796401", "0.5779361", "0.5765649", "0.5759023", "0.5742546", "0.572596", "0.57150143", "0.5714903", "0.57088387", "0.57029414", "0.5700403", "0.57001716", "0.5694628", "0.56804144", "0.5678146", "0.567118", "0.56186825", "0.5607672", "0.5603317", "0.5594351", "0.5587332", "0.55776954", "0.5552695", "0.5550939", "0.5538157", "0.55288917", "0.552779", "0.5513141", "0.5502733", "0.54853225", "0.5481567", "0.5481391", "0.54756135", "0.545722", "0.54530126", "0.542753", "0.5423204", "0.54086816", "0.5406973", "0.5403477", "0.5403377", "0.53933626", "0.5391557", "0.5387027", "0.5381569", "0.53804135", "0.5369301", "0.5352394", "0.53520703", "0.53443253", "0.5342076", "0.5339083", "0.5335635", "0.53344595", "0.53318995", "0.53277344", "0.5322583", "0.5315016", "0.5314693" ]
0.8415547
0
SetOperations sets the operations property value. The collection of longrunning operations on the list.
SetOperations задает значение свойства operations. Коллекция долгоживущих операций в списке.
func (m *List) SetOperations(value []RichLongRunningOperationable)() { m.operations = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *ExternalConnection) SetOperations(value []ConnectionOperationable)() {\n m.operations = value\n}", "func (m *Workbook) SetOperations(value []WorkbookOperationable)() {\n m.operations = value\n}", "func (m *List) GetOperations()([]RichLongRunningOperationable) {\n return m.operations\n}", "func (c *jobsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v2/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *tensorboardRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/ui/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (req *UpsertObjectRequest) Operations(operations []Operation) *UpsertObjectRequest {\n\treq.operations = operations\n\treturn req\n}", "func (client BaseClient) ListOperations(ctx context.Context) (result Operations, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/BaseClient.ListOperations\")\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.ListOperationsPreparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListOperationsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListOperationsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *cloudChannelRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *workflowsServiceV2BetaRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v2beta/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (req *UpsertRequest) Operations(operations []Operation) *UpsertRequest {\n\treq.operations = operations\n\treturn req\n}", "func (cli *FakeDatabaseClient) ListOperations(ctx context.Context, in *lropb.ListOperationsRequest, opts ...grpc.CallOption) (*lropb.ListOperationsResponse, error) {\n\tatomic.AddInt32(&cli.listOperationsCalledCnt, 1)\n\treturn nil, nil\n}", "func (so *Operations) Operations() api.Operations {\n\treturn api.Operations(so)\n}", "func ListOperations() ([]*op.Operation, error) {\n\tmessage := protocol.NewRequestListMessage()\n\terr := channel.Broadcast(message)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc1 := make(chan *protocol.ResponseList)\n\n\tonResponse := func(response *protocol.ResponseList) {\n\t\tc1 <- response\n\t}\n\n\tbus.SubscribeOnce(string(message.RequestList.ID), onResponse)\n\n\tselect {\n\tcase res := <-c1:\n\t\tif res.Result == protocol.ResponseOk {\n\t\t\treturn res.Operations, nil\n\t\t}\n\n\t\treturn nil, errors.New(string(res.Message))\n\tcase <-time.After(10 * time.Second):\n\t\tbus.Unsubscribe(string(message.RequestList.ID), onResponse)\n\t\treturn nil, errors.New(\"timeout\")\n\t}\n}", "func (c *JobsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *Client) ListOperations(ctx context.Context, params *ListOperationsInput, optFns ...func(*Options)) (*ListOperationsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListOperationsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListOperations\", params, optFns, addOperationListOperationsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListOperationsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (c *TensorboardClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *CloudChannelClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *WorkflowsServiceV2BetaClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func Operations() (string, error) {\n\treturn makeRequest(\"operations\")\n}", "func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (op *OperationRequest) SetOperationsEndpoint() *OperationRequest {\n\treturn op.setEndpoint(\"operations\")\n}", "func (c *cloudChannelReportsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (o NamedRuleWithOperationsPatchOutput) Operations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v NamedRuleWithOperationsPatch) []string { return v.Operations }).(pulumi.StringArrayOutput)\n}", "func SetOps(ops []op.Operation) Options {\n\treturn func(p *Permission) error {\n\t\tif ops == nil {\n\t\t\treturn errors.ErrNilOps\n\t\t}\n\t\tp.Ops = ops\n\t\treturn nil\n\t}\n}", "func NewOperations() *Operations {\n\treturn &Operations{}\n}", "func (bq *InMemoryBuildQueue) ListOperations(ctx context.Context, request *buildqueuestate.ListOperationsRequest) (*buildqueuestate.ListOperationsResponse, error) {\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\t// Obtain operation names in sorted order.\n\tnameList := make([]string, 0, len(bq.operationsNameMap))\n\tfor name := range bq.operationsNameMap {\n\t\tnameList = append(nameList, name)\n\t}\n\tsort.Strings(nameList)\n\tpaginationInfo, endIndex := getPaginationInfo(len(nameList), request.PageSize, func(i int) bool {\n\t\treturn request.StartAfter == nil || nameList[i] > request.StartAfter.OperationName\n\t})\n\n\t// Extract status.\n\tnameListRegion := nameList[paginationInfo.StartIndex:endIndex]\n\toperations := make([]*buildqueuestate.OperationState, 0, len(nameListRegion))\n\tfor _, name := range nameListRegion {\n\t\to := bq.operationsNameMap[name]\n\t\toperations = append(operations, o.getOperationState(bq))\n\t}\n\treturn &buildqueuestate.ListOperationsResponse{\n\t\tOperations: operations,\n\t\tPaginationInfo: paginationInfo,\n\t}, nil\n}", "func (r *OperationsService) List(name string) *OperationsListCall {\n\tc := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *OperationsService) List(name string) *OperationsListCall {\n\tc := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *PolicyBasedRoutingClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (b *ManagedAppRegistrationRequestBuilder) Operations() *ManagedAppRegistrationOperationsCollectionRequestBuilder {\n\tbb := &ManagedAppRegistrationOperationsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/operations\"\n\treturn bb\n}", "func (client BaseClient) ListOperationsResponder(resp *http.Response) (result Operations, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (dop *patchCollector) Operations() []OperationSpec {\n\treturn dop.patchOperations\n}", "func (c *CloudChannelReportsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (client *ApplicationClient) ListOperations(options *ApplicationClientListOperationsOptions) *ApplicationClientListOperationsPager {\n\treturn &ApplicationClientListOperationsPager{\n\t\tclient: client,\n\t\trequester: func(ctx context.Context) (*policy.Request, error) {\n\t\t\treturn client.listOperationsCreateRequest(ctx, options)\n\t\t},\n\t\tadvancer: func(ctx context.Context, resp ApplicationClientListOperationsResponse) (*policy.Request, error) {\n\t\t\treturn runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink)\n\t\t},\n\t}\n}", "func (m *Microservice) GetOperations(status string) (*c8y.OperationCollection, *c8y.Response, error) {\n\topt := &c8y.OperationCollectionOptions{\n\t\tStatus: status,\n\t\tAgentID: m.AgentID,\n\t\tPaginationOptions: c8y.PaginationOptions{\n\t\t\tPageSize: 5,\n\t\t\tWithTotalPages: false,\n\t\t},\n\t}\n\n\tdata, resp, err := m.Client.Operation.GetOperations(m.WithServiceUser(), opt)\n\treturn data, resp, err\n}", "func ToOperations(operations []operation.Operation) ([]*api.Operation, error) {\n\tvar pbOperations []*api.Operation\n\n\tfor _, o := range operations {\n\t\tpbOperation := &api.Operation{}\n\t\tvar err error\n\t\tswitch op := o.(type) {\n\t\tcase *operation.Set:\n\t\t\tpbOperation.Body, err = toSet(op)\n\t\tcase *operation.Add:\n\t\t\tpbOperation.Body, err = toAdd(op)\n\t\tcase *operation.Move:\n\t\t\tpbOperation.Body, err = toMove(op)\n\t\tcase *operation.Remove:\n\t\t\tpbOperation.Body, err = toRemove(op)\n\t\tcase *operation.Edit:\n\t\t\tpbOperation.Body, err = toEdit(op)\n\t\tcase *operation.Select:\n\t\t\tpbOperation.Body, err = toSelect(op)\n\t\tcase *operation.RichEdit:\n\t\t\tpbOperation.Body, err = toRichEdit(op)\n\t\tcase *operation.Style:\n\t\t\tpbOperation.Body, err = toStyle(op)\n\t\tcase *operation.Increase:\n\t\t\tpbOperation.Body, err = toIncrease(op)\n\t\tdefault:\n\t\t\treturn nil, ErrUnsupportedOperation\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpbOperations = append(pbOperations, pbOperation)\n\t}\n\n\treturn pbOperations, nil\n}", "func (o NamedRuleWithOperationsOutput) Operations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v NamedRuleWithOperations) []string { return v.Operations }).(pulumi.StringArrayOutput)\n}", "func NewOperations(\n\texecutor interfaces.CommandExecutor,\n\tlc logger.LoggingClient,\n\texecutorPath string) *operations {\n\n\treturn &operations{\n\t\texecutor: executor,\n\t\tloggingClient: lc,\n\t\texecutorPath: executorPath,\n\t}\n}", "func (handler *NullHandler) Operations() api_operation.Operations {\n\tops := api_operation.New_SimpleOperations()\n\n\t// Add Null config operations\n\tops.Add(api_operation.Operation(&NullConfigReadersOperation{}))\n\tops.Add(api_operation.Operation(&NullConfigWritersOperation{}))\n\t// Add Null setting operations\n\tops.Add(api_operation.Operation(&NullSettingGetOperation{}))\n\tops.Add(api_operation.Operation(&NullSettingSetOperation{}))\n\t// Add Null command operations\n\tops.Add(api_operation.Operation(&NullCommandListOperation{}))\n\tops.Add(api_operation.Operation(&NullCommandExecOperation{}))\n\t// Add Null documentation operations\n\tops.Add(api_operation.Operation(&NullDocumentTopicListOperation{}))\n\tops.Add(api_operation.Operation(&NullDocumentTopicGetOperation{}))\n\t// Add null monitor operations\n\tops.Add(api_operation.Operation(&NullMonitorStatusOperation{}))\n\tops.Add(api_operation.Operation(&NullMonitorInfoOperation{}))\n\tops.Add(api_operation.Operation(&api_monitor.MonitorStandardLogOperation{}))\n\t// Add Null orchestration operations\n\tops.Add(api_operation.Operation(&NullOrchestrateUpOperation{}))\n\tops.Add(api_operation.Operation(&NullOrchestrateDownOperation{}))\n\t// Add Null security handlers\n\tops.Add(api_operation.Operation(&NullSecurityAuthenticateOperation{}))\n\tops.Add(api_operation.Operation(&NullSecurityAuthorizeOperation{}))\n\tops.Add(api_operation.Operation(&NullSecurityUserOperation{}))\n\n\treturn ops.Operations()\n}", "func GetOperations() ([]dtos.Operation, error) {\n\tvar ops []dtos.Operation\n\n\tresp, err := makeJSONRequest(\"GET\", apiURL+\"/operations\", http.NoBody)\n\tif err != nil {\n\t\treturn ops, errors.Append(err, ErrCannotConnect)\n\t}\n\n\tif err = evaluateResponseStatusCode(resp.StatusCode); err != nil {\n\t\treturn ops, err\n\t}\n\n\terr = readResponseBody(&ops, resp.Body)\n\n\treturn ops, err\n}", "func (handler *LocalHandler_Setting) Operations() api_operation.Operations {\n\tops := api_operation.New_SimpleOperations()\n\n\t// Make a wrapper for the Settings Config interpretation, based on itnerpreting YML settings\n\twrapper := handler_configwrapper.SettingsConfigWrapper(handler_configwrapper.New_BaseSettingConfigWrapperYmlOperation(handler.ConfigWrapper()))\n\n\t// Now we can add config operations that use that Base class\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperGetOperation{Wrapper: wrapper}))\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperSetOperation{Wrapper: wrapper}))\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperListOperation{Wrapper: wrapper}))\n\n\treturn ops.Operations()\n}", "func (r *InspectOperationsService) List(name string) *InspectOperationsListCall {\n\tc := &InspectOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (p *profileCache) ResourceOperations(profileName string, cmd string, method string) ([]models.ResourceOperation, errors.EdgeX) {\n\tp.mutex.RLock()\n\tdefer p.mutex.RUnlock()\n\n\tif err := p.verifyProfileExists(profileName); err != nil {\n\t\treturn nil, err\n\t}\n\n\trosMap, err := p.verifyResourceOperationsExists(method, profileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ok bool\n\tvar ros []models.ResourceOperation\n\tif ros, ok = rosMap[cmd]; !ok {\n\t\terrMsg := fmt.Sprintf(\"failed to find DeviceCommand %s in Profile %s\", cmd, profileName)\n\t\treturn nil, errors.NewCommonEdgeX(errors.KindEntityDoesNotExist, errMsg, nil)\n\t}\n\n\treturn ros, nil\n}", "func (process *Process) GetOperations() []*Operation {\n\n\t// fields\n\tfieldList := \"operation.id, operation.content, operation.start, operation.end, operation.is_running, operation.current_task, operation.result\"\n\n\t// the query\n\tsql := \"SELECT \" + fieldList + \" FROM `operation` AS operation WHERE process=? ORDER BY operation.id DESC\"\n\n\trows, err := database.Connection.Query(sql, process.Action.ID)\n\tif err != nil {\n\t\tfmt.Println(\"Problem #7 when getting all the operations of the process: \")\n\t\tfmt.Println(err)\n\t}\n\n\tvar (\n\t\tlist []*Operation\n\t\tID, currentTaskID int\n\t\tstart, end int64\n\t\tisRunning bool\n\t\tcontent, isRunningString, result string\n\t\ttask *Task\n\t)\n\n\tfor rows.Next() {\n\t\trows.Scan(&ID, &content, &start, &end, &isRunningString, &currentTaskID, &result)\n\n\t\tisRunning, err = strconv.ParseBool(isRunningString)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tif isRunning {\n\t\t\ttask = NewTask(currentTaskID)\n\t\t}\n\n\t\tlist = append(list, &Operation{\n\t\t\tCurrentTask: task,\n\t\t\tAction: &Action{\n\t\t\t\tID: ID,\n\t\t\t\tIsRunning: isRunning,\n\t\t\t\tStart: start,\n\t\t\t\tEnd: end,\n\t\t\t\tContent: content,\n\t\t\t\tresult: result,\n\t\t\t},\n\t\t})\n\t}\n\treturn list\n}", "func (e *Endpoint) GetOperations() []models.EndpointOperation {\n\treturn e.Operations\n}", "func (m *Master) GetOperations(session *gocql.Session, hostname string) ([]ops.Operation, error) {\n\tvar operations []ops.Operation\n\tvar description, scriptName string\n\tvar attributes map[string]string\n\tq := `SELECT description, script_name, attributes FROM operations where hostname = ?`\n\titer := session.Query(q, hostname).Iter()\n\tfor iter.Scan(&description, &scriptName, &attributes) {\n\t\to := ops.Operation{\n\t\t\tDescription: description,\n\t\t\tScriptName: scriptName,\n\t\t\tAttributes: attributes,\n\t\t}\n\t\toperations = append(operations, o)\n\t}\n\tif err := iter.Close(); err != nil {\n\t\treturn []ops.Operation{}, fmt.Errorf(\"error getting operations from DB: %v\", err)\n\t}\n\n\treturn operations, nil\n}", "func (p *Postgres) Operations() []bindings.OperationKind {\n\treturn []bindings.OperationKind{\n\t\texecOperation,\n\t\tqueryOperation,\n\t\tcloseOperation,\n\t}\n}", "func taskListOperation(response *http.Response, executor *operationExecutor) error {\n\tvar err error\n\n\t// TaskList response is a JSON array\n\t// https://docs.docker.com/engine/api/v1.28/#operation/TaskList\n\tresponseArray, err := getResponseAsJSONArray(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !executor.operationContext.isAdmin {\n\t\tresponseArray, err = filterTaskList(responseArray, executor.operationContext)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn rewriteResponse(response, responseArray, http.StatusOK)\n}", "func (o *StoragePhysicalDisk) SetBackgroundOperations(v string) {\n\to.BackgroundOperations = &v\n}", "func (transport *Transport) taskListOperation(response *http.Response, executor *operationExecutor) error {\n\t// TaskList response is a JSON array\n\t// https://docs.docker.com/engine/api/v1.28/#operation/TaskList\n\tresponseArray, err := utils.GetResponseAsJSONArray(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresourceOperationParameters := &resourceOperationParameters{\n\t\tresourceIdentifierAttribute: taskServiceObjectIdentifier,\n\t\tresourceType: portainer.ServiceResourceControl,\n\t\tlabelsObjectSelector: selectorTaskLabels,\n\t}\n\n\tresponseArray, err = transport.applyAccessControlOnResourceList(resourceOperationParameters, responseArray, executor)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn utils.RewriteResponse(response, responseArray, http.StatusOK)\n}", "func (o *Volume) SetIops(v int32) {\n\to.Iops = &v\n}", "func (m *ExternalConnection) GetOperations()([]ConnectionOperationable) {\n return m.operations\n}", "func (o *ResourceDefinitionFilter) SetOperation(v string) {\n\to.Operation = v\n}", "func (o *Volume) SetIops(v int64) {\n\to.Iops = &v\n}", "func (client BaseClient) GetAllOperations(ctx context.Context, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.GetAllOperations\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetAllOperationsPreparer(ctx, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetAllOperationsSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetAllOperationsResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (m *Workbook) GetOperations()([]WorkbookOperationable) {\n return m.operations\n}", "func (swagger *MgwSwagger) SetOperationPolicies(apiProject ProjectAPI) (err error) {\n\tfor _, resource := range swagger.resources {\n\t\tpath := strings.TrimSuffix(resource.path, \"/\")\n\t\tfor _, operation := range resource.methods {\n\t\t\tmethod := operation.method\n\t\t\tfor _, yamlOperation := range apiProject.APIYaml.Data.Operations {\n\t\t\t\tif strings.TrimSuffix(yamlOperation.Target, \"/\") == path && strings.EqualFold(method, yamlOperation.Verb) {\n\t\t\t\t\toperation.policies, err = apiProject.Policies.GetFormattedOperationalPolicies(yamlOperation.OperationPolicies, swagger)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif operation.policies.Request != nil || operation.policies.Response != nil || operation.policies.Fault != nil {\n\t\t\t\t\t\tresource.hasPolicies = true\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (client BaseClient) ListOperationsPreparer(ctx context.Context) (*http.Request, error) {\n\tconst APIVersion = \"2018-05-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/providers/Microsoft.SerialConsole/operations\"),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (reader *LogzioSpanReader) GetOperations(ctx context.Context, query spanstore.OperationQueryParameters) ([]spanstore.Operation, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"GetOperations\")\n\tdefer span.Finish()\n\toperations, err := reader.serviceOperationStorage.getOperations(ctx, query.ServiceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []spanstore.Operation\n\tfor _, operation := range operations {\n\t\tresult = append(result, spanstore.Operation{\n\t\t\tName: operation,\n\t\t})\n\t}\n\treturn result, err\n\n\n}", "func (m *RegistryKeyState) SetOperation(value *RegistryOperation)() {\n m.operation = value\n}", "func getOperations(props *spec.PathItem) map[string]*spec.Operation {\n\tops := map[string]*spec.Operation{\n\t\t\"DELETE\": props.Delete,\n\t\t\"GET\": props.Get,\n\t\t\"HEAD\": props.Head,\n\t\t\"OPTIONS\": props.Options,\n\t\t\"PATCH\": props.Patch,\n\t\t\"POST\": props.Post,\n\t\t\"PUT\": props.Put,\n\t}\n\n\t// Keep those != nil\n\tfor key, op := range ops {\n\t\tif op == nil {\n\t\t\tdelete(ops, key)\n\t\t}\n\t}\n\treturn ops\n}", "func (q *Q) Operations() OperationsQI {\n\treturn &OperationsQ{\n\t\tparent: q,\n\t\tsql: selectOperation,\n\t}\n}", "func ExampleOperationsClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armmonitor.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewOperationsClient().List(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.OperationListResult = armmonitor.OperationListResult{\n\t// \tValue: []*armmonitor.Operation{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Operations/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Operations read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Operations\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Metrics/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metrics read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metrics\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Incidents/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule Incidents read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rule Incident resource\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/providers/Microsoft.Insights/MetricDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Activated/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity Log Alert Activated\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity Log Alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/EventCategories/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event category read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Event category\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/eventtypes/values/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event types management values read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Events\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/eventtypes/digestevents/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event types management digest read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Digest events\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log Definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Scaleup/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale scale up operation\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Scaledown/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale scale down operation\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Activated/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule activated\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Resolved/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule resolved\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Throttled/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule throttled\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Register/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Register Microsoft.Insights\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Microsoft.Insights\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Webtests/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Webtest write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Web tests\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Webtests/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Webtest delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Web tests\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t}},\n\t// }\n}", "func (o *TOC) OutputOperations(i int, outputChapter outputs.Chapter, operations *kubernetes.ActionInfoList) error {\n\toperationsSection, err := outputChapter.AddSection(i, \"Operations\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, operation := range *operations {\n\t\to.OutputOperation(i, operationsSection, &operation)\n\t\t_ = operation\n\t}\n\treturn nil\n}", "func (r *SpanReader) GetOperations(ctx context.Context, service string) ([]string, error){\n\treturn r.cache.LoadOperations(service)\n}", "func ExampleOperationsClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armaddons.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewOperationsClient().List(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.OperationListValue = armaddons.OperationListValue{\n\t// \tValue: []*armaddons.OperationsDefinition{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Addons/supportProviders/supportPlanTypes/read\"),\n\t// \t\t\tDisplay: &armaddons.OperationsDisplayDefinition{\n\t// \t\t\t\tDescription: to.Ptr(\"Get the specified Canonical support plan state.\"),\n\t// \t\t\t\tOperation: to.Ptr(\"Get Canonical support plan state\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Addons\"),\n\t// \t\t\t\tResource: to.Ptr(\"supportPlanTypes\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Addons/supportProviders/supportPlanTypes/write\"),\n\t// \t\t\tDisplay: &armaddons.OperationsDisplayDefinition{\n\t// \t\t\t\tDescription: to.Ptr(\"Adds the Canonical support plan type specified.\"),\n\t// \t\t\t\tOperation: to.Ptr(\"Adds a Canonical support plan.\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Addons\"),\n\t// \t\t\t\tResource: to.Ptr(\"supportPlanTypes\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Addons/supportProviders/supportPlanTypes/delete\"),\n\t// \t\t\tDisplay: &armaddons.OperationsDisplayDefinition{\n\t// \t\t\t\tDescription: to.Ptr(\"Removes the specified Canonical support plan\"),\n\t// \t\t\t\tOperation: to.Ptr(\"Removes the Canonical support plan\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Addons\"),\n\t// \t\t\t\tResource: to.Ptr(\"supportPlanTypes\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Addons/supportProviders/canonical/supportPlanTypes/get\"),\n\t// \t\t\tDisplay: &armaddons.OperationsDisplayDefinition{\n\t// \t\t\t\tDescription: to.Ptr(\"Gets the available Canonical support plan types as well as some extra metadata on their enabled status.\"),\n\t// \t\t\t\tOperation: to.Ptr(\"Gets available Canonical support plan types.\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Addons\"),\n\t// \t\t\t\tResource: to.Ptr(\"supportProviders\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Addons/register/action\"),\n\t// \t\t\tDisplay: &armaddons.OperationsDisplayDefinition{\n\t// \t\t\t\tDescription: to.Ptr(\"Register the specified subscription with Microsoft.Addons\"),\n\t// \t\t\t\tOperation: to.Ptr(\"Register for Microsoft.Addons\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Addons\"),\n\t// \t\t\t\tResource: to.Ptr(\"register\"),\n\t// \t\t\t},\n\t// \t}},\n\t// }\n}", "func serviceListOperation(request *http.Request, response *http.Response, operationContext *restrictedOperationContext) error {\n\tvar err error\n\t// ServiceList response is a JSON array\n\t// https://docs.docker.com/engine/api/v1.28/#operation/ServiceList\n\tresponseArray, err := getResponseAsJSONArray(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif operationContext.isAdmin {\n\t\tresponseArray, err = decorateServiceList(responseArray, operationContext.resourceControls)\n\t} else {\n\t\tresponseArray, err = filterServiceList(responseArray, operationContext.resourceControls, operationContext.userID, operationContext.userTeamIDs)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn rewriteResponse(response, responseArray, http.StatusOK)\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (os *OpSet) Ops() []*Op {\n\treturn os.set\n}", "func (m *TeamItemRequestBuilder) Operations()(*i9fa0e9d329dc2b42ce0cc0330991bb8f8e864efaaef5061789d895e28321a6b2.OperationsRequestBuilder) {\n return i9fa0e9d329dc2b42ce0cc0330991bb8f8e864efaaef5061789d895e28321a6b2.NewOperationsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (b *Bucket) SetOperationTimeout(timeout time.Duration) {\n\tb.opTimeout = timeout\n}", "func (client BaseClient) GetAllOperationsResponder(resp *http.Response) (result SetObject, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusForbidden,http.StatusInternalServerError),\n autorest.ByUnmarshallingJSON(&result.Value),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (resp *ActionVpsFeatureUpdateAllResponse) WatchOperation(timeout float64, updateIn float64, callback OperationProgressCallback) (*ActionActionStatePollResponse, error) {\n\treq := resp.Action.Client.ActionState.Poll.Prepare()\n\treq.SetPathParamInt(\"action_state_id\", resp.Response.Meta.ActionStateId)\n\n\tinput := req.NewInput()\n\tinput.SetTimeout(timeout)\n\tinput.SetUpdateIn(updateIn)\n\n\tpollResp, err := req.Call()\n\n\tif err != nil {\n\t\treturn pollResp, err\n\t} else if pollResp.Output.Finished {\n\t\treturn pollResp, nil\n\t}\n\n\tif callback(pollResp.Output) == StopWatching {\n\t\treturn pollResp, nil\n\t}\n\n\tfor {\n\t\treq = resp.Action.Client.ActionState.Poll.Prepare()\n\t\treq.SetPathParamInt(\"action_state_id\", resp.Response.Meta.ActionStateId)\n\t\treq.SetInput(&ActionActionStatePollInput{\n\t\t\tTimeout: timeout,\n\t\t\tUpdateIn: updateIn,\n\t\t\tStatus: pollResp.Output.Status,\n\t\t\tCurrent: pollResp.Output.Current,\n\t\t\tTotal: pollResp.Output.Total,\n\t\t})\n\t\tpollResp, err = req.Call()\n\n\t\tif err != nil {\n\t\t\treturn pollResp, err\n\t\t} else if pollResp.Output.Finished {\n\t\t\treturn pollResp, nil\n\t\t}\n\n\t\tif callback(pollResp.Output) == StopWatching {\n\t\t\treturn pollResp, nil\n\t\t}\n\t}\n}", "func (s *OperationNamesStorage) GetOperations(service string) ([]string, error) {\n\titer := s.session.Query(s.QueryStmt, service).Iter()\n\n\tvar operation string\n\tvar operations []string\n\tfor iter.Scan(&operation) {\n\t\toperations = append(operations, operation)\n\t}\n\tif err := iter.Close(); err != nil {\n\t\terr = errors.Wrap(err, \"Error reading operation_names from storage\")\n\t\treturn nil, err\n\t}\n\treturn operations, nil\n}", "func (op OperationRequest) StreamOperations(ctx context.Context, client *Client, handler OperationHandler) error {\n\tendpoint, err := op.BuildURL()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to build endpoint for operation request\")\n\t}\n\n\turl := fmt.Sprintf(\"%s%s\", client.fixHorizonURL(), endpoint)\n\treturn client.stream(ctx, url, func(data []byte) error {\n\t\tvar baseRecord operations.Base\n\n\t\tif err = json.Unmarshal(data, &baseRecord); err != nil {\n\t\t\treturn errors.Wrap(err, \"error unmarshaling data for operation request\")\n\t\t}\n\n\t\tops, err := operations.UnmarshalOperation(baseRecord.GetTypeI(), data)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"unmarshaling to the correct operation type\")\n\t\t}\n\n\t\thandler(ops)\n\t\treturn nil\n\t})\n}", "func (db Db) GetOperations(portfolioID string, key string, value string, from string, to string) ([]models.Operation, error) {\n\tpid, err := primitive.ObjectIDFromHex(portfolioID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not decode portfolio Id (%s). Internal error : %s\", portfolioID, err)\n\t}\n\n\tfilter := bson.M{\"pid\": pid}\n\tand := []interface{}{}\n\thasParams := false\n\tif key != \"\" && value != \"\" {\n\t\tand = append(and, bson.M{key: value})\n\t\thasParams = true\n\t}\n\n\tif dtime, err := time.Parse(\"2006-01-02T15:04:05Z07:00\", from); err == nil {\n\t\tand = append(and, bson.M{\"time\": bson.M{\"$gte\": dtime}})\n\t\thasParams = true\n\t}\n\n\tif dtime, err := time.Parse(\"2006-01-02T15:04:05Z07:00\", to); err == nil {\n\t\tand = append(and, bson.M{\"time\": bson.M{\"$lte\": dtime}})\n\t\thasParams = true\n\t}\n\tif hasParams {\n\t\tand = append(and, filter)\n\t\tfilter = bson.M{\"$and\": and}\n\t}\n\n\tfindOptions := options.Find()\n\tfindOptions.SetSort(bson.M{\"time\": 1})\n\treturn db.getOperations(filter, findOptions)\n}", "func (s *FederationSyncController) clusterOperations(selectedClusters, unselectedClusters []string,\n\ttemplate, override *unstructured.Unstructured, key string) ([]util.FederatedOperation, error) {\n\n\toperations := make([]util.FederatedOperation, 0)\n\n\toverridesMap, err := util.GetOverrides(override)\n\tif err != nil {\n\t\toverrideKind := s.typeConfig.GetOverride().Kind\n\t\treturn nil, fmt.Errorf(\"Error reading cluster overrides for %s %q: %v\", overrideKind, key, err)\n\t}\n\n\tversionMap, err := s.versionManager.Get(template, override)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error retrieving version map: %v\", err)\n\t}\n\n\ttargetKind := s.typeConfig.GetTarget().Kind\n\tfor _, clusterName := range selectedClusters {\n\t\t// TODO(marun) Create the desired object only if needed\n\t\tdesiredObj, err := s.objectForCluster(template, overridesMap[clusterName])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// TODO(marun) Wait until result of add operation has reached\n\t\t// the target store before attempting subsequent operations?\n\t\t// Otherwise the object won't be found but an add operation\n\t\t// will fail with AlreadyExists.\n\t\tclusterObj, found, err := s.informer.GetTargetStore().GetByKey(clusterName, key)\n\t\tif err != nil {\n\t\t\twrappedErr := fmt.Errorf(\"Failed to get %s %q from cluster %q: %v\", targetKind, key, clusterName, err)\n\t\t\truntime.HandleError(wrappedErr)\n\t\t\treturn nil, wrappedErr\n\t\t}\n\n\t\tvar operationType util.FederatedOperationType = \"\"\n\n\t\tif found {\n\t\t\tclusterObj := clusterObj.(*unstructured.Unstructured)\n\n\t\t\t// This controller does not perform updates to namespaces\n\t\t\t// in the host cluster. Such operations need to be\n\t\t\t// performed via the Kube API.\n\t\t\t//\n\t\t\t// The Namespace type is a special case because it is the\n\t\t\t// only container in the Kubernetes API. This controller\n\t\t\t// presumes a separation between the template and target\n\t\t\t// resources, but a namespace in the host cluster is\n\t\t\t// necessarily both template and target.\n\t\t\tif targetKind == util.NamespaceKind && util.IsPrimaryCluster(template, clusterObj) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdesiredObj, err = s.objectForUpdateOp(desiredObj, clusterObj)\n\t\t\tif err != nil {\n\t\t\t\twrappedErr := fmt.Errorf(\"Failed to determine desired object %s %q for cluster %q: %v\", targetKind, key, clusterName, err)\n\t\t\t\truntime.HandleError(wrappedErr)\n\t\t\t\treturn nil, wrappedErr\n\t\t\t}\n\n\t\t\tversion, ok := versionMap[clusterName]\n\t\t\tif !ok {\n\t\t\t\t// No target version recorded for template+override version\n\t\t\t\toperationType = util.OperationTypeUpdate\n\t\t\t} else {\n\t\t\t\ttargetVersion := s.comparisonHelper.GetVersion(clusterObj)\n\n\t\t\t\t// Check if versions don't match. If they match then check its\n\t\t\t\t// ObjectMeta which only applies to resources where Generation\n\t\t\t\t// is used to track versions because Generation is only updated\n\t\t\t\t// when Spec changes.\n\t\t\t\tif version != targetVersion {\n\t\t\t\t\toperationType = util.OperationTypeUpdate\n\t\t\t\t} else if !s.comparisonHelper.Equivalent(desiredObj, clusterObj) {\n\t\t\t\t\t// TODO(marun) Since only the metadata is compared\n\t\t\t\t\t// in the call to Equivalent(), use the template\n\t\t\t\t\t// to avoid having to worry about overrides.\n\t\t\t\t\toperationType = util.OperationTypeUpdate\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// A namespace in the host cluster will never need to be\n\t\t\t// added since by definition it must already exist.\n\n\t\t\toperationType = util.OperationTypeAdd\n\t\t}\n\n\t\tif len(operationType) > 0 {\n\t\t\toperations = append(operations, util.FederatedOperation{\n\t\t\t\tType: operationType,\n\t\t\t\tObj: desiredObj,\n\t\t\t\tClusterName: clusterName,\n\t\t\t\tKey: key,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, clusterName := range unselectedClusters {\n\t\trawClusterObj, found, err := s.informer.GetTargetStore().GetByKey(clusterName, key)\n\t\tif err != nil {\n\t\t\twrappedErr := fmt.Errorf(\"Failed to get %s %q from cluster %q: %v\", targetKind, key, clusterName, err)\n\t\t\truntime.HandleError(wrappedErr)\n\t\t\treturn nil, wrappedErr\n\t\t}\n\t\tif found {\n\t\t\tclusterObj := rawClusterObj.(pkgruntime.Object)\n\t\t\t// This controller does not initiate deletion of namespaces in the host cluster.\n\t\t\tif targetKind == util.NamespaceKind && util.IsPrimaryCluster(template, clusterObj) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toperations = append(operations, util.FederatedOperation{\n\t\t\t\tType: util.OperationTypeDelete,\n\t\t\t\tObj: clusterObj,\n\t\t\t\tClusterName: clusterName,\n\t\t\t\tKey: key,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn operations, nil\n}", "func parseOperations(operationsJSON []byte) (operations []*HTTPOperation, batchMode bool, payloadErr error) {\n\t// there are two possible options for receiving information from a post request\n\t// the first is that the user provides an object in the form of { query, variables, operationName }\n\t// the second option is a list of that object\n\n\tsingleQuery := &HTTPOperation{}\n\t// if we were given a single object\n\tif err := json.Unmarshal(operationsJSON, &singleQuery); err == nil {\n\t\t// add it to the list of operations\n\t\toperations = append(operations, singleQuery)\n\t\t// we weren't given an object\n\t} else {\n\t\t// but we could have been given a list\n\t\tbatch := []*HTTPOperation{}\n\n\t\tif err = json.Unmarshal(operationsJSON, &batch); err != nil {\n\t\t\tpayloadErr = fmt.Errorf(\"encountered error parsing operationsJSON: %w\", err)\n\t\t} else {\n\t\t\toperations = batch\n\t\t}\n\n\t\t// we're in batch mode\n\t\tbatchMode = true\n\t}\n\n\treturn operations, batchMode, payloadErr\n}", "func (m *DeviceManagementRequestBuilder) ResourceOperations()(*i460ebd1d2d6c5576fc5e23bb59098a0eb4d16ebe0bf39c0b86508c13edbb1c20.ResourceOperationsRequestBuilder) {\n return i460ebd1d2d6c5576fc5e23bb59098a0eb4d16ebe0bf39c0b86508c13edbb1c20.NewResourceOperationsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *ManagedAppRegistrationItemRequestBuilder) Operations()(*i798793d33f3b0c4349f4a5beaee290369942f7f1d78a4207726bf30670bbf0d0.OperationsRequestBuilder) {\n return i798793d33f3b0c4349f4a5beaee290369942f7f1d78a4207726bf30670bbf0d0.NewOperationsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func Operations(bs []models.Operation) []*genModels.OperationsRow {\n\toperations := make([]*genModels.OperationsRow, len(bs))\n\tfor i := range bs {\n\t\toperations[i] = Operation(bs[i], bs[i].DoubleOperationEvidenceExtended)\n\t}\n\treturn operations\n}", "func (o *CatalogEntry) SetOperation(v string) {\n\to.Operation = &v\n}", "func NewOperationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *OperationsClient {\n\tcp := arm.ClientOptions{}\n\tif options != nil {\n\t\tcp = *options\n\t}\n\tif len(cp.Host) == 0 {\n\t\tcp.Host = arm.AzurePublicCloud\n\t}\n\treturn &OperationsClient{subscriptionID: subscriptionID, ep: string(cp.Host), pl: armruntime.NewPipeline(module, version, credential, &cp)}\n}", "func (ro *ResourceOperations) List(parameters *ResourceListParameters) (*ResourceListResult, *AzureOperationResponse, error) {\n\tsubscriptionId := getSubscriptionId(ro.c, nil)\n\n\tpath := \"/subscriptions/\" + url.QueryEscape(subscriptionId)\n\n\tif parameters != nil {\n\t\tif parameters.ResourceGroupName != \"\" {\n\t\t\tpath += \"/resourcegroups/\" + url.QueryEscape(parameters.ResourceGroupName)\n\t\t}\n\t}\n\n\tpath += \"/resources?api-version=\" + url.QueryEscape(ro.c.apiVersion)\n\n\tif parameters != nil {\n\t\tif parameters.Top != 0 {\n\t\t\tpath += \"&$top=\" + strconv.Itoa(parameters.Top)\n\t\t}\n\n\t\tfilter := \"\"\n\n\t\tif parameters.ResourceType != \"\" {\n\t\t\tfilter += url.QueryEscape(\"resourceType eq '\" + parameters.ResourceType + \"'\")\n\t\t}\n\n\t\tif parameters.TagValue != \"\" {\n\t\t\tif filter != \"\" {\n\t\t\t\tfilter += url.QueryEscape(\" and \")\n\t\t\t}\n\t\t\tfilter += url.QueryEscape(\"tagValue eq '\" + parameters.ResourceType + \"'\")\n\t\t}\n\n\t\tif filter != \"\" {\n\t\t\tpath += \"&filter=\" + filter\n\t\t}\n\t}\n\n\tvar result ResourceListResult\n\tazureOperationResponse, err := ro.c.DoGet(path, &result)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &result, azureOperationResponse, nil\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *Client) PreapplyOperations(input PreapplyOperationsInput) ([]Operations, error) {\n\terr := validator.New().Struct(input)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid input\")\n\t}\n\n\top, err := json.Marshal(input.Operations)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to preapply operation\")\n\t}\n\n\tresp, err := c.post(fmt.Sprintf(\"/chains/main/blocks/%s/helpers/preapply/operations\", input.Blockhash), op)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to preapply operation\")\n\t}\n\n\tvar operations []Operations\n\terr = json.Unmarshal(resp, &operations)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal operations\")\n\t}\n\n\treturn operations, nil\n}", "func (r *AppsOperationsService) List(appsId string) *AppsOperationsListCall {\n\tc := &AppsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.appsId = appsId\n\treturn c\n}", "func (volumeOpts *VolumeOpts) VolumeOperations(experiment *ExperimentDetails) {\n\tvolumeOpts.NewVolumeBuilder().\n\t\tBuildVolumeBuilderForConfigMaps(experiment.ConfigMaps).\n\t\tBuildVolumeBuilderForSecrets(experiment.Secrets).\n\t\tBuildVolumeBuilderForHostFileVolumes(experiment.HostFileVolumes)\n\n\tvolumeOpts.NewVolumeMounts().\n\t\tBuildVolumeMountsForConfigMaps(experiment.ConfigMaps).\n\t\tBuildVolumeMountsForSecrets(experiment.Secrets).\n\t\tBuildVolumeMountsForHostFileVolumes(experiment.HostFileVolumes)\n}", "func WithDefOps(defops map[string]spec.Operation) Option {\n\treturn func(r *Options) error {\n\t\tr.defops = defops\n\t\treturn nil\n\t}\n}", "func (samplerOptions) MaxOperations(maxOperations int) SamplerOption {\n\treturn func(o *samplerOptions) {\n\t\to.maxOperations = maxOperations\n\t}\n}", "func (o *ActionDTO) SetOperation(v string) {\n\to.Operation = &v\n}", "func NewMockContainerOperations() *MockContainerOperations {\n\treturn &MockContainerOperations{\n\t\tMockCreate: func(ctx context.Context, pat azblob.PublicAccessType, meta azblob.Metadata) error {\n\t\t\treturn nil\n\t\t},\n\t\tMockUpdate: func(ctx context.Context, pat azblob.PublicAccessType, meta azblob.Metadata) error {\n\t\t\treturn nil\n\t\t},\n\t\tMockGet: func(ctx context.Context) (*azblob.PublicAccessType, azblob.Metadata, error) {\n\t\t\treturn nil, nil, nil\n\t\t},\n\t\tMockDelete: func(ctx context.Context) error {\n\t\t\treturn nil\n\t\t},\n\t}\n}" ]
[ "0.7198802", "0.69220114", "0.66551083", "0.6605073", "0.6553442", "0.6553442", "0.6538797", "0.6449035", "0.6385875", "0.63704", "0.6315704", "0.6312198", "0.62994707", "0.61955124", "0.6192981", "0.6184774", "0.6169092", "0.61600715", "0.61439407", "0.6048", "0.6038706", "0.59916914", "0.59916914", "0.59502065", "0.59350616", "0.59078264", "0.5906391", "0.5851567", "0.58504426", "0.57288843", "0.57288843", "0.5709067", "0.5699432", "0.56625134", "0.5582858", "0.5548629", "0.55180675", "0.5505503", "0.5504762", "0.5496343", "0.5419692", "0.5384008", "0.5361094", "0.531633", "0.5305869", "0.5304028", "0.52268153", "0.51912636", "0.51692396", "0.51658744", "0.514806", "0.5133027", "0.5125535", "0.5114139", "0.5083026", "0.5058316", "0.50542235", "0.5053678", "0.50320953", "0.5026212", "0.5008497", "0.49966377", "0.49912274", "0.49475217", "0.4945654", "0.49323586", "0.4929312", "0.49226305", "0.49196285", "0.49145168", "0.49032548", "0.49032548", "0.4873781", "0.4867795", "0.4866852", "0.48423737", "0.48251337", "0.48232138", "0.47708502", "0.47581458", "0.47126257", "0.4702776", "0.46912098", "0.4690061", "0.4686394", "0.46848822", "0.46768227", "0.46759683", "0.46738216", "0.46738216", "0.46738216", "0.46738216", "0.46738216", "0.46328035", "0.46183482", "0.46121514", "0.46116492", "0.45959556", "0.45950624", "0.45936662" ]
0.8358397
0
SetSharepointIds sets the sharepointIds property value. Returns identifiers useful for SharePoint REST compatibility. Readonly.
SetSharepointIds задает значение свойства sharepointIds. Возвращает идентификаторы, полезные для совместимости с SharePoint REST. Только для чтения.
func (m *List) SetSharepointIds(value SharepointIdsable)() { m.sharepointIds = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *MicrosoftGraphListItem) SetSharepointIds(v AnyOfmicrosoftGraphSharepointIds) {\n\to.SharepointIds = &v\n}", "func (o *MicrosoftGraphItemReference) SetSharepointIds(v AnyOfmicrosoftGraphSharepointIds) {\n\to.SharepointIds = &v\n}", "func (m *Drive) SetSharePointIds(value SharepointIdsable)() {\n m.sharePointIds = value\n}", "func (o *MicrosoftGraphListItem) GetSharepointIds() AnyOfmicrosoftGraphSharepointIds {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret\n\t}\n\treturn *o.SharepointIds\n}", "func (o *MicrosoftGraphItemReference) GetSharepointIds() AnyOfmicrosoftGraphSharepointIds {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret\n\t}\n\treturn *o.SharepointIds\n}", "func (m *Drive) GetSharePointIds()(SharepointIdsable) {\n return m.sharePointIds\n}", "func NewSharepointIds()(*SharepointIds) {\n m := &SharepointIds{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (m *List) GetSharepointIds()(SharepointIdsable) {\n return m.sharepointIds\n}", "func (o *MicrosoftGraphListItem) HasSharepointIds() bool {\n\tif o != nil && o.SharepointIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *MicrosoftGraphItemReference) HasSharepointIds() bool {\n\tif o != nil && o.SharepointIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *SharepointIds) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"listId\", m.GetListId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"listItemId\", m.GetListItemId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"listItemUniqueId\", m.GetListItemUniqueId())\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.WriteStringValue(\"siteId\", m.GetSiteId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"siteUrl\", m.GetSiteUrl())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tenantId\", m.GetTenantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"webId\", m.GetWebId())\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}", "func (o *MicrosoftGraphItemReference) GetSharepointIdsOk() (AnyOfmicrosoftGraphSharepointIds, bool) {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret, false\n\t}\n\treturn *o.SharepointIds, true\n}", "func (o *MicrosoftGraphListItem) GetSharepointIdsOk() (AnyOfmicrosoftGraphSharepointIds, bool) {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret, false\n\t}\n\treturn *o.SharepointIds, true\n}", "func (m *DeviceManagementComplexSettingDefinition) SetPropertyDefinitionIds(value []string)() {\n err := m.GetBackingStore().Set(\"propertyDefinitionIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SharepointIds) SetListId(value *string)() {\n err := m.GetBackingStore().Set(\"listId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SharepointIds) SetListItemId(value *string)() {\n err := m.GetBackingStore().Set(\"listItemId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SharepointIds) SetSiteId(value *string)() {\n err := m.GetBackingStore().Set(\"siteId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *MicrosoftGraphItemReference) SetSharepointIdsExplicitNull(b bool) {\n\to.SharepointIds = nil\n\to.isExplicitNullSharepointIds = b\n}", "func (o *MicrosoftGraphListItem) SetSharepointIdsExplicitNull(b bool) {\n\to.SharepointIds = nil\n\to.isExplicitNullSharepointIds = b\n}", "func (m *SharepointIds) SetWebId(value *string)() {\n err := m.GetBackingStore().Set(\"webId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SharepointIds) SetListItemUniqueId(value *string)() {\n err := m.GetBackingStore().Set(\"listItemUniqueId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *PlacementsListCall) SiteIds(siteIds ...int64) *PlacementsListCall {\n\tvar siteIds_ []string\n\tfor _, v := range siteIds {\n\t\tsiteIds_ = append(siteIds_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"siteIds\", siteIds_)\n\treturn c\n}", "func (op *ListSharedAccessOp) FolderIds(val ...string) *ListSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"folder_ids\", strings.Join(val, \",\"))\n\t}\n\treturn op\n}", "func (m *PromotionMutation) SaleIDs() (ids []int) {\n\tif id := m.sale; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (m *UserMutation) SellsIDs() (ids []int) {\n\tfor id := range m.sells {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (c *PlacementGroupsListCall) SiteIds(siteIds ...int64) *PlacementGroupsListCall {\n\tvar siteIds_ []string\n\tfor _, v := range siteIds {\n\t\tsiteIds_ = append(siteIds_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"siteIds\", siteIds_)\n\treturn c\n}", "func (m *RiskyServicePrincipalsDismissPostRequestBody) SetServicePrincipalIds(value []string)() {\n err := m.GetBackingStore().Set(\"servicePrincipalIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *Workteam) SetProductListingIds(v []*string) *Workteam {\n\ts.ProductListingIds = v\n\treturn s\n}", "func (o *LineStatusByIdsParams) SetIds(ids []string) {\n\to.Ids = ids\n}", "func setSharelist(stub shim.ChaincodeStubInterface, args []string) pb.Response{\n\tvar err error\n\tfmt.Println(\"starting set_sharelist\")\n\n\tif len(args) !=3 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 3\")\n\t}\n\n\treceiptId := args[0]\n\townerId := args[1]\n\townerName := args[2]\n\n\t// get receipt's current state\n\treceiptAsBytes, err := stub.GetState(receiptId)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get Receipt\")\n\t}\n\tres := Receipt{}\n\tjson.Unmarshal(receiptAsBytes, &res)\n\n\towner := Owner{}\n\towner.Id = ownerId\n\towner.Username = ownerName\n\tres.ShareList = append(res.ShareList, owner)\n\n\tresAsBytes, _ := json.Marshal(res)\n\terr = stub.PutState(receiptId, resAsBytes)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"end set_sharelist\")\n\treturn shim.Success(nil)\n}", "func ShareLists(hrcSrvShare unsafe.Pointer, hrcSrvSource unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpShareLists, 2, uintptr(hrcSrvShare), uintptr(hrcSrvSource), 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func (m *ServicePrincipalRiskDetection) SetKeyIds(value []string)() {\n err := m.GetBackingStore().Set(\"keyIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *CampaignsListCall) Ids(ids ...int64) *CampaignsListCall {\n\tvar ids_ []string\n\tfor _, v := range ids {\n\t\tids_ = append(ids_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"ids\", ids_)\n\treturn c\n}", "func (s *ListAnnotationStoresInput) SetIds(v []*string) *ListAnnotationStoresInput {\n\ts.Ids = v\n\treturn s\n}", "func (o *ViewUserDashboard) SetDashboardSettingIds(v []int32) {\n\to.DashboardSettingIds = &v\n}", "func (options *CreateWorkspaceOptions) SetAppliedShareddataIds(appliedShareddataIds []string) *CreateWorkspaceOptions {\n\toptions.AppliedShareddataIds = appliedShareddataIds\n\treturn options\n}", "func (s *DescribeContinuousExportsInput) SetExportIds(v []*string) *DescribeContinuousExportsInput {\n\ts.ExportIds = v\n\treturn s\n}", "func (m *ItemTranslateExchangeIdsPostRequestBody) SetInputIds(value []string)() {\n err := m.GetBackingStore().Set(\"inputIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func CreateSharepointIdsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSharepointIds(), nil\n}", "func (s *DescribeExportTasksInput) SetExportIds(v []*string) *DescribeExportTasksInput {\n\ts.ExportIds = v\n\treturn s\n}", "func (s UserSet) SetPartnerShare(value bool) {\n\ts.RecordCollection.Set(models.NewFieldName(\"PartnerShare\", \"partner_share\"), value)\n}", "func SetRelatedIssueIDs(s *pb.Issue, ids string) error {\n\tif ids == \"\" {\n\t\treturn nil\n\t}\n\tidStrs := strings.Split(ids, \",\")\n\tdp := map[uint64]bool{}\n\trelatedIssueIDs := make([]uint64, 0)\n\tfor _, id := range idStrs {\n\t\tissueID, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif dp[uint64(issueID)] {\n\t\t\tcontinue\n\t\t}\n\t\tdp[uint64(issueID)] = true\n\t\trelatedIssueIDs = append(relatedIssueIDs, uint64(issueID))\n\t}\n\ts.RelatedIssueIDs = relatedIssueIDs\n\treturn nil\n}", "func (g *Group) SetToManyReferenceIDs(name string, IDs []string) error {\n\tif name == \"users\" {\n\t\tfor _, i := range IDs {\n\t\t\tj, err := strconv.ParseUint(i, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.UserIDs = append(g.UserIDs, uint(j))\n\t\t}\n\t}\n\n\treturn errors.New(\"There is no to-many relationship with the name \" + name)\n}", "func (fs *FakeSession) SetMany(pdus ...gosnmp.SnmpPDU) {\n\tfs.dirty = true\n\tfor _, pdu := range pdus {\n\t\tfs.data[pdu.Name] = pdu\n\t}\n}", "func (s *ListVariantStoresInput) SetIds(v []*string) *ListVariantStoresInput {\n\ts.Ids = v\n\treturn s\n}", "func (s *DescribeExportConfigurationsInput) SetExportIds(v []*string) *DescribeExportConfigurationsInput {\n\ts.ExportIds = v\n\treturn s\n}", "func SetIds(t *Task) {\n\tt.Id = str2md5(t.Name+t.Text)\n\t\n\tfor _, subTask := range t.SubTasks {\n\t\tSetIds(subTask)\n\t}\n}", "func (m *DeviceManagementConfigurationSettingGroupDefinition) SetChildIds(value []string)() {\n err := m.GetBackingStore().Set(\"childIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *ListAnnotationImportJobsInput) SetIds(v []*string) *ListAnnotationImportJobsInput {\n\ts.Ids = v\n\treturn s\n}", "func (o *MultiDeleteIssueAttachmentOfIssueParams) SetIds(ids string) {\n\to.Ids = ids\n}", "func (m *EntityMutation) SplitsIDs() (ids []int) {\n\tfor id := range m.splits {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (o *PostAPI24PoliciesNfsMembersParams) SetPolicyIds(policyIds []string) {\n\to.PolicyIds = policyIds\n}", "func (s *UpdateUserSecurityProfilesInput) SetSecurityProfileIds(v []*string) *UpdateUserSecurityProfilesInput {\n\ts.SecurityProfileIds = v\n\treturn s\n}", "func (s *ListAssociatedRoute53HealthChecksOutput) SetHealthCheckIds(v []*string) *ListAssociatedRoute53HealthChecksOutput {\n\ts.HealthCheckIds = v\n\treturn s\n}", "func (o *FiltersSecurityGroup) SetSecurityGroupIds(v []string) {\n\to.SecurityGroupIds = &v\n}", "func (o *MicrosoftGraphItemReference) HasShareId() bool {\n\tif o != nil && o.ShareId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s UserSet) SetShare(value bool) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Share\", \"share\"), value)\n}", "func (o *DeleteAPI24PoliciesSmbMembersParams) SetPolicyIds(policyIds []string) {\n\to.PolicyIds = policyIds\n}", "func (s *ListVariantImportJobsInput) SetIds(v []*string) *ListVariantImportJobsInput {\n\ts.Ids = v\n\treturn s\n}", "func (c *CitiesListCall) DartIds(dartIds ...int64) *CitiesListCall {\n\tvar dartIds_ []string\n\tfor _, v := range dartIds {\n\t\tdartIds_ = append(dartIds_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"dartIds\", dartIds_)\n\treturn c\n}", "func (m *UserMutation) SpouseIDs() (ids []int) {\n\tif id := m.spouse; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (op *ListSharedAccessOp) UserIds(val ...string) *ListSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"user_ids\", strings.Join(val, \",\"))\n\t}\n\treturn op\n}", "func (c *Client) FindReportPointOfSaleReportInvoiceIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(ReportPointOfSaleReportInvoiceModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (s *BatchDeleteReadSetInput) SetIds(v []*string) *BatchDeleteReadSetInput {\n\ts.Ids = v\n\treturn s\n}", "func (o *ViewUserDashboard) GetDashboardSettingIds() []int32 {\n\tif o == nil || o.DashboardSettingIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.DashboardSettingIds\n}", "func (o *ViewMilestone) GetTasklistIds() []int32 {\n\tif o == nil || o.TasklistIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.TasklistIds\n}", "func (o *SharedSecretSet3) SetSharedSecretSetId(v int32) {\n\to.SharedSecretSetId = v\n}", "func (c *PlacementsListCall) Ids(ids ...int64) *PlacementsListCall {\n\tvar ids_ []string\n\tfor _, v := range ids {\n\t\tids_ = append(ids_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"ids\", ids_)\n\treturn c\n}", "func (r *ListSLOsOptionalParameters) WithIds(ids string) *ListSLOsOptionalParameters {\n\tr.Ids = &ids\n\treturn r\n}", "func (m *BrowserSiteList) SetSharedCookies(value []BrowserSharedCookieable)() {\n err := m.GetBackingStore().Set(\"sharedCookies\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SharepointIds) SetSiteUrl(value *string)() {\n err := m.GetBackingStore().Set(\"siteUrl\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *FiltersNet) SetDhcpOptionsSetIds(v []string) {\n\to.DhcpOptionsSetIds = &v\n}", "func (s *UserSearchSummary) SetSecurityProfileIds(v []*string) *UserSearchSummary {\n\ts.SecurityProfileIds = v\n\treturn s\n}", "func (o *NiatelemetryNexusDashboardsAllOf) SetNumberOfSitesInMso(v int64) {\n\to.NumberOfSitesInMso = &v\n}", "func (o *MicrosoftGraphItemReference) SetShareId(v string) {\n\to.ShareId = &v\n}", "func (s *ResolverEndpoint) SetSecurityGroupIds(v []*string) *ResolverEndpoint {\n\ts.SecurityGroupIds = v\n\treturn s\n}", "func (s *ResolverEndpoint) SetSecurityGroupIds(v []*string) *ResolverEndpoint {\n\ts.SecurityGroupIds = v\n\treturn s\n}", "func (m *OrganizationMutation) StaffsIDs() (ids []int) {\n\tfor id := range m.staffs {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (o *ListResourceTypesUsingGET2Params) SetIds(ids []string) {\n\to.Ids = ids\n}", "func (s *DomainSettings) SetSecurityGroupIds(v []*string) *DomainSettings {\n\ts.SecurityGroupIds = v\n\treturn s\n}", "func getIds() []string {\n\tclient := &http.Client{}\n\tvar ids []string\n\tsongRequest, err := http.NewRequest(\"GET\", \"https://api.spotify.com/v1/me/tracks?limit=50&offset=0\", nil)\n\tsongRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(songRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\ttrack := gjson.Get(items.Array()[i].String(), \"track\")\n\t\t\tid := gjson.Get(track.String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\tids = append(ids, getPlaylistIds()...) // Calls to get song IDs from user playlists\n\treturn fixIds(ids)\n}", "func (o *ViewMilestone) SetTasklistIds(v []int32) {\n\to.TasklistIds = &v\n}", "func (m *Application) SetIdentifierUris(value []string)() {\n m.identifierUris = value\n}", "func (o *MicrosoftGraphItemReference) GetShareId() string {\n\tif o == nil || o.ShareId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ShareId\n}", "func (c *Client) FindReportSaleReportSaleproformaIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(ReportSaleReportSaleproformaModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (o *Ga4ghFeature) SetChildIds(v []string) {\n\to.ChildIds = &v\n}", "func (m *DeviceManagementComplexSettingDefinition) GetPropertyDefinitionIds()([]string) {\n val, err := m.GetBackingStore().Get(\"propertyDefinitionIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func (c *SitesListCall) Ids(ids ...int64) *SitesListCall {\n\tvar ids_ []string\n\tfor _, v := range ids {\n\t\tids_ = append(ids_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"ids\", ids_)\n\treturn c\n}", "func (s *NetworkSettings) SetSecurityGroupIds(v []*string) *NetworkSettings {\n\ts.SecurityGroupIds = v\n\treturn s\n}", "func (m *Map) SetMany(keys []string) {\n\tfor _, key := range keys {\n\t\tm.Set(key)\n\t}\n}", "func (s *CreateNetworkSettingsInput) SetSecurityGroupIds(v []*string) *CreateNetworkSettingsInput {\n\ts.SecurityGroupIds = v\n\treturn s\n}", "func (s *ListAppsInput) SetAppIds(v []*string) *ListAppsInput {\n\ts.AppIds = v\n\treturn s\n}", "func (s *UpdateNetworkSettingsInput) SetSecurityGroupIds(v []*string) *UpdateNetworkSettingsInput {\n\ts.SecurityGroupIds = v\n\treturn s\n}", "func (o *FileExtractOptions) SetVarsList(split string) *FileExtractOptions {\n\t// create empty map and header list\n\tm := map[string]Types{}\n\th := []string{}\n\n\t// construct map from split\n\tfields := strings.Split(split, \",\")\n\tif len(fields)%3 != 0 {\n\t\tlog.Fatalf(\"Check the pa list: %s, invalid number of parameters, not modulo 3\", split)\n\t}\n\tfor i := 0; i < len(fields); i += 3 {\n\t\tif v, err := strconv.Atoi(fields[i+1]); err == nil {\n\t\t\tm[fields[i]] = Types{column: v, types: fields[i+2]}\n\t\t\t//pf(\"%#v -> %#v\\n\", h, fields[i])\n\t\t\th = append(h, fields[i])\n\t\t} else {\n\t\t\tlog.Fatalf(\"Check the input of SetVars: [%v]: %v -> %v\\n\",\n\t\t\t\tfields[i], fields[i+1], err)\n\t\t}\n\t}\n\t// copy map and header list to FileExtractOptions object\n\to.varsList = m\n\to.hdr = h\n\treturn o\n}", "func (o LookupNetworkPacketCoreControlPlaneResultOutput) SiteIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupNetworkPacketCoreControlPlaneResult) []string { return v.SiteIds }).(pulumi.StringArrayOutput)\n}", "func (c *Client) FindSaleReportIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(SaleReportModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (o *InlineResponse2002) SetSecrets(v []Secret) {\n\to.Secrets = &v\n}", "func (m *BrowserSiteList) SetSites(value []BrowserSiteable)() {\n err := m.GetBackingStore().Set(\"sites\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *User) SetIdentities(value []ObjectIdentityable)() {\n m.identities = value\n}", "func autoShareNonSharedItems(svcs *services.APIServices, ids viewStateReferencedIDs, datasetID string, userID string) (map[string]string, error) {\n\tidRemap := map[string]string{}\n\n\tunsharedROIIDs := []string{}\n\tunsharedExpressionIDs := []string{}\n\tunsharedRGBMixIDs := []string{}\n\n\tfor _, item := range ids.ROIs {\n\t\tif !strings.HasPrefix(item.ID, utils.SharedItemIDPrefix) && !checkIsBuiltinID(item.ID) {\n\t\t\tunsharedROIIDs = append(unsharedROIIDs, item.ID)\n\t\t}\n\t}\n\n\tfor _, item := range ids.Expressions {\n\t\tif !strings.HasPrefix(item.ID, utils.SharedItemIDPrefix) {\n\t\t\tunsharedExpressionIDs = append(unsharedExpressionIDs, item.ID)\n\t\t}\n\t}\n\n\tfor _, item := range ids.RGBMixes {\n\t\tif !strings.HasPrefix(item.ID, utils.SharedItemIDPrefix) && !checkIsBuiltinID(item.ID) {\n\t\t\tunsharedRGBMixIDs = append(unsharedRGBMixIDs, item.ID)\n\t\t}\n\t}\n\n\tnewIDs, err := roiModel.ShareROIs(svcs, userID, datasetID, unsharedROIIDs)\n\tif err != nil {\n\t\treturn idRemap, err\n\t}\n\n\tfor idx, id := range newIDs {\n\t\tidRemap[unsharedROIIDs[idx]] = utils.SharedItemIDPrefix + id\n\t}\n\n\tnewIDs, err = shareExpressions(svcs, userID, unsharedExpressionIDs)\n\tif err != nil {\n\t\treturn idRemap, err\n\t}\n\n\tfor idx, id := range newIDs {\n\t\tidRemap[unsharedExpressionIDs[idx]] = utils.SharedItemIDPrefix + id\n\t}\n\n\tnewIDs, err = shareRGBMixes(svcs, userID, unsharedRGBMixIDs)\n\tif err != nil {\n\t\treturn idRemap, err\n\t}\n\n\tfor idx, id := range newIDs {\n\t\tidRemap[unsharedRGBMixIDs[idx]] = utils.SharedItemIDPrefix + id\n\t}\n\n\tif !strings.HasPrefix(ids.Quant.ID, utils.SharedItemIDPrefix) {\n\t\terr := quantModel.ShareQuantification(svcs, userID, datasetID, ids.Quant.ID)\n\t\tif err != nil {\n\t\t\treturn idRemap, err\n\t\t}\n\n\t\tidRemap[ids.Quant.ID] = utils.SharedItemIDPrefix + ids.Quant.ID\n\t}\n\n\treturn idRemap, nil\n}" ]
[ "0.7952072", "0.7934823", "0.77746314", "0.75141704", "0.750047", "0.6807269", "0.6786915", "0.67614096", "0.6590971", "0.63483787", "0.6196856", "0.5963558", "0.59606564", "0.57671094", "0.556037", "0.544962", "0.5333266", "0.53018636", "0.5215398", "0.51930815", "0.5125199", "0.5022773", "0.50168025", "0.4959874", "0.49152353", "0.48647487", "0.4863367", "0.4859065", "0.4845201", "0.4816858", "0.47790456", "0.47758454", "0.47465402", "0.46984378", "0.46431243", "0.46319988", "0.45965332", "0.45878696", "0.45855054", "0.45827386", "0.45821035", "0.45641804", "0.45565173", "0.45538288", "0.45500764", "0.45444208", "0.45277923", "0.45017678", "0.44696847", "0.4465542", "0.44641575", "0.44557047", "0.44535625", "0.4443475", "0.44166142", "0.44074148", "0.4395864", "0.43885505", "0.43883216", "0.4373918", "0.43710598", "0.43703315", "0.43661264", "0.4358669", "0.43545282", "0.43510404", "0.43503535", "0.43398732", "0.43272105", "0.43262964", "0.43242162", "0.4321018", "0.43078288", "0.42986473", "0.4294372", "0.4280316", "0.4280316", "0.4271821", "0.4251278", "0.42498794", "0.42495078", "0.42447397", "0.4243656", "0.42403555", "0.42367345", "0.4235797", "0.422462", "0.42233047", "0.4222446", "0.42207748", "0.42202136", "0.42182797", "0.42136526", "0.42104796", "0.42063132", "0.41898543", "0.418886", "0.4187511", "0.41860083", "0.41769257" ]
0.8109699
0
SetSubscriptions sets the subscriptions property value. The set of subscriptions on the list.
SetSubscriptions задает значение свойства subscriptions. Сет subscriptions на списке.
func (m *List) SetSubscriptions(value []Subscriptionable)() { m.subscriptions = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockSessionMockRecorder) SetSubscriptions(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetSubscriptions\", reflect.TypeOf((*MockSession)(nil).SetSubscriptions), arg0)\n}", "func (m *MockSession) SetSubscriptions(arg0 []*nats.Subscription) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetSubscriptions\", arg0)\n}", "func (r *ProjectsLocationsDataExchangesService) ListSubscriptions(resource string) *ProjectsLocationsDataExchangesListSubscriptionsCall {\n\tc := &ProjectsLocationsDataExchangesListSubscriptionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\treturn c\n}", "func (r *ProjectsLocationsDataExchangesListingsService) ListSubscriptions(resource string) *ProjectsLocationsDataExchangesListingsListSubscriptionsCall {\n\tc := &ProjectsLocationsDataExchangesListingsListSubscriptionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\treturn c\n}", "func (m *GraphBaseServiceClient) Subscriptions()(*idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.SubscriptionsRequestBuilder) {\n return idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.NewSubscriptionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Subscriptions()(*idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.SubscriptionsRequestBuilder) {\n return idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.NewSubscriptionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\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 (r *SubscriptionsService) List() *SubscriptionsListCall {\n\tc := &SubscriptionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}", "func (client *Client) Subscriptions() (*Subscriptions, error) {\n\tsubscriptions := new(Subscriptions)\n\tif err := client.apiGet(MARATHON_API_SUBSCRIPTION, nil, subscriptions); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn subscriptions, nil\n\t}\n}", "func (svc *SubscriptionService) GetSubscriptions(params *param.GetParams) ([]*nimbleos.Subscription, error) {\n\tsubscriptionResp, err := svc.objectSet.GetObjectListFromParams(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn subscriptionResp, nil\n}", "func (m *SubscriptionManager) Subscriptions() graphqlws.Subscriptions {\n\treturn m.inner.Subscriptions()\n}", "func (c *Client) Subscriptions(ctx context.Context) *SubscriptionIterator {\n\treturn &SubscriptionIterator{c.Client.Subscriptions(ctx), c.projectID, c.sensor}\n}", "func SetServerSubscription(s []string) func(*Server) error {\n\treturn func(c *Server) error {\n\t\tif s != nil {\n\t\t\tfor _, d := range s {\n\t\t\t\tc.subscriptionURLs = append(c.subscriptionURLs, d)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tc.subscriptionURLs = append(c.subscriptionURLs, \"http://joajgazyztfssty4w2on5oaqksz6tqoxbduy553y34mf4byv6gpq.b32.i2p/export/alive-hosts.txt\")\n\t\treturn nil\n\t}\n}", "func ListSubscriptions(db bun.IDB, offset, limit uint32) ([]*domain.Subscription, error) {\n\tmodel := []Subscription{}\n\n\tif err := db.NewSelect().Model(&model).Scan(context.Background()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := []*domain.Subscription{}\n\n\tfor _, subscription := range model {\n\t\tres = append(res, &domain.Subscription{\n\t\t\tPK: subscription.PK,\n\t\t\tSubscriberPK: subscription.SubscriberPK,\n\t\t\tListPK: subscription.ListPK,\n\t\t\tEmailAddress: domain.EmailAddress(subscription.EmailAddress),\n\t\t\tData: subscription.Data,\n\t\t\tVersion: subscription.Version,\n\t\t})\n\t}\n\n\treturn res, nil\n}", "func (s *T) Subscriptions() <-chan map[string][]string {\n\treturn s.subscriptionsCh\n}", "func (client *ClientImpl) ListSubscriptions(ctx context.Context, args ListSubscriptionsArgs) (*[]Subscription, error) {\n\tqueryParams := url.Values{}\n\tif args.PublisherId != nil {\n\t\tqueryParams.Add(\"publisherId\", *args.PublisherId)\n\t}\n\tif args.EventType != nil {\n\t\tqueryParams.Add(\"eventType\", *args.EventType)\n\t}\n\tif args.ConsumerId != nil {\n\t\tqueryParams.Add(\"consumerId\", *args.ConsumerId)\n\t}\n\tif args.ConsumerActionId != nil {\n\t\tqueryParams.Add(\"consumerActionId\", *args.ConsumerActionId)\n\t}\n\tlocationId, _ := uuid.Parse(\"fc50d02a-849f-41fb-8af1-0a5216103269\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.1\", nil, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []Subscription\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (r *SubscriptionsService) List() *SubscriptionsListCall {\n\treturn &SubscriptionsListCall{\n\t\ts: r.s,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"subscriptions\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}", "func (c *Client) ListSubscriptions(namespace string) (*v1alpha1.SubscriptionList, error) {\n\tif err := c.initClient(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubscriptionList := &v1alpha1.SubscriptionList{}\n\tif err := c.crClient.List(\n\t\tcontext.TODO(),\n\t\tsubscriptionList,\n\t\t&client.ListOptions{\n\t\t\tNamespace: namespace,\n\t\t},\n\t); err != nil {\n\t\treturn subscriptionList, err\n\t}\n\treturn subscriptionList, nil\n}", "func (a *StreamsApiService) UpdateSubscriptions(ctx _context.Context) ApiUpdateSubscriptionsRequest {\n\treturn ApiUpdateSubscriptionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (client NotificationDataPlaneClient) ListSubscriptions(ctx context.Context, request ListSubscriptionsRequest) (response ListSubscriptionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listSubscriptions, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tresponse = ListSubscriptionsResponse{RawResponse: ociResponse.HTTPResponse()}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListSubscriptionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListSubscriptionsResponse\")\n\t}\n\treturn\n}", "func (sns *SNS) ListSubscriptions(NextToken *string) (resp *ListSubscriptionsResp, err error) {\n\tresp = &ListSubscriptionsResp{}\n\tparams := makeParams(\"ListSubscriptions\")\n\tif NextToken != nil {\n\t\tparams[\"NextToken\"] = *NextToken\n\t}\n\terr = sns.query(params, resp)\n\treturn\n}", "func (c *Client) Subscriptions() []string {\n\tresult := []string{}\n\tfor subscription, subscriber := range c.subscriptions {\n\t\tif subscriber != nil {\n\t\t\tresult = append(result, subscription)\n\t\t}\n\t}\n\treturn result\n}", "func (s *CreateNotificationInput) SetSubscribers(v []*Subscriber) *CreateNotificationInput {\n\ts.Subscribers = v\n\treturn s\n}", "func (d *DatastoreSubscription) Set(sub *Subscription) error {\n\tv, err := datastore.EncodeGob(sub)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to encode gob\")\n\t}\n\treturn d.store.Set(d.prefix(sub.Name), v)\n}", "func (eventNotifications *EventNotificationsV1) ListSubscriptions(listSubscriptionsOptions *ListSubscriptionsOptions) (result *SubscriptionList, response *core.DetailedResponse, err error) {\n\treturn eventNotifications.ListSubscriptionsWithContext(context.Background(), listSubscriptionsOptions)\n}", "func UpdateSubscriptions(c client.Client, cfg *osdUpgradeConfig, scaler scaler.Scaler, dsb drain.NodeDrainStrategyBuilder, metricsClient metrics.Metrics, m maintenance.Maintenance, cvClient cv.ClusterVersion, nc eventmanager.EventManager, upgradeConfig *upgradev1alpha1.UpgradeConfig, machinery machinery.Machinery, availabilityCheckers ac.AvailabilityCheckers, logger logr.Logger) (bool, error) {\n\tfor _, item := range upgradeConfig.Spec.SubscriptionUpdates {\n\t\tsub := &operatorv1alpha1.Subscription{}\n\t\terr := c.Get(context.TODO(), types.NamespacedName{Namespace: item.Namespace, Name: item.Name}, sub)\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\tlogger.Info(\"subscription :%s in namespace %s not exists, do not need update\")\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tif sub.Spec.Channel != item.Channel {\n\t\t\tsub.Spec.Channel = item.Channel\n\t\t\terr = c.Update(context.TODO(), sub)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true, nil\n}", "func (m *List) GetSubscriptions()([]Subscriptionable) {\n return m.subscriptions\n}", "func (m *SubscriptionManager) RemoveSubscriptions(conn graphqlws.Connection) {\n\tfor _, sub := range m.Subscriptions()[conn] {\n\t\tm.removeSub(conn, sub)\n\t}\n\tm.inner.RemoveSubscriptions(conn)\n}", "func (s *server) ListTopicSubscriptions(ctx context.Context, in *empty.Empty) (*pb.ListTopicSubscriptionsResponse, error) {\n\treturn &pb.ListTopicSubscriptionsResponse{\n\t\tSubscriptions: []*pb.TopicSubscription{\n\t\t\t{Topic: \"TopicA\"},\n\t\t},\n\t}, nil\n}", "func (w *AuthWorker) Subscriptions() []*worker.Subscription {\n\treturn make([]*worker.Subscription, 0)\n}", "func (s *API) ListSubscriptions(status SubscriptionStatus) (data SubscriptionsResponse, err error) {\n\tif status == \"\" {\n\t\tstatus = SubscriptionStatusAll\n\t}\n\tendpoint := zoho.Endpoint{\n\t\tName: \"subscriptions\",\n\t\tURL: fmt.Sprintf(\"https://subscriptions.zoho.%s/api/v1/subscriptions\", s.ZohoTLD),\n\t\tMethod: zoho.HTTPGet,\n\t\tResponseData: &SubscriptionsResponse{},\n\t\tURLParameters: map[string]zoho.Parameter{\n\t\t\t\"filter_by\": zoho.Parameter(status),\n\t\t},\n\t\tHeaders: map[string]string{\n\t\t\tZohoSubscriptionsEndpointHeader: s.OrganizationID,\n\t\t},\n\t}\n\n\terr = s.Zoho.HTTPRequest(&endpoint)\n\tif err != nil {\n\t\treturn SubscriptionsResponse{}, fmt.Errorf(\"Failed to retrieve subscriptions: %s\", err)\n\t}\n\n\tif v, ok := endpoint.ResponseData.(*SubscriptionsResponse); ok {\n\t\treturn *v, nil\n\t}\n\n\treturn SubscriptionsResponse{}, fmt.Errorf(\"Data retrieved was not 'SubscriptionsResponse'\")\n}", "func (o *ClusterAuthorizationResponse) SetSubscription(v ObjectReference) {\n\to.Subscription = &v\n}", "func (s *ListSubscribersOutput) SetSubscribers(v []*SubscriberResource) *ListSubscribersOutput {\n\ts.Subscribers = v\n\treturn s\n}", "func (s *SubscriptionsSupervisor) UpdateSubscriptions(ctx context.Context, channel *messagingv1beta1.Channel, isFinalizer bool) (map[eventingduck.SubscriberSpec]error, error) {\n\ts.subscriptionsMux.Lock()\n\tdefer s.subscriptionsMux.Unlock()\n\n\tfailedToSubscribe := make(map[eventingduck.SubscriberSpec]error)\n\tcRef := eventingchannels.ChannelReference{Namespace: channel.Namespace, Name: channel.Name}\n\ts.logger.Info(\"Update subscriptions\", zap.String(\"cRef\", cRef.String()), zap.String(\"subscribable\", fmt.Sprintf(\"%v\", channel)), zap.Bool(\"isFinalizer\", isFinalizer))\n\tif channel.Spec.Subscribers == nil || isFinalizer {\n\t\ts.logger.Sugar().Infof(\"Empty subscriptions for channel Ref: %v; unsubscribe all active subscriptions, if any\", cRef)\n\t\tchMap, ok := s.subscriptions[cRef]\n\t\tif !ok {\n\t\t\t// nothing to do\n\t\t\ts.logger.Sugar().Infof(\"No channel Ref %v found in subscriptions map\", cRef)\n\t\t\treturn failedToSubscribe, nil\n\t\t}\n\t\tfor sub := range chMap {\n\t\t\ts.logger.Error(\"unsubscribe\", zap.Error(s.unsubscribe(cRef, sub)))\n\t\t}\n\t\tdelete(s.subscriptions, cRef)\n\t\treturn failedToSubscribe, nil\n\t}\n\n\tsubscriptions := channel.Spec.Subscribers\n\tactiveSubs := make(map[types.UID]bool) // it's logically a set\n\n\tchMap, ok := s.subscriptions[cRef]\n\tif !ok {\n\t\tchMap = make(map[types.UID]*stan.Subscription)\n\t\ts.subscriptions[cRef] = chMap\n\t}\n\n\tfor _, sub := range subscriptions {\n\t\t// check if the subscription already exist and do nothing in this case\n\t\tsubRef := newSubscriptionReference(sub)\n\t\tif _, ok := chMap[subRef.UID]; ok {\n\t\t\tactiveSubs[subRef.UID] = true\n\t\t\ts.logger.Sugar().Infof(\"Subscription: %v already active for channel: %v\", sub, cRef)\n\t\t\tcontinue\n\t\t}\n\t\t// subscribe and update failedSubscription if subscribe fails\n\t\tnatssSub, err := s.subscribe(ctx, cRef, subRef)\n\t\tif err != nil {\n\t\t\ts.logger.Sugar().Errorf(\"failed to subscribe (subscription:%q) to channel: %v. Error:%s\", sub, cRef, err.Error())\n\n\t\t\tsubv1alpha1 := newSubscriptionReference(sub)\n\t\t\tfailedToSubscribe[eventingduck.SubscriberSpec(subv1alpha1)] = err\n\t\t\tcontinue\n\t\t}\n\t\tchMap[subRef.UID] = natssSub\n\t\tactiveSubs[subRef.UID] = true\n\t}\n\t// Unsubscribe for deleted subscriptions\n\tfor sub := range chMap {\n\t\tif ok := activeSubs[sub]; !ok {\n\t\t\ts.logger.Error(\"unsubscribe\", zap.Error(s.unsubscribe(cRef, sub)))\n\t\t}\n\t}\n\t// delete the channel from s.subscriptions if chMap is empty\n\tif len(s.subscriptions[cRef]) == 0 {\n\t\tdelete(s.subscriptions, cRef)\n\t}\n\treturn failedToSubscribe, nil\n}", "func (mr *MockIApiMockRecorder) ListSubscriptions(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListSubscriptions\", reflect.TypeOf((*MockIApi)(nil).ListSubscriptions), arg0, arg1)\n}", "func (s *NotificationWithSubscribers) SetSubscribers(v []*Subscriber) *NotificationWithSubscribers {\n\ts.Subscribers = v\n\treturn s\n}", "func (m *MockIApi) ListSubscriptions(arg0 *chartmogul.Cursor, arg1 string) (*chartmogul.Subscriptions, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListSubscriptions\", arg0, arg1)\n\tret0, _ := ret[0].(*chartmogul.Subscriptions)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (ss *SubscriptionsService) List(ctx context.Context, cID string, opts *SubscriptionListOptions) (\n\tres *Response,\n\tsl *SubscriptionList,\n\terr error,\n) {\n\tu := fmt.Sprintf(\"v2/customers/%s/subscriptions\", cID)\n\n\tres, err = ss.list(ctx, u, opts)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &sl); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *conn) Subscriptions() map[int]*Subscription {\n\treturn c.subcriptions\n}", "func (m *MockISubscription) ListSubscriptions(userID uint) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListSubscriptions\", userID)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Client) GetSubscriptions(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET SUBSCRIPTIONS ==========\")\n\turl := buildURL(path[\"subscriptions\"])\n\n\treturn c.do(\"GET\", url, \"\", queryParams)\n}", "func (m *subscriptionMigrator) populateSubscriptions(namespaces []string) error {\n\tvar kymaSubscriptions []kymaeventingv1alpha1.Subscription\n\n\tfor _, ns := range namespaces {\n\t\tsubs, err := m.kymaClient.EventingV1alpha1().Subscriptions(ns).List(metav1.ListOptions{})\n\t\tswitch {\n\t\tcase apierrors.IsNotFound(err):\n\t\t\treturn NewTypeNotFoundError(err.(*apierrors.StatusError).ErrStatus.Details.Kind)\n\t\tcase err != nil:\n\t\t\treturn errors.Wrapf(err, \"listing Subscriptions in namespace %s\", ns)\n\t\t}\n\t\tkymaSubscriptions = append(kymaSubscriptions, subs.Items...)\n\t}\n\n\tm.subscriptions = kymaSubscriptions\n\n\treturn nil\n}", "func (c *Client) Subscriptions() map[string]*Subscription {\n\tsubs := make(map[string]*Subscription)\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tfor k, v := range c.subs {\n\t\tsubs[k] = v\n\t}\n\treturn subs\n}", "func (a Accessor) GetSubscriptionList(service, servicePath string, subscriptions *[]Subscription) error {\n\treturn a.access(&AccessParameter{\n\t\tEpID: EntryPointIDs.Subscriptions,\n\t\tMethod: gohttp.HttpMethods.GET,\n\t\tService: service,\n\t\tServicePath: servicePath,\n\t\tPath: \"\",\n\t\tReceivedBody: subscriptions,\n\t})\n}", "func (client NotificationDataPlaneClient) listSubscriptions(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/subscriptions\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListSubscriptionsResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (s *MemoryStore) Subscriptions() []subscription.Subscription {\n\ts.subsMux.RLock()\n\tdefer s.subsMux.RUnlock()\n\n\tsubs := make([]subscription.Subscription, 0, len(s.subscriptions))\n\tfor _, sub := range s.subscriptions {\n\t\tsubs = append(subs, sub)\n\t}\n\treturn subs\n}", "func (m *MockDB) ListSubscriptions(userID uint) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListSubscriptions\", userID)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *DescribeSubscribersForNotificationOutput) SetSubscribers(v []*Subscriber) *DescribeSubscribersForNotificationOutput {\n\ts.Subscribers = v\n\treturn s\n}", "func (o GetTopicSubscriptionsResultOutput) Subscriptions() GetTopicSubscriptionsSubscriptionArrayOutput {\n\treturn o.ApplyT(func(v GetTopicSubscriptionsResult) []GetTopicSubscriptionsSubscription { return v.Subscriptions }).(GetTopicSubscriptionsSubscriptionArrayOutput)\n}", "func (ac *Client) NewListSubscriptionsPager(topicName string, options *ListSubscriptionsOptions) *runtime.Pager[ListSubscriptionsResponse] {\n\tvar pageSize int32\n\n\tif options != nil {\n\t\tpageSize = options.MaxPageSize\n\t}\n\n\tep := &entityPager[atom.SubscriptionFeed, atom.SubscriptionEnvelope, SubscriptionPropertiesItem]{\n\t\tconvertFn: func(env *atom.SubscriptionEnvelope) (*SubscriptionPropertiesItem, error) {\n\t\t\treturn newSubscriptionItem(env, topicName)\n\t\t},\n\t\tbaseFragment: fmt.Sprintf(\"/%s/Subscriptions?\", topicName),\n\t\tmaxPageSize: pageSize,\n\t\tem: ac.em,\n\t}\n\n\treturn runtime.NewPager(runtime.PagingHandler[ListSubscriptionsResponse]{\n\t\tMore: func(ltr ListSubscriptionsResponse) bool {\n\t\t\treturn ep.More()\n\t\t},\n\t\tFetcher: func(ctx context.Context, t *ListSubscriptionsResponse) (ListSubscriptionsResponse, error) {\n\t\t\titems, err := ep.Fetcher(ctx)\n\n\t\t\tif err != nil {\n\t\t\t\treturn ListSubscriptionsResponse{}, err\n\t\t\t}\n\n\t\t\treturn ListSubscriptionsResponse{\n\t\t\t\tSubscriptions: items,\n\t\t\t}, nil\n\t\t},\n\t})\n}", "func (o UserDefinedResourcesPropertiesResponseOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v UserDefinedResourcesPropertiesResponse) []string { return v.QuerySubscriptions }).(pulumi.StringArrayOutput)\n}", "func (eventNotifications *EventNotificationsV1) ListSubscriptionsWithContext(ctx context.Context, listSubscriptionsOptions *ListSubscriptionsOptions) (result *SubscriptionList, response *core.DetailedResponse, err error) {\n\terr = core.ValidateNotNil(listSubscriptionsOptions, \"listSubscriptionsOptions cannot be nil\")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.ValidateStruct(listSubscriptionsOptions, \"listSubscriptionsOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpathParamsMap := map[string]string{\n\t\t\"instance_id\": *listSubscriptionsOptions.InstanceID,\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = eventNotifications.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(eventNotifications.Service.Options.URL, `/v1/instances/{instance_id}/subscriptions`, pathParamsMap)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listSubscriptionsOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"event_notifications\", \"V1\", \"ListSubscriptions\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\tif listSubscriptionsOptions.Offset != nil {\n\t\tbuilder.AddQuery(\"offset\", fmt.Sprint(*listSubscriptionsOptions.Offset))\n\t}\n\tif listSubscriptionsOptions.Limit != nil {\n\t\tbuilder.AddQuery(\"limit\", fmt.Sprint(*listSubscriptionsOptions.Limit))\n\t}\n\tif listSubscriptionsOptions.Search != nil {\n\t\tbuilder.AddQuery(\"search\", fmt.Sprint(*listSubscriptionsOptions.Search))\n\t}\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = eventNotifications.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalSubscriptionList)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func (this *mxTopics) Subscribers(topic []byte, qos byte, subs *[]interface{}, qoss *[]byte) error {\n\tif !message.ValidQos(qos) {\n\t\treturn fmt.Errorf(\"Invalid QoS %d\", qos)\n\t}\n\n\tthis.smu.RLock()\n\t(*subs)[0] = this.subscriber[string(topic)]\n\tthis.smu.RUnlock()\n\t// *qoss = (*qoss)[0:0]\n\treturn nil\n}", "func (prefs *UserPreferences) ChannelSubscriptions() ([]string, error) {\n\tvar subs []string\n\tif prefs.ChannelSubs != nil {\n\t\tif err := json.Unmarshal(prefs.ChannelSubs, &subs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn subs, nil\n}", "func (s *Simple) Subscriptions() []plugin.Subscription {\n\treturn []plugin.Subscription{\n\t\tplugin.Subscription{\n\t\t\tEventType: event.SystemEventReceivedType,\n\t\t\tType: plugin.Sync,\n\t\t},\n\t}\n}", "func (m *MockSession) GetSubscriptions() []*nats.Subscription {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\")\n\tret0, _ := ret[0].([]*nats.Subscription)\n\treturn ret0\n}", "func (c *PublisherClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest) *StringIterator {\n\tctx = metadata.NewContext(ctx, c.metadata)\n\tit := &StringIterator{}\n\tit.apiCall = func() error {\n\t\tvar resp *pubsubpb.ListTopicSubscriptionsResponse\n\t\terr := gax.Invoke(ctx, func(ctx context.Context) error {\n\t\t\tvar err error\n\t\t\treq.PageToken = it.nextPageToken\n\t\t\treq.PageSize = it.pageSize\n\t\t\tresp, err = c.client.ListTopicSubscriptions(ctx, req)\n\t\t\treturn err\n\t\t}, c.CallOptions.ListTopicSubscriptions...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif resp.NextPageToken == \"\" {\n\t\t\tit.atLastPage = true\n\t\t}\n\t\tit.nextPageToken = resp.NextPageToken\n\t\tit.items = resp.Subscriptions\n\t\treturn nil\n\t}\n\treturn it\n}", "func (r *SubscriptionsListServerResponse) Items(value *SubscriptionList) *SubscriptionsListServerResponse {\n\tr.items = value\n\treturn r\n}", "func (r *SubscriptionsService) Get(subscription string) *SubscriptionsGetCall {\n\tc := &SubscriptionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.subscription = subscription\n\treturn c\n}", "func (mr *MockISubscriptionMockRecorder) ListSubscriptions(userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListSubscriptions\", reflect.TypeOf((*MockISubscription)(nil).ListSubscriptions), userID)\n}", "func (o UserDefinedResourcesPropertiesOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v UserDefinedResourcesProperties) []string { return v.QuerySubscriptions }).(pulumi.StringArrayOutput)\n}", "func (c *NATSTestClient) HasSubscriptions(t *testing.T, rids ...string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tif len(rids) != len(c.subs) {\n\t\tt.Errorf(\"expected %d subscription, found %d\", len(rids), len(c.subs))\n\t}\n\n\tfor _, rid := range rids {\n\t\tif _, ok := c.subs[\"event.\"+rid]; !ok {\n\t\t\tt.Fatalf(\"expected subscription for event.%s.* not found\", rid)\n\t\t}\n\t}\n\n\tif len(rids) != len(c.subs) {\n\tnext:\n\t\tfor ns := range c.subs {\n\t\t\tfor _, rid := range rids {\n\t\t\t\tif ns == \"event.\"+rid {\n\t\t\t\t\tcontinue next\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.Fatalf(\"expected no subscription for %s.*, but found one\", ns)\n\t\t}\n\t}\n}", "func (client BaseClient) ListSubscriptionPlans(ctx context.Context, subscriptionID uuid.UUID, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.ListSubscriptionPlans\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.ListSubscriptionPlansPreparer(ctx, subscriptionID, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"ListSubscriptionPlans\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.ListSubscriptionPlansSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"ListSubscriptionPlans\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.ListSubscriptionPlansResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"ListSubscriptionPlans\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (c *DefaultApiService) ListSubscription(params *ListSubscriptionParams) (*ListSubscriptionResponse, error) {\n\tpath := \"/v1/Subscriptions\"\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.SinkSid != nil {\n\t\tdata.Set(\"SinkSid\", *params.SinkSid)\n\t}\n\tif params != nil && params.PageSize != nil {\n\t\tdata.Set(\"PageSize\", fmt.Sprint(*params.PageSize))\n\t}\n\n\tresp, err := c.requestHandler.Get(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &ListSubscriptionResponse{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\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 (mr *MockDBMockRecorder) ListSubscriptions(userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListSubscriptions\", reflect.TypeOf((*MockDB)(nil).ListSubscriptions), userID)\n}", "func (in *SubscriptionList) DeepCopy() *SubscriptionList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionList) DeepCopy() *SubscriptionList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (d *DatastoreSubscription) List() ([]*Subscription, error) {\n\treturn d.collectByField(func(s *Subscription) bool {\n\t\treturn true\n\t})\n}", "func (k *Kraken) GetSubscriptions() ([]wshandler.WebsocketChannelSubscription, error) {\n\treturn k.Websocket.GetSubscriptions(), nil\n}", "func (o UserDefinedResourcesPropertiesResponsePtrOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *UserDefinedResourcesPropertiesResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QuerySubscriptions\n\t}).(pulumi.StringArrayOutput)\n}", "func (g *Gemini) Subscribe(channelsToSubscribe []stream.ChannelSubscription) error {\n\tchannels := make([]string, 0, len(channelsToSubscribe))\n\tfor x := range channelsToSubscribe {\n\t\tif common.StringDataCompareInsensitive(channels, channelsToSubscribe[x].Channel) {\n\t\t\tcontinue\n\t\t}\n\t\tchannels = append(channels, channelsToSubscribe[x].Channel)\n\t}\n\n\tvar pairs currency.Pairs\n\tfor x := range channelsToSubscribe {\n\t\tif pairs.Contains(channelsToSubscribe[x].Currency, true) {\n\t\t\tcontinue\n\t\t}\n\t\tpairs = append(pairs, channelsToSubscribe[x].Currency)\n\t}\n\n\tfmtPairs, err := g.FormatExchangeCurrencies(pairs, asset.Spot)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsubs := make([]wsSubscriptions, len(channels))\n\tfor x := range channels {\n\t\tsubs[x] = wsSubscriptions{\n\t\t\tName: channels[x],\n\t\t\tSymbols: strings.Split(fmtPairs, \",\"),\n\t\t}\n\t}\n\n\twsSub := wsSubscribeRequest{\n\t\tType: \"subscribe\",\n\t\tSubscriptions: subs,\n\t}\n\terr = g.Websocket.Conn.SendJSONMessage(wsSub)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tg.Websocket.AddSuccessfulSubscriptions(channelsToSubscribe...)\n\treturn nil\n}", "func FilterSubscriptions(subs []*pb.RPC_SubOpts, filter func(string) bool) []*pb.RPC_SubOpts {\n\taccept := make(map[string]*pb.RPC_SubOpts)\n\n\tfor _, sub := range subs {\n\t\ttopic := sub.GetTopicid()\n\n\t\tif !filter(topic) {\n\t\t\tcontinue\n\t\t}\n\n\t\totherSub, ok := accept[topic]\n\t\tif ok {\n\t\t\tif sub.GetSubscribe() != otherSub.GetSubscribe() {\n\t\t\t\tdelete(accept, topic)\n\t\t\t}\n\t\t} else {\n\t\t\taccept[topic] = sub\n\t\t}\n\t}\n\n\tif len(accept) == 0 {\n\t\treturn nil\n\t}\n\n\tresult := make([]*pb.RPC_SubOpts, 0, len(accept))\n\tfor _, sub := range accept {\n\t\tresult = append(result, sub)\n\t}\n\n\treturn result\n}", "func (eventNotifications *EventNotificationsV1) NewSubscriptionsPager(options *ListSubscriptionsOptions) (pager *SubscriptionsPager, err error) {\n\tif options.Offset != nil && *options.Offset != 0 {\n\t\terr = fmt.Errorf(\"the 'options.Offset' field should not be set\")\n\t\treturn\n\t}\n\n\tvar optionsCopy ListSubscriptionsOptions = *options\n\tpager = &SubscriptionsPager{\n\t\thasNext: true,\n\t\toptions: &optionsCopy,\n\t\tclient: eventNotifications,\n\t}\n\treturn\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 (client IdentityClient) ListRegionSubscriptions(ctx context.Context, request ListRegionSubscriptionsRequest) (response ListRegionSubscriptionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listRegionSubscriptions, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListRegionSubscriptionsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListRegionSubscriptionsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListRegionSubscriptionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListRegionSubscriptionsResponse\")\n\t}\n\treturn\n}", "func (m *ItemItemsDriveItemItemRequestBuilder) Subscriptions()(*ItemItemsItemSubscriptionsRequestBuilder) {\n return NewItemItemsItemSubscriptionsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func printSubscriptions(namespace string) error {\n\t// print subscription details\n\tctx := context.TODO()\n\tsubscriptionList := eventingv1alpha1.SubscriptionList{}\n\tif err := k8sClient.List(ctx, &subscriptionList, client.InNamespace(namespace)); err != nil {\n\t\tlogf.Log.V(1).Info(\"error while getting subscription list\", \"error\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"subscriptions: %+v\\n\", subscriptionList)\n\treturn nil\n}", "func (in *Subscription) DeepCopy() *Subscription {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Subscription)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Subscription) DeepCopy() *Subscription {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Subscription)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (psc *PubSubChannel) NumSubscriptions() int {\n psc.subsMutex.RLock()\n defer psc.subsMutex.RUnlock()\n return len(psc.subscriptions)\n}", "func (_m *DBClient) GetSubscriptions() ([]models.Subscription, error) {\n\tret := _m.Called()\n\n\tvar r0 []models.Subscription\n\tif rf, ok := ret.Get(0).(func() []models.Subscription); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]models.Subscription)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (c *Contributor) GetSubscriptionsURL() string {\n\tif c == nil || c.SubscriptionsURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *c.SubscriptionsURL\n}", "func (o *GetSubscriptionsParams) WithPageSize(pageSize *int32) *GetSubscriptionsParams {\n\to.SetPageSize(pageSize)\n\treturn o\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 (m *MockDB) GetSubscriptions(address, network string) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\", address, network)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *MemoryStore) NumSubscriptions() int {\n\ts.subsMux.RLock()\n\tdefer s.subsMux.RUnlock()\n\n\treturn len(s.subscriptions)\n}", "func (b EntitlementBuilder) SetSubscriptionData(data datastructure.EntitledSubscription) EntitlementBuilder {\n\treturn b.marshalData(data)\n}", "func (*EventNotificationsV1) NewListSubscriptionsOptions(instanceID string) *ListSubscriptionsOptions {\n\treturn &ListSubscriptionsOptions{\n\t\tInstanceID: core.StringPtr(instanceID),\n\t}\n}", "func (m *UserResource) ListUserSubscriptions(ctx context.Context, userId string) ([]*Subscription, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/subscriptions\", userId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar subscription []*Subscription\n\n\tresp, err := rq.Do(ctx, req, &subscription)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn subscription, resp, nil\n}", "func (o UserDefinedResourcesPropertiesPtrOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *UserDefinedResourcesProperties) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QuerySubscriptions\n\t}).(pulumi.StringArrayOutput)\n}", "func (pager *SubscriptionsPager) GetAll() (allItems []SubscriptionListItem, err error) {\n\treturn pager.GetAllWithContext(context.Background())\n}", "func (subscriptions *Subscriptions) Get() ([]*SubscriptionInfo, error) {\n\tclient := NewHTTPClient(subscriptions.client)\n\tresp, err := client.Get(subscriptions.endpoint, subscriptions.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata, _ := NormalizeODataCollection(resp)\n\tvar subs []*SubscriptionInfo\n\tif err := json.Unmarshal(data, &subs); err != nil {\n\t\treturn nil, err\n\t}\n\treturn subs, nil\n}", "func TestSubscriptionsTestSuite(t *testing.T) {\n\tsuite.Run(t, new(SubscriptionsTestSuite))\n}", "func (m *MockISubscription) GetSubscriptions(address, network string) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\", address, network)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *PubsubValueStore) GetSubscriptions() []string {\n\tp.mx.Lock()\n\tdefer p.mx.Unlock()\n\n\tvar res []string\n\tfor sub := range p.topics {\n\t\tres = append(res, sub)\n\t}\n\n\treturn res\n}", "func (r *SubscriptionsService) Create(subscription *Subscription) *SubscriptionsCreateCall {\n\tc := &SubscriptionsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.subscription = subscription\n\treturn c\n}", "func (o ServiceDelegationOutput) SubscriptionsEnabled() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v ServiceDelegation) *bool { return v.SubscriptionsEnabled }).(pulumi.BoolPtrOutput)\n}", "func (m *LogicAppTriggerEndpointConfiguration) SetSubscriptionId(value *string)() {\n err := m.GetBackingStore().Set(\"subscriptionId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (a *StreamsApiService) GetSubscriptionsExecute(r ApiGetSubscriptionsRequest) (JsonSuccessBase, *_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 JsonSuccessBase\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"StreamsApiService.GetSubscriptions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/users/me/subscriptions\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.includeSubscribers != nil {\n\t\tlocalVarQueryParams.Add(\"include_subscribers\", parameterToString(*r.includeSubscribers, \"\"))\n\t}\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\treq, err := a.client.prepareRequest(r.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(req)\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\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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}" ]
[ "0.6805649", "0.6752347", "0.64073074", "0.6334549", "0.6187249", "0.6187249", "0.6186094", "0.6131424", "0.61299884", "0.6005485", "0.6001537", "0.5987716", "0.5975161", "0.5895233", "0.5893747", "0.5869636", "0.5850222", "0.5823477", "0.57931256", "0.57788503", "0.5737833", "0.5645545", "0.5635899", "0.5628309", "0.55477893", "0.5530035", "0.5510144", "0.54940933", "0.5481932", "0.54787594", "0.5475482", "0.5471435", "0.5430498", "0.54233146", "0.54008466", "0.53992397", "0.5382942", "0.53823894", "0.5370962", "0.5370954", "0.53664786", "0.5349992", "0.53480846", "0.5330066", "0.5325007", "0.5308751", "0.53042287", "0.5295488", "0.52943933", "0.5272752", "0.5239395", "0.51890093", "0.515373", "0.5148992", "0.5141447", "0.5127454", "0.5098357", "0.5086655", "0.50785667", "0.50770235", "0.50756335", "0.5042387", "0.5040281", "0.5038977", "0.50357676", "0.5026011", "0.50120693", "0.50120693", "0.50040346", "0.5002593", "0.49887192", "0.4984167", "0.4968394", "0.49680874", "0.49602783", "0.4947744", "0.49312916", "0.4906321", "0.49048325", "0.49048325", "0.48916906", "0.4877712", "0.48678556", "0.48628765", "0.48541614", "0.48483136", "0.48464838", "0.4841235", "0.4834556", "0.48333913", "0.48273692", "0.48247904", "0.48245516", "0.4820585", "0.48069993", "0.4805797", "0.4794954", "0.47757608", "0.47703427", "0.4752344" ]
0.8208021
0
SetSystem sets the system property value. If present, indicates that this is a systemmanaged list. Readonly.
SetSystem устанавливает значение системного свойства. Если присутствует, указывает, что это список, управляемый системой. Только для чтения.
func (m *List) SetSystem(value SystemFacetable)() { m.system = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *RoleWithAccess) SetSystem(v bool) {\n\to.System = &v\n}", "func (o *IamServiceProviderAllOf) SetSystem(v IamSystemRelationship) {\n\to.System = &v\n}", "func (m *Drive) SetSystem(value SystemFacetable)() {\n m.system = value\n}", "func (m *AndroidManagedStoreApp) SetIsSystemApp(value *bool)() {\n err := m.GetBackingStore().Set(\"isSystemApp\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Client) UpdateSystem(system *System) error {\n\titem := reflect.ValueOf(system).Elem()\n\tid, err := c.GetItemHandle(\"system\", system.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.updateCobblerFields(\"system\", item, id)\n}", "func SetSystemLogLevel(l level.Level) {\n\tSystemLogLevel = l\n}", "func (scsuo *SurveyCellScanUpdateOne) SetSystemID(s string) *SurveyCellScanUpdateOne {\n\tscsuo.system_id = &s\n\treturn scsuo\n}", "func (scsu *SurveyCellScanUpdate) SetSystemID(s string) *SurveyCellScanUpdate {\n\tscsu.system_id = &s\n\treturn scsu\n}", "func (u *VolumeUpdater) SetVolumeSystemTags(ctx context.Context, systemTags ...string) {\n\tu.InSVSTags = systemTags\n\tu.InSVSTctx = ctx\n}", "func (w *PropertyWrite) removeSystem(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tres sql.Result\n\t\terr error\n\t)\n\n\tif res, err = w.stmtRemoveSystem.Exec(\n\t\tq.Property.System.Name,\n\t); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\tif mr.RowCnt(res.RowsAffected()) {\n\t\tmr.Property = append(mr.Property, q.Property)\n\t}\n}", "func (r *ListTemplatesRequest) TypeSystem() *ListTemplatesRequest {\n\tr.request.Add(\"type\", \"system\")\n\treturn r\n}", "func (w *PropertyWrite) addSystem(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tres sql.Result\n\t\terr error\n\t)\n\n\tif res, err = w.stmtAddSystem.Exec(\n\t\tq.Property.System.Name,\n\t); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\tif mr.RowCnt(res.RowsAffected()) {\n\t\tmr.Property = append(mr.Property, q.Property)\n\t}\n}", "func (o *RoleWithAccess) GetSystem() bool {\n\tif o == nil || o.System == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.System\n}", "func SetSystemLogLevelFromString(s string) {\n\tSystemLogLevel = level.ToLoglevel(strings.ToUpper(s))\n}", "func (cli *CLI) SystemList() {\n\tlist := nbv1.NooBaaList{}\n\terr := cli.Client.List(cli.Ctx, nil, &list)\n\tif meta.IsNoMatchError(err) {\n\t\tcli.Log.Warningf(\"CRD not installed.\\n\")\n\t\treturn\n\t}\n\tutil.Panic(err)\n\tif len(list.Items) == 0 {\n\t\tcli.Log.Printf(\"No systems found.\\n\")\n\t\treturn\n\t}\n\ttable := (&util.PrintTable{}).AddRow(\n\t\t\"NAMESPACE\",\n\t\t\"NAME\",\n\t\t\"PHASE\",\n\t\t\"MGMT-ENDPOINTS\",\n\t\t\"S3-ENDPOINTS\",\n\t\t\"IMAGE\",\n\t\t\"AGE\",\n\t)\n\tfor i := range list.Items {\n\t\ts := &list.Items[i]\n\t\ttable.AddRow(\n\t\t\ts.Namespace,\n\t\t\ts.Name,\n\t\t\tstring(s.Status.Phase),\n\t\t\tfmt.Sprint(s.Status.Services.ServiceMgmt.NodePorts),\n\t\t\tfmt.Sprint(s.Status.Services.ServiceS3.NodePorts),\n\t\t\ts.Status.ActualImage,\n\t\t\tsince(s.ObjectMeta.CreationTimestamp.Time),\n\t\t)\n\t}\n\tfmt.Print(table.String())\n}", "func (s *ContainerDefinition) SetSystemControls(v []*SystemControl) *ContainerDefinition {\n\ts.SystemControls = v\n\treturn s\n}", "func (o *RoleWithAccess) HasSystem() bool {\n\tif o != nil && o.System != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a *Client) System(params *SystemParams, authInfo runtime.ClientAuthInfoWriter) (*SystemOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSystemParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"system\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/system\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &SystemReader{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.(*SystemOK), nil\n\n}", "func setSystemTime(t time.Time) error {\n\t// convert time types\n\tsystime := windows.Systemtime{\n\t\tYear: uint16(t.Year()),\n\t\tMonth: uint16(t.Month()),\n\t\tDay: uint16(t.Day()),\n\t\tHour: uint16(t.Hour()),\n\t\tMinute: uint16(t.Minute()),\n\t\tSecond: uint16(t.Second()),\n\t\tMilliseconds: uint16(t.Nanosecond() / 1000000),\n\t}\n\n\t// make call to windows api\n\tr1, _, err := procSetSystemTime.Call(uintptr(unsafe.Pointer(&systime)))\n\tif r1 == 0 {\n\t\tlog.Printf(\"%+v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (dt *FieldTraits) System(p Path) { dt.add(p, FieldTypeSystem) }", "func ListSystems(query, outputFormat string) {\n\tsystemList, err := apiClientV1.GetSystems(false)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read system users, err='%s'\\n\", err)\n\t}\n\n\toutputData(outputFormat, query, systemList)\n\n}", "func (m *Fake) SetSysctl(sysctl string, newVal int) error {\n\tm.Settings[sysctl] = newVal\n\treturn nil\n}", "func (m *List) GetSystem()(SystemFacetable) {\n return m.system\n}", "func (me *XsdGoPkgHasElems_System) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_System; 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\tfor _, x := range me.Systems {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\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 (s UserSet) IsSystem() bool {\n\tres := s.Collection().Call(\"IsSystem\")\n\tresTyped, _ := res.(bool)\n\treturn resTyped\n}", "func SetSessionSystemVar(vars *SessionVars, name string, value types.Datum) error {\n\tsysVar := GetSysVar(name)\n\tif sysVar == nil {\n\t\treturn ErrUnknownSystemVar.GenWithStackByArgs(name)\n\t}\n\tsVal := \"\"\n\tvar err error\n\tif !value.IsNull() {\n\t\tsVal, err = value.ToString()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tsVal, err = ValidateSetSystemVar(vars, name, sVal, ScopeSession)\n\tif err != nil {\n\t\treturn err\n\t}\n\tCheckDeprecationSetSystemVar(vars, name)\n\treturn vars.SetSystemVar(name, sVal)\n}", "func (n *netLink) SetSysVal(attribute, value string) (string, error) {\n\treturn sysctl.Sysctl(attribute, value)\n}", "func RegisterSystem(name string, system System) {\n\tgob.Register(system)\n\tsystemsMu.Lock()\n\tdefer systemsMu.Unlock()\n\tmust.Nil(systems[name], \"system \", name, \" already registered\")\n\tsystems[name] = system\n}", "func ValidateSetSystemVar(vars *SessionVars, name string, value string, scope ScopeFlag) (string, error) {\n\tsv := GetSysVar(name)\n\tif sv == nil {\n\t\treturn value, ErrUnknownSystemVar.GenWithStackByArgs(name)\n\t}\n\t// Normalize the value and apply validation based on type.\n\t// i.e. TypeBool converts 1/on/ON to ON.\n\tnormalizedValue, err := sv.ValidateFromType(vars, value, scope)\n\tif err != nil {\n\t\treturn normalizedValue, err\n\t}\n\t// If type validation was successful, call the (optional) validation function\n\treturn sv.ValidateFromHook(vars, normalizedValue, value, scope)\n}", "func (me *XsdGoPkgHasElem_System) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_System; 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.System.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 (m *PrintConnector) SetOperatingSystem(value *string)() {\n err := m.GetBackingStore().Set(\"operatingSystem\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *myClient) initializeSystem(d string, p string) (b bool, err error) {\n\tdevices, err := c.getStorageDevices()\n\tif err != nil {\n\t\treturn\n\t}\n\tif len(devices) == 0 {\n\t\tlogger.Info(\"All devices are configured already\")\n\t\treturn\n\t}\n\tvar deviceString string\n\tfor i, device := range devices {\n\t\tdevice = fmt.Sprintf(\"%s\", strconv.Quote(device))\n\t\tif i == 0 {\n\t\t\tdeviceString = device\n\t\t\tcontinue\n\t\t}\n\t\tdeviceString = fmt.Sprintf(\"%s,%s\", deviceString, device)\n\t}\n\tpostBody := fmt.Sprintf(`\n\t\t{\n\t\t\t\t\t\"type\": \"SystemInitializationParameters\",\n\t\t\t\t\t\"defaultUser\": \"%s\",\n\t\t\t\t\t\"defaultPassword\": \"%s\",\n\t\t\t\t\t\"devices\": [\n\t\t\t\t\t\t%s\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t`, d, p, deviceString)\n\tlogger.Info(\"Assigning devices to storage domain\")\n\taction, _, err := c.httpPost(\"domain/initializeSystem\", postBody)\n\tif err != nil {\n\t\treturn\n\t}\n\tc.jobWaiter(action)\n\tc.waitForEngineReady(10, 300)\n\treturn true, err\n}", "func (s *EvaluationAnswerOutput_) SetSystemSuggestedValue(v *EvaluationAnswerData) *EvaluationAnswerOutput_ {\n\ts.SystemSuggestedValue = v\n\treturn s\n}", "func (in *System) DeepCopy() *System {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(System)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func System() disko.System {\n\treturn &linuxSystem{}\n}", "func (o IopingSpecVolumeVolumeSourceScaleIOPtrOutput) System() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceScaleIO) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.System\n\t}).(pulumi.StringPtrOutput)\n}", "func (inst *InitAuctionManagerV2) SetSystemSysvarAccount(systemSysvar ag_solanago.PublicKey) *InitAuctionManagerV2 {\n\tinst.AccountMetaSlice[8] = ag_solanago.Meta(systemSysvar)\n\treturn inst\n}", "func (c *Client) CreateSystem(system System) (*System, error) {\n\t// Check if a system with the same name already exists\n\tif _, err := c.GetSystem(system.Name); err == nil {\n\t\treturn nil, fmt.Errorf(\"A system with the name %s already exists.\", system.Name)\n\t}\n\n\tif system.Profile == \"\" && system.Image == \"\" {\n\t\treturn nil, fmt.Errorf(\"A system must have a profile or image set.\")\n\t}\n\n\t// Set default values. I guess these aren't taken care of by Cobbler?\n\tif system.BootFiles == \"\" {\n\t\tsystem.BootFiles = \"<<inherit>>\"\n\t}\n\n\tif system.FetchableFiles == \"\" {\n\t\tsystem.FetchableFiles = \"<<inherit>>\"\n\t}\n\n\tif system.MGMTParameters == \"\" {\n\t\tsystem.MGMTParameters = \"<<inherit>>\"\n\t}\n\n\tif system.PowerType == \"\" {\n\t\tsystem.PowerType = \"ipmilan\"\n\t}\n\n\tif system.Status == \"\" {\n\t\tsystem.Status = \"production\"\n\t}\n\n\tif system.VirtAutoBoot == \"\" {\n\t\tsystem.VirtAutoBoot = \"0\"\n\t}\n\n\tif system.VirtCPUs == \"\" {\n\t\tsystem.VirtCPUs = \"<<inherit>>\"\n\t}\n\n\tif system.VirtDiskDriver == \"\" {\n\t\tsystem.VirtDiskDriver = \"<<inherit>>\"\n\t}\n\n\tif system.VirtFileSize == \"\" {\n\t\tsystem.VirtFileSize = \"<<inherit>>\"\n\t}\n\n\tif system.VirtPath == \"\" {\n\t\tsystem.VirtPath = \"<<inherit>>\"\n\t}\n\n\tif system.VirtRam == \"\" {\n\t\tsystem.VirtRam = \"<<inherit>>\"\n\t}\n\n\tif system.VirtType == \"\" {\n\t\tsystem.VirtType = \"<<inherit>>\"\n\t}\n\n\t// To create a system via the Cobbler API, first call new_system to obtain an ID\n\tresult, err := c.Call(\"new_system\", c.Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewId := result.(string)\n\n\t// Set the value of all fields\n\titem := reflect.ValueOf(&system).Elem()\n\tif err := c.updateCobblerFields(\"system\", item, newId); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save the final system\n\tif _, err := c.Call(\"save_system\", newId, c.Token); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Return a clean copy of the system\n\treturn c.GetSystem(system.Name)\n}", "func (o FioSpecVolumeVolumeSourceScaleIOPtrOutput) System() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceScaleIO) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.System\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *CmdReal) SetSysProcAttr(attr *syscall.SysProcAttr) {\n\tc.cmd.SysProcAttr = attr\n}", "func (me *TxsdSystemCategory) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }", "func (c MethodsCollection) IsSystem() pIsSystem {\n\treturn pIsSystem{\n\t\tMethod: c.MustGet(\"IsSystem\"),\n\t}\n}", "func (r *SysNet) SetSysNet(rw http.ResponseWriter) error {\n\tpath, err := r.getPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn share.WriteOneLineFile(path, r.Value)\n}", "func NewSystem(state []float32, parameters []float32, system func(state []float32, parameters []float32) []float32) (s *System) {\n\tif system != nil {\n\t\ts = &System{stateVector: state, parametersVector: parameters, function: system}\n\t} else {\n\t\tpanic(\"NewSystem called with nil system\")\n\t}\n\treturn\n}", "func ChooseSystem(a ...System) {\n\tsystemRegistry = a\n\tsystem = newSystem()\n}", "func (cl *APIClient) UseLIVESystem() *APIClient {\n\tcl.socketConfig.SetSystemEntity(\"54cd\")\n\treturn cl\n}", "func (o IopingSpecVolumeVolumeSourceScaleIOOutput) System() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceScaleIO) string { return v.System }).(pulumi.StringOutput)\n}", "func (s *SendMessageBatchRequestEntry) SetMessageSystemAttributes(v map[string]*MessageSystemAttributeValue) *SendMessageBatchRequestEntry {\n\ts.MessageSystemAttributes = v\n\treturn s\n}", "func (o *ApplianceGroupOpStatus) SetSystemOpStatus(v ApplianceSystemOpStatusRelationship) {\n\to.SystemOpStatus = &v\n}", "func UnmarshalSystemLock(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(SystemLock)\n\terr = core.UnmarshalPrimitive(m, \"sys_locked\", &obj.SysLocked)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"sys_locked_by\", &obj.SysLockedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"sys_locked_at\", &obj.SysLockedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func NewMockSystem(ctrl *gomock.Controller) *MockSystem {\n\tmock := &MockSystem{ctrl: ctrl}\n\tmock.recorder = &MockSystemMockRecorder{mock}\n\treturn mock\n}", "func NewMockSystem(ctrl *gomock.Controller) *MockSystem {\n\tmock := &MockSystem{ctrl: ctrl}\n\tmock.recorder = &MockSystemMockRecorder{mock}\n\treturn mock\n}", "func (m *Manager) System(bin string, args ...string) (*pm.JobResult, error) {\n\treturn mgr.System(bin, args...)\n}", "func (s *SendMessageInput) SetMessageSystemAttributes(v map[string]*MessageSystemAttributeValue) *SendMessageInput {\n\ts.MessageSystemAttributes = v\n\treturn s\n}", "func (c *Dg) SetDeviceVsys(g interface{}, d string, vsys []string) error {\n var name string\n\n switch v := g.(type) {\n case string:\n name = v\n case Entry:\n name = v.Name\n default:\n return fmt.Errorf(\"Unknown type sent to add devices: %s\", v)\n }\n\n c.con.LogAction(\"(set) device vsys in device group: %s\", name)\n\n m := util.MapToVsysEnt(map[string] []string{d: vsys})\n path := c.xpath([]string{name})\n path = append(path, \"devices\")\n\n _, err := c.con.Set(path, m.Entries[0], nil, nil)\n return err\n}", "func (o *IamServiceProviderAllOf) HasSystem() bool {\n\tif o != nil && o.System != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func MockOnSetSystem(ctx context.Context, mockAPI *redfishMocks.RedfishAPI, systemID string,\n\tcomputerSystem redfishClient.ComputerSystem, httpResponse *http.Response, err error) {\n\trequest := redfishClient.ApiSetSystemRequest{}.ComputerSystem(computerSystem)\n\tmockAPI.On(\"SetSystem\", ctx, systemID).Return(request).Times(1)\n\tmockAPI.On(\"SetSystemExecute\", mock.Anything).Return(computerSystem, httpResponse, err).Times(1)\n}", "func (*CgroupfsManager) IsSystemd() bool {\n\treturn false\n}", "func (h *Handler) SelectSystem() int {\n\tfor {\n\t\tcmd := h.ReadCommand()\n\t\tif cmd == nil {\n\t\t\treturn 0\n\t\t}\n\t\tname := \"\"\n\t\ti, err := strconv.Atoi(cmd[0])\n\t\tif err == nil && len(h.systems) >= i && i >= 1 {\n\t\t\tname = h.systems[i-1]\n\t\t} else {\n\t\t\tname = cmd[0]\n\t\t}\n\t\tfor _, s := range h.systems {\n\t\t\tif name == s {\n\t\t\t\tsys := system.Get(name)\n\t\t\t\tif sys == nil {\n\t\t\t\t\tsys = meta.GetSystem(name)\n\t\t\t\t\tsys.Cache()\n\t\t\t\t}\n\t\t\t\tif sys == nil {\n\t\t\t\t\th.PrintlnEnd([]byte(\"build system(\\\"\" + s + \"\\\") failed!\"))\n\t\t\t\t} else {\n\t\t\t\t\th.sys = sys\n\t\t\t\t\th.svr = nil\n\t\t\t\t\th.resetPrompt()\n\t\t\t\t\th.Prompt()\n\t\t\t\t\treturn 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\th.PrintlnEnd([]byte(\"select(\\\"\" + cmd[0] + \"\\\") not found in system list!\"))\n\t}\n}", "func withSystem(node *System) systemOption {\n\treturn func(m *SystemMutation) {\n\t\tm.oldValue = func(context.Context) (*System, error) {\n\t\t\treturn node, nil\n\t\t}\n\t\tm.id = &node.ID\n\t}\n}", "func (a *Client) ListSystemProcessors(params *ListSystemProcessorsParams) (*ListSystemProcessorsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListSystemProcessorsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listSystemProcessors\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/Systems/{identifier}/Processors\",\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: &ListSystemProcessorsReader{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.(*ListSystemProcessorsOK), nil\n\n}", "func (client *APIClient) GetSystem(systemName string) (system System, err error) {\n\tresponse, err := client.request(\"GET\", urlSystem(systemName), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = utilities.FromJSON(response, &system)\n\treturn\n}", "func (o FioSpecVolumeVolumeSourceScaleIOOutput) System() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceScaleIO) string { return v.System }).(pulumi.StringOutput)\n}", "func (o *Block) GetHintSystem(ctx context.Context) (hintSystem bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"HintSystem\").Store(&hintSystem)\n\treturn\n}", "func (m *DeviceHealthAttestationState) SetOperatingSystemRevListInfo(value *string)() {\n err := m.GetBackingStore().Set(\"operatingSystemRevListInfo\", value)\n if err != nil {\n panic(err)\n }\n}", "func (*procSysctl) SetSysctl(sysctl string, newVal string) error {\n\treturn util.WriteFileWithNosec(path.Join(sysctlBase, sysctl), []byte(newVal))\n}", "func (in *SystemSpec) DeepCopy() *SystemSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SystemSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func WithSystemMetricMeasurementFrequency(frequency time.Duration) Option {\n\treturn func(c *config) {\n\t\tc.options.SystemMetrics.MeasurementFrequency = frequency\n\t}\n}", "func (o *ApplianceImageBundleAllOf) SetSystemPackages(v []OnpremImagePackage) {\n\to.SystemPackages = v\n}", "func (m *Win32LobAppFileSystemDetection) SetCheck32BitOn64System(value *bool)() {\n err := m.GetBackingStore().Set(\"check32BitOn64System\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *SoundGroup) SystemObject() (*System, error) {\n\tvar system System\n\tres := C.FMOD_SoundGroup_GetSystemObject(s.cptr, &system.cptr)\n\treturn &system, errs[res]\n}", "func CheckDeprecationSetSystemVar(s *SessionVars, name string) {\n\tswitch name {\n\tcase TiDBIndexLookupConcurrency, TiDBIndexLookupJoinConcurrency,\n\t\tTiDBHashJoinConcurrency, TiDBHashAggPartialConcurrency, TiDBHashAggFinalConcurrency,\n\t\tTiDBProjectionConcurrency, TiDBWindowConcurrency, TiDBMergeJoinConcurrency, TiDBStreamAggConcurrency:\n\t\ts.StmtCtx.AppendWarning(errWarnDeprecatedSyntax.FastGenByArgs(name, TiDBExecutorConcurrency))\n\tcase TIDBMemQuotaHashJoin, TIDBMemQuotaMergeJoin,\n\t\tTIDBMemQuotaSort, TIDBMemQuotaTopn,\n\t\tTIDBMemQuotaIndexLookupReader, TIDBMemQuotaIndexLookupJoin:\n\t\ts.StmtCtx.AppendWarning(errWarnDeprecatedSyntax.FastGenByArgs(name, TIDBMemQuotaQuery))\n\t}\n}", "func (d *DSP) SystemObject() (*System, error) {\n\tvar system System\n\tres := C.FMOD_DSP_GetSystemObject(d.cptr, &system.cptr)\n\treturn &system, errs[res]\n}", "func System(engine *gosge.Engine, gs geometry.Scale) error {\n\tms := movementSystem{\n\t\tgs: gs,\n\t}\n\n\tengine.World().AddSystem(ms.system)\n\n\treturn nil\n}", "func (this *KeyspaceTerm) IsSystem() bool {\n\treturn this.path != nil && this.path.IsSystem()\n}", "func System(g gl.Context3, m *ecs.Manager) {\n\tg.ClearColor(1, 1, 1, 1)\n\tg.LineWidth(4)\n\tg.Enable(gl.CULL_FACE)\n\tg.CullFace(gl.BACK)\n\n\trs := glRenderer{\n\t\tg: g,\n\t\tinstances: []*renderableInstance{},\n\t}\n\trs.setupMaterial()\n\tm.ReflAuto(&rs)\n\n}", "func TestSystem(t *testing.T) {\n\tav, err := NewClient(\"qa.airvantage.io\",\n\t\tos.Getenv(\"API_KEY\"), os.Getenv(\"API_SECRET\"),\n\t\tos.Getenv(\"AV_LOGIN\"), os.Getenv(\"AV_PASSWORD\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tav.Debug = true\n\n\t// Create a new System\n\tsysspec := System{\n\t\tName: \"api test\",\n\t\tGateway: &Gateway{\n\t\t\tIMEI: \"118218318418\",\n\t\t\tType: \"api-gateway\",\n\t\t},\n\t}\n\tsys, err := av.CreateSystem(&sysspec)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer av.DeleteSystem(sys.UID, true, false)\n\n\tsys, err = av.FindSystemByUID(sys.UID)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(\"Found: %+v\", sys)\n\n\tif sys.Name != sysspec.Name {\n\t\tt.FailNow()\n\t}\n}", "func SystemStore(name string) (*CertStore, error) {\n\tcName := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cName))\n\n\thStore := C.openStoreSystem(C.HCRYPTPROV(0), (*C.CHAR)(cName))\n\tif hStore == C.HCERTSTORE(nil) {\n\t\treturn nil, getErr(\"Error getting system cert store\")\n\t}\n\treturn &CertStore{hStore: hStore}, nil\n}", "func (r *CheckConfigurationRead) constraintSystem(cnf *proto.CheckConfig) error {\n\tvar (\n\t\tconfigID, property, value string\n\t\trows *sql.Rows\n\t\terr error\n\t)\n\n\tif rows, err = r.stmtShowConstraintSystem.Query(\n\t\tcnf.ID,\n\t); err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tif err = rows.Scan(\n\t\t\t&configID,\n\t\t\t&property,\n\t\t\t&value,\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconstraint := proto.CheckConfigConstraint{\n\t\t\tConstraintType: `system`,\n\t\t\tSystem: &proto.PropertySystem{\n\t\t\t\tName: property,\n\t\t\t\tValue: value,\n\t\t\t},\n\t\t}\n\t\tcnf.Constraints = append(cnf.Constraints, constraint)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (sv *globalSystemVariables) SetGlobal(name string, val interface{}) error {\n\tsv.mutex.Lock()\n\tdefer sv.mutex.Unlock()\n\tname = strings.ToLower(name)\n\tsysVar, ok := systemVars[name]\n\tif !ok {\n\t\treturn sql.ErrUnknownSystemVariable.New(name)\n\t}\n\tif sysVar.Scope == sql.SystemVariableScope_Session {\n\t\treturn sql.ErrSystemVariableSessionOnly.New(name)\n\t}\n\tif !sysVar.Dynamic || sysVar.ValueFunction != nil {\n\t\treturn sql.ErrSystemVariableReadOnly.New(name)\n\t}\n\tconvertedVal, _, err := sysVar.Type.Convert(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsvv := sql.SystemVarValue{Var: sysVar, Val: convertedVal}\n\tsv.sysVarVals[name] = svv\n\tif sysVar.NotifyChanged != nil {\n\t\tsysVar.NotifyChanged(sql.SystemVariableScope_Global, svv)\n\t}\n\treturn nil\n}", "func (m *DeviceHealthAttestationState) SetOperatingSystemKernelDebugging(value *string)() {\n err := m.GetBackingStore().Set(\"operatingSystemKernelDebugging\", value)\n if err != nil {\n panic(err)\n }\n}", "func (options *CreateActionOptions) SetSysLock(sysLock *SystemLock) *CreateActionOptions {\n\toptions.SysLock = sysLock\n\treturn options\n}", "func (c *Client) DeleteSystem(name string) error {\n\t_, err := c.Call(\"remove_system\", name, c.Token)\n\treturn err\n}", "func (me *TxsdSystemSpoofed) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }", "func GetSystemMemory() *System {\n\tinfo, err := mem.VirtualMemory()\n\tif err != nil {\n\t\tfmt.Printf(\"mem.VirtualMemory error: %v\\n\", err)\n\t\treturn &System{}\n\t}\n\n\treturn &System{\n\t\tTotal: info.Total >> 20,\n\t\tFree: info.Free >> 20,\n\t\tUsagePercent: info.UsedPercent,\n\t}\n}", "func (a *Client) GetSystem(params *GetSystemParams) (*GetSystemOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSystemParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSystem\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/Systems/{identifier}\",\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: &GetSystemReader{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.(*GetSystemOK), nil\n\n}", "func NewSystem(blockNumber string) *System {\n\n\treturn &System{\n\t\tHeight: blockNumber,\n\t\tGoldTokenSupply: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tTotalCeloUSDValue: \"0\"}\n\n}", "func setSystemStatus(status *pb.SystemStatus, members []serf.Member) {\n\tvar foundMaster bool\n\n\tmissing := make(memberMap)\n\tfor _, member := range members {\n\t\tmissing[member.Name] = struct{}{}\n\t}\n\n\tstatus.Status = pb.SystemStatus_Running\n\tfor _, node := range status.Nodes {\n\t\tif !foundMaster && isMaster(node.MemberStatus) {\n\t\t\tfoundMaster = true\n\t\t}\n\t\tif status.Status == pb.SystemStatus_Running {\n\t\t\tstatus.Status = nodeToSystemStatus(node.Status)\n\t\t}\n\t\tif node.MemberStatus.Status == pb.MemberStatus_Failed {\n\t\t\tstatus.Status = pb.SystemStatus_Degraded\n\t\t}\n\t\tdelete(missing, node.Name)\n\t}\n\tif !foundMaster {\n\t\tstatus.Status = pb.SystemStatus_Degraded\n\t\tstatus.Summary = errNoMaster.Error()\n\t}\n\tif len(missing) != 0 {\n\t\tstatus.Status = pb.SystemStatus_Degraded\n\t\tstatus.Summary = fmt.Sprintf(msgNoStatus, missing)\n\t}\n}", "func (c *Client) GetSystem(name string) (*System, error) {\n\tvar system System\n\n\tresult, err := c.Call(\"get_system\", name, c.Token)\n\tif err != nil {\n\t\treturn &system, err\n\t}\n\n\tif result == \"~\" {\n\t\treturn nil, fmt.Errorf(\"System %s not found.\", name)\n\t}\n\n\tdecodeResult, err := decodeCobblerItem(result, &system)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := decodeResult.(*System)\n\ts.Client = *c\n\n\treturn s, nil\n}", "func (a *AllApiService) SystemPropertyUpdateSystemProperty(ctx _context.Context, body SystemPropertyUpdateSystemProperty) (SystemPropertyUpdateSystemPropertyResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SystemPropertyUpdateSystemPropertyResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/systemProperty/updateSystemProperty\"\n\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\t// body params\n\tlocalVarPostBody = &body\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\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v SystemPropertyUpdateSystemPropertyResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\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 (a *Client) ListSystems(params *ListSystemsParams) (*ListSystemsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListSystemsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listSystems\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/Systems\",\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: &ListSystemsReader{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.(*ListSystemsOK), nil\n\n}", "func (bot *Engine) SetSubsystem(subSystemName string, enable bool) error {\n\tif bot == nil {\n\t\treturn errNilBot\n\t}\n\n\tif bot.Config == nil {\n\t\treturn errNilConfig\n\t}\n\n\tvar err error\n\tswitch strings.ToLower(subSystemName) {\n\tcase CommunicationsManagerName:\n\t\tif enable {\n\t\t\tif bot.CommunicationsManager == nil {\n\t\t\t\tcommunicationsConfig := bot.Config.GetCommunicationsConfig()\n\t\t\t\tbot.CommunicationsManager, err = SetupCommunicationManager(&communicationsConfig)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.CommunicationsManager.Start()\n\t\t}\n\t\treturn bot.CommunicationsManager.Stop()\n\tcase ConnectionManagerName:\n\t\tif enable {\n\t\t\tif bot.connectionManager == nil {\n\t\t\t\tbot.connectionManager, err = setupConnectionManager(&bot.Config.ConnectionMonitor)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.connectionManager.Start()\n\t\t}\n\t\treturn bot.connectionManager.Stop()\n\tcase OrderManagerName:\n\t\tif enable {\n\t\t\tif bot.OrderManager == nil {\n\t\t\t\tbot.OrderManager, err = SetupOrderManager(\n\t\t\t\t\tbot.ExchangeManager,\n\t\t\t\t\tbot.CommunicationsManager,\n\t\t\t\t\t&bot.ServicesWG,\n\t\t\t\t\tbot.Config.OrderManager.Verbose,\n\t\t\t\t\tbot.Config.OrderManager.ActivelyTrackFuturesPositions,\n\t\t\t\t\tbot.Config.OrderManager.FuturesTrackingSeekDuration)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.OrderManager.Start()\n\t\t}\n\t\treturn bot.OrderManager.Stop()\n\tcase PortfolioManagerName:\n\t\tif enable {\n\t\t\tif bot.portfolioManager == nil {\n\t\t\t\tbot.portfolioManager, err = setupPortfolioManager(bot.ExchangeManager, bot.Settings.PortfolioManagerDelay, &bot.Config.Portfolio)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.portfolioManager.Start(&bot.ServicesWG)\n\t\t}\n\t\treturn bot.portfolioManager.Stop()\n\tcase NTPManagerName:\n\t\tif enable {\n\t\t\tif bot.ntpManager == nil {\n\t\t\t\tbot.ntpManager, err = setupNTPManager(\n\t\t\t\t\t&bot.Config.NTPClient,\n\t\t\t\t\t*bot.Config.Logging.Enabled)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.ntpManager.Start()\n\t\t}\n\t\treturn bot.ntpManager.Stop()\n\tcase DatabaseConnectionManagerName:\n\t\tif enable {\n\t\t\tif bot.DatabaseManager == nil {\n\t\t\t\tbot.DatabaseManager, err = SetupDatabaseConnectionManager(&bot.Config.Database)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.DatabaseManager.Start(&bot.ServicesWG)\n\t\t}\n\t\treturn bot.DatabaseManager.Stop()\n\tcase SyncManagerName:\n\t\tif enable {\n\t\t\tif bot.currencyPairSyncer == nil {\n\t\t\t\tcfg := bot.Config.SyncManagerConfig\n\t\t\t\tcfg.SynchronizeTicker = bot.Settings.EnableTickerSyncing\n\t\t\t\tcfg.SynchronizeOrderbook = bot.Settings.EnableOrderbookSyncing\n\t\t\t\tcfg.SynchronizeContinuously = bot.Settings.SyncContinuously\n\t\t\t\tcfg.SynchronizeTrades = bot.Settings.EnableTradeSyncing\n\t\t\t\tcfg.Verbose = bot.Settings.Verbose || cfg.Verbose\n\n\t\t\t\tif cfg.TimeoutREST != bot.Settings.SyncTimeoutREST &&\n\t\t\t\t\tbot.Settings.SyncTimeoutREST != config.DefaultSyncerTimeoutREST {\n\t\t\t\t\tcfg.TimeoutREST = bot.Settings.SyncTimeoutREST\n\t\t\t\t}\n\t\t\t\tif cfg.TimeoutWebsocket != bot.Settings.SyncTimeoutWebsocket &&\n\t\t\t\t\tbot.Settings.SyncTimeoutWebsocket != config.DefaultSyncerTimeoutWebsocket {\n\t\t\t\t\tcfg.TimeoutWebsocket = bot.Settings.SyncTimeoutWebsocket\n\t\t\t\t}\n\t\t\t\tif cfg.NumWorkers != bot.Settings.SyncWorkersCount &&\n\t\t\t\t\tbot.Settings.SyncWorkersCount != config.DefaultSyncerWorkers {\n\t\t\t\t\tcfg.NumWorkers = bot.Settings.SyncWorkersCount\n\t\t\t\t}\n\t\t\t\tbot.currencyPairSyncer, err = setupSyncManager(\n\t\t\t\t\t&cfg,\n\t\t\t\t\tbot.ExchangeManager,\n\t\t\t\t\t&bot.Config.RemoteControl,\n\t\t\t\t\tbot.Settings.EnableWebsocketRoutine)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.currencyPairSyncer.Start()\n\t\t}\n\t\treturn bot.currencyPairSyncer.Stop()\n\tcase dispatch.Name:\n\t\tif enable {\n\t\t\treturn dispatch.Start(bot.Settings.DispatchMaxWorkerAmount, bot.Settings.DispatchJobsLimit)\n\t\t}\n\t\treturn dispatch.Stop()\n\tcase DeprecatedName:\n\t\tif enable {\n\t\t\tif bot.apiServer == nil {\n\t\t\t\tvar filePath string\n\t\t\t\tfilePath, err = config.GetAndMigrateDefaultPath(bot.Settings.ConfigFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbot.apiServer, err = setupAPIServerManager(&bot.Config.RemoteControl, &bot.Config.Profiler, bot.ExchangeManager, bot, bot.portfolioManager, filePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.apiServer.StartRESTServer()\n\t\t}\n\t\treturn bot.apiServer.StopRESTServer()\n\tcase WebsocketName:\n\t\tif enable {\n\t\t\tif bot.apiServer == nil {\n\t\t\t\tvar filePath string\n\t\t\t\tfilePath, err = config.GetAndMigrateDefaultPath(bot.Settings.ConfigFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbot.apiServer, err = setupAPIServerManager(&bot.Config.RemoteControl, &bot.Config.Profiler, bot.ExchangeManager, bot, bot.portfolioManager, filePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.apiServer.StartWebsocketServer()\n\t\t}\n\t\treturn bot.apiServer.StopWebsocketServer()\n\tcase grpcName, grpcProxyName:\n\t\treturn errGRPCManagementFault\n\tcase dataHistoryManagerName:\n\t\tif enable {\n\t\t\tif bot.dataHistoryManager == nil {\n\t\t\t\tbot.dataHistoryManager, err = SetupDataHistoryManager(bot.ExchangeManager, bot.DatabaseManager, &bot.Config.DataHistoryManager)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.dataHistoryManager.Start()\n\t\t}\n\t\treturn bot.dataHistoryManager.Stop()\n\tcase vm.Name:\n\t\tif enable {\n\t\t\tif bot.gctScriptManager == nil {\n\t\t\t\tbot.gctScriptManager, err = vm.NewManager(&bot.Config.GCTScript)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.gctScriptManager.Start(&bot.ServicesWG)\n\t\t}\n\t\treturn bot.gctScriptManager.Stop()\n\tcase strings.ToLower(CurrencyStateManagementName):\n\t\tif enable {\n\t\t\tif bot.currencyStateManager == nil {\n\t\t\t\tbot.currencyStateManager, err = SetupCurrencyStateManager(\n\t\t\t\t\tbot.Config.CurrencyStateManager.Delay,\n\t\t\t\t\tbot.ExchangeManager)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bot.currencyStateManager.Start()\n\t\t}\n\t\treturn bot.currencyStateManager.Stop()\n\t}\n\treturn fmt.Errorf(\"%s: %w\", subSystemName, errSubsystemNotFound)\n}", "func (options *UpdateActionOptions) SetSysLock(sysLock *SystemLock) *UpdateActionOptions {\n\toptions.SysLock = sysLock\n\treturn options\n}", "func (cli *CLI) SystemCreate() {\n\tsys := cli.LoadSystemDefaults()\n\tns := util.KubeObject(bundle.File_deploy_namespace_yaml).(*corev1.Namespace)\n\tns.Name = cli.Namespace\n\t// TODO check PVC if exist and the system does not exist -\n\t// fail and suggest to delete them first with cli system delete.\n\tutil.KubeCreateSkipExisting(cli.Client, ns)\n\tutil.KubeCreateSkipExisting(cli.Client, sys)\n}", "func NewSystem(systemSvc controller.System) System {\n\n\tucase := &systemUsecase{\n\t\tsystem: systemSvc,\n\t}\n\n\treturn ucase\n}", "func hostSystemData(ctx context.Context, client *govmomi.Client) ([]mo.HostSystem, error) {\n\tm := view.NewManager(client.Client)\n\thostSystems := []mo.HostSystem{}\n\tview, err := m.CreateContainerView(ctx, client.ServiceContent.RootFolder, []string{\"HostSystem\"}, true)\n\tif err != nil {\n\t\treturn hostSystems, err\n\t}\n\n\tdefer view.Destroy(ctx)\n\n\terr = view.Retrieve(ctx, []string{\"HostSystem\"}, []string{\"name\", \"summary\"}, &hostSystems)\n\tif err != nil {\n\t\treturn hostSystems, err\n\t}\n\treturn hostSystems, nil\n}", "func NewSystem(ctx *Context, conf SystemConfig, cont SystemControl, cron cron.Cronner) (*System, error) {\n\tLog(INFO, ctx, \"NewSystem\")\n\tif !cron.Persistent() && cont.LocationTTL != Forever && os.Getenv(\"RULES_CRON_OVERRIDE\") == \"\" {\n\t\terr := errors.New(\"can't use an ephemeral cron and finite location TTLs\")\n\t\tLog(WARN, ctx, \"NewSystem\", \"error\", err)\n\t\treturn nil, err\n\t}\n\tif !cont.CachePending {\n\t\tLog(WARN, ctx, \"NewSystem\", \"forcingCachePending\", true)\n\t\tcont.CachePending = true\n\t}\n\tsys := &System{\n\t\tconfig: conf,\n\t\tcron: cron,\n\t\tCachedLocations: NewCachedLocations(ctx),\n\t}\n\tLog(DEBUG, ctx, \"DEBUG.NewSystem\", \"sys\", *sys)\n\tsys.SetControl(cont)\n\n\tSystemParameters.DefaultControl = cont.DefaultLocControl\n\tSystemParameters.Log(ctx)\n\treturn sys, nil\n}", "func (t *OpenconfigSystem_System) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *IamServiceProviderAllOf) GetSystem() IamSystemRelationship {\n\tif o == nil || o.System == nil {\n\t\tvar ret IamSystemRelationship\n\t\treturn ret\n\t}\n\treturn *o.System\n}", "func (c *Client) System(method string, id interface{}, data interface{}) System {\n\tvar system System\n\n\tswitch method {\n\tcase \"GET\":\n\t\tendpoint := fmt.Sprintf(\"systems/%v\", id)\n\t\tc.invokeAPI(\"GET\", endpoint, nil, &system)\n\tcase \"CREATE\":\n\t\tendpoint := \"systems\"\n\t\tc.invokeAPI(\"POST\", endpoint, data, &system)\n\tcase \"UPDATE\":\n\t\tendpoint := fmt.Sprintf(\"systems/%v\", id)\n\t\tc.invokeAPI(\"PUT\", endpoint, data, &system)\n\tcase \"DELETE\":\n\t\tendpoint := fmt.Sprintf(\"systems/%v\", id)\n\t\tc.invokeAPI(\"DELETE\", endpoint, nil, nil)\n\t}\n\n\treturn system\n}" ]
[ "0.7896474", "0.72561866", "0.6967416", "0.6135101", "0.60012877", "0.5942262", "0.57586634", "0.57460856", "0.5723831", "0.5708102", "0.56640434", "0.5659007", "0.5594216", "0.5577806", "0.5535843", "0.5497821", "0.54853433", "0.5480487", "0.547595", "0.5474845", "0.54435337", "0.5434316", "0.5423254", "0.54042536", "0.54033405", "0.53886294", "0.5354729", "0.5350145", "0.5333595", "0.52893007", "0.52817875", "0.5271718", "0.52353346", "0.5220286", "0.5220099", "0.5218113", "0.5211185", "0.5186254", "0.51652235", "0.5155769", "0.5142016", "0.5133033", "0.51325136", "0.51159704", "0.5113825", "0.51013905", "0.50948566", "0.509281", "0.5086224", "0.5084569", "0.5072271", "0.5072271", "0.505612", "0.5051825", "0.5046181", "0.5045181", "0.4994966", "0.49938387", "0.4992335", "0.4983731", "0.49811468", "0.4980376", "0.49793512", "0.49585333", "0.49525192", "0.49494803", "0.49389613", "0.4938862", "0.49384558", "0.4931699", "0.4901566", "0.48998764", "0.48958716", "0.4895025", "0.48880157", "0.48776135", "0.4872608", "0.48662543", "0.48653176", "0.48494187", "0.48476523", "0.48444173", "0.4829759", "0.48174152", "0.48159087", "0.48023236", "0.47999892", "0.47931644", "0.47926286", "0.47907522", "0.47783247", "0.47729158", "0.47657865", "0.47586912", "0.4751501", "0.4740608", "0.47347844", "0.47332424", "0.47320154", "0.47303435" ]
0.78210694
1
ReqParticipant specifies the participation role for the calendar user specified by the property is a required participant, REQPARTICIPANT.
ReqParticipant определяет роль участия для пользователя календаря, указанным свойством является обязательным участником, REQPARTICIPANT.
func ReqParticipant() parameter.Parameter { return Other("REQ-PARTICIPANT") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func OptParticipant() parameter.Parameter {\n\treturn Other(\"OPT-PARTICIPANT\")\n}", "func (s *ChannelDefinition) SetParticipantRole(v string) *ChannelDefinition {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *TranscriptFilter) SetParticipantRole(v string) *TranscriptFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *SentimentFilter) SetParticipantRole(v string) *SentimentFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *InterruptionFilter) SetParticipantRole(v string) *InterruptionFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *ParticipantTimerConfiguration) SetParticipantRole(v string) *ParticipantTimerConfiguration {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (duo *DatumUpdateOne) SetParticipant(p *Participant) *DatumUpdateOne {\n\treturn duo.SetParticipantID(p.ID)\n}", "func (du *DatumUpdate) SetParticipant(p *Participant) *DatumUpdate {\n\treturn du.SetParticipantID(p.ID)\n}", "func (r *ChannelsReportSpamRequest) GetParticipant() (value InputPeerClass) {\n\tif r == nil {\n\t\treturn\n\t}\n\treturn r.Participant\n}", "func (s *ParticipantDetailsToAdd) SetParticipantRole(v string) *ParticipantDetailsToAdd {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (user *User) IsParticipant() bool {\n\treturn user.Role == UserRoleParticipant\n}", "func (e *EncryptedChatRequested) GetParticipantID() (value int) {\n\treturn e.ParticipantID\n}", "func ScheduleChangeRequestActorPRecipient() *ScheduleChangeRequestActor {\n\tv := ScheduleChangeRequestActorVRecipient\n\treturn &v\n}", "func (user *User) SetAsParticipant() {\n\tuser.Role = UserRoleParticipant\n}", "func (s *DealService) DeleteParticipant(ctx context.Context, dealID int, participantID int) (*Response, error) {\n\turi := fmt.Sprintf(\"/deals/%v/participants/%v\", dealID, participantID)\n\treq, err := s.client.NewRequest(http.MethodDelete, uri, nil, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(ctx, req, nil)\n}", "func ScheduleChangeRequestActorPSender() *ScheduleChangeRequestActor {\n\tv := ScheduleChangeRequestActorVSender\n\treturn &v\n}", "func (s *StartChatContactOutput) SetParticipantId(v string) *StartChatContactOutput {\n\ts.ParticipantId = &v\n\treturn s\n}", "func AddParticipant(id bson.ObjectId, userID bson.ObjectId) (Event, User) {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"insapp\").C(\"event\")\n\teventID := bson.M{\"_id\": id}\n\tchange := bson.M{\"$addToSet\": bson.M{\n\t\t\"participants\": userID,\n\t}}\n\tdb.Update(eventID, change)\n\tvar event Event\n\tdb.Find(bson.M{\"_id\": id}).One(&event)\n\tuser := AddEventToUser(userID, event.ID)\n\treturn event, user\n}", "func CreateDescribeChannelParticipantsRequest() (request *DescribeChannelParticipantsRequest) {\n\trequest = &DescribeChannelParticipantsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"rtc\", \"2018-01-11\", \"DescribeChannelParticipants\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (m *IncomingContext) SetSourceParticipantId(value *string)() {\n m.sourceParticipantId = value\n}", "func (f *Controller) ParticipantCreated(p *models.ChannelParticipant) error {\n\treturn f.handleParticipantOperation(p)\n}", "func (c *Client) ParticipantResources(ctx context.Context, conferenceSid string) ([]*ParticipantResource, error) {\n\tctx, span := trace.StartSpan(ctx, \"twilio.Client.ParticipantResource()\")\n\tdefer span.End()\n\n\turl := fmt.Sprintf(\"%s/Accounts/%s/Conferences/%s/Participants.json\", baseURL, c.accountSid, conferenceSid)\n\n\treq, err := c.newRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"twilio.Client.ParticipantResource()\")\n\t}\n\n\tres, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"twilio.Client.ParticipantResource(): http.Do(\")\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, errors.WithMessage(decodeError(res.Body), \"twilio.Client.ParticipantResource()\")\n\t}\n\n\tresource := &struct {\n\t\tParticipants []*ParticipantResource\n\t}{}\n\n\tif err := json.NewDecoder(res.Body).Decode(resource); err != nil {\n\t\treturn nil, errors.WithMessage(err, \"twilio.Client.ParticipantResource(): json.Decoder.Decode()\")\n\t}\n\n\treturn resource.Participants, nil\n}", "func NewParticipant(participantType ParticipantType, ID string, name string, username string) (Participant, error){\n\tif participantType == \"\" {\n\t\treturn nil, errors.New(\"Participant Type must not be empty.\")\n\t}\n\n\tif participantType == UserParticipant {\n\n\t\tif ID != \"\" {\n\t\t\treturn participant{ID:ID, Type:participantType}, nil\n\t\t} else if username != \"\" {\n\t\t\treturn participant{Username:username, Type:participantType}, nil\n\t\t} else {\n\t\t\treturn nil, errors.New(\"Username or ID must not be empty for UserParticipant\")\n\t\t}\n\n\t} else if participantType == TeamParticipant || participantType == EscalationParticipant {\n\n\t\tif ID != \"\" {\n\t\t\treturn participant{ID:ID, Type:participantType}, nil\n\t\t} else if name != \"\" {\n\t\t\treturn participant{Name:name, Type:participantType}, nil\n\t\t} else {\n\t\t\treturn nil, errors.New(\"Name or ID must not be empty for TeamParticipant or EscalationParticipant\")\n\t\t}\n\n\t} else if participantType == NoneParticipant {\n\n\t\treturn participant{Type:participantType}, nil\n\n\t} else {\n\n\t\treturn nil, errors.New(\"ParticipantType must not be empty\")\n\t}\n}", "func (i *Invoice) SetPhoneRequested(value bool) {\n\tif value {\n\t\ti.Flags.Set(2)\n\t\ti.PhoneRequested = true\n\t} else {\n\t\ti.Flags.Unset(2)\n\t\ti.PhoneRequested = false\n\t}\n}", "func NonParticipant() parameter.Parameter {\n\treturn Other(\"NON-PARTICIPANT\")\n}", "func (e *EncryptedChatWaiting) GetParticipantID() (value int) {\n\treturn e.ParticipantID\n}", "func (ch *CertHandler) GetParticipantID() string {\n\t// TODO: implement\n\treturn \"participant1\"\n}", "func (s *CreateParticipantOutput) SetParticipantId(v string) *CreateParticipantOutput {\n\ts.ParticipantId = &v\n\treturn s\n}", "func (s *SessionTrackerV1) AddParticipant(participant Participant) {\n\ts.Spec.Participants = append(s.Spec.Participants, participant)\n}", "func ScheduleChangeRequestActorPManager() *ScheduleChangeRequestActor {\n\tv := ScheduleChangeRequestActorVManager\n\treturn &v\n}", "func ScheduleChangeRequestActorPSystem() *ScheduleChangeRequestActor {\n\tv := ScheduleChangeRequestActorVSystem\n\treturn &v\n}", "func (m *IncomingContext) GetSourceParticipantId()(*string) {\n return m.sourceParticipantId\n}", "func (*AppointmentResponse_ParticipantStatusCode) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_appointment_response_proto_rawDescGZIP(), []int{0, 0}\n}", "func (twilio *Twilio) AddConferenceParticipant(conferenceSid string, participant *ConferenceParticipantOptions) (*ConferenceParticipant, *Exception, error) {\n\tform, err := query.Values(participant)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tres, err := twilio.post(form, twilio.buildUrl(fmt.Sprintf(\"Conferences/%s/Participants.json\", conferenceSid)))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdecoder := json.NewDecoder(res.Body)\n\n\tif res.StatusCode != http.StatusCreated {\n\t\texception := new(Exception)\n\t\terr = decoder.Decode(exception)\n\t\treturn nil, exception, err\n\t}\n\n\tconf := new(ConferenceParticipant)\n\terr = decoder.Decode(conf)\n\treturn conf, nil, err\n}", "func (e Elem) Participants(raw *tg.Client) (*participants.GetParticipantsQueryBuilder, bool) {\n\tchannel, ok := peer.ToInputChannel(e.Peer)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn participants.NewQueryBuilder(raw).GetParticipants(channel), true\n}", "func NewParticipant(participant_number int) *Participant {\n\tp := new(Participant)\n\tp.i = participant_number\n\tp.pid = []byte(\"XXXsomethingunique\")\n\n\t// Generate long-term private/public keypair\n\tp.sk = rand_int(group_q)\n\tp.pk = new(big.Int).Exp(group_g, p.sk, group_p)\n\n\tdebug.Printf(\"Created participant %d:\\nsk = %x\\npk = %x\\n\",\n\t\tp.i, p.sk, p.pk)\n\n\treturn p\n}", "func (a *Client) ProjectParticipantPut(params *ProjectParticipantPutParams, authInfo runtime.ClientAuthInfoWriter) (*ProjectParticipantPutOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewProjectParticipantPutParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ProjectParticipant_put\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/project/participant/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json; charset=utf-8\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ProjectParticipantPutReader{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\tsuccess, ok := result.(*ProjectParticipantPutOK)\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 ProjectParticipant_put: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func OutcomeOverviewParticipantsEQ(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (e *EncryptedChat) GetParticipantID() (value int) {\n\treturn e.ParticipantID\n}", "func (i *Invoice) GetPhoneRequested() (value bool) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.Flags.Has(2)\n}", "func NewMeetingParticipants()(*MeetingParticipants) {\n m := &MeetingParticipants{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func RemoveParticipant(id bson.ObjectId, userID bson.ObjectId) (Event, User) {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"insapp\").C(\"event\")\n\teventID := bson.M{\"_id\": id}\n\tchange := bson.M{\"$pull\": bson.M{\n\t\t\"participants\": userID,\n\t}}\n\tdb.Update(eventID, change)\n\tvar event Event\n\tdb.Find(bson.M{\"_id\": id}).One(&event)\n\tuser := RemoveEventFromUser(userID, event.ID)\n\treturn event, user\n}", "func (c Client) Update(input *UpdateParticipantInput) (*UpdateParticipantResponse, error) {\n\treturn c.UpdateWithContext(context.Background(), input)\n}", "func (t Topic) Req() Topic {\n\tt.IsModified()\n\treturn Topic(fmt.Sprintf(\"%s.%s\", t.String(), \"REQ\"))\n}", "func (matcher *JoinSession) AddParticipant(maxAmount uint64, sessID SessionID) (*SessionParticipant, error) {\n\n\treq := addParticipantReq{\n\t\tmaxAmount: maxAmount,\n\t\tsessID: sessID,\n\t\tresp: make(chan addParticipantRes),\n\t}\n\tmatcher.addParticipantReq <- req\n\n\tresp := <-req.resp\n\treturn resp.participant, resp.err\n}", "func (c Client) UpdateWithContext(context context.Context, input *UpdateParticipantInput) (*UpdateParticipantResponse, error) {\n\top := client.Operation{\n\t\tMethod: http.MethodPost,\n\t\tURI: \"/Rooms/{roomSid}/Participants/{sid}\",\n\t\tContentType: client.URLEncoded,\n\t\tPathParams: map[string]string{\n\t\t\t\"roomSid\": c.roomSid,\n\t\t\t\"sid\": c.sid,\n\t\t},\n\t}\n\n\tif input == nil {\n\t\tinput = &UpdateParticipantInput{}\n\t}\n\n\tresponse := &UpdateParticipantResponse{}\n\tif err := c.client.Send(context, op, input, response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn response, nil\n}", "func (*SubscribeTeamRequest) Descriptor() ([]byte, []int) {\n\treturn file_protos_participant_service_proto_rawDescGZIP(), []int{2}\n}", "func (matcher *JoinSession) addParticipantInput(req *submitSplitTxReq) ([]int32, []int32, error) {\n\n\tif _, has := matcher.SessionData.Participants[req.sessionID]; !has {\n\t\treturn nil, nil, ErrSessionNotFound\n\t}\n\n\tinputIndes := make([]int32, 0)\n\toutputIndes := make([]int32, 0)\n\n\tparticipant := matcher.SessionData.Participants[req.sessionID]\n\tparticipant.SplitTx = req.splitTx\n\n\tparticipant.chanSubmitSplitTxRes = req.resp\n\n\t// Clone the sending transaction if this is first sending participant.\n\tif matcher.SessionData.MergedSplitTx == nil {\n\t\tmatcher.SessionData.MergedSplitTx = req.splitTx.Copy()\n\n\t\tfor i, _ := range matcher.SessionData.MergedSplitTx.TxIn {\n\t\t\tinputIndes = append(inputIndes, int32(i))\n\t\t}\n\t\tfor i, _ := range matcher.SessionData.MergedSplitTx.TxOut {\n\t\t\toutputIndes = append(outputIndes, int32(i))\n\t\t}\n\t} else {\n\t\tk := 0\n\t\tinputSize := len(matcher.SessionData.MergedSplitTx.TxIn)\n\t\tfor _, txin := range req.splitTx.TxIn {\n\t\t\tmatcher.SessionData.MergedSplitTx.AddTxIn(txin)\n\t\t\tinputIndes = append(inputIndes, int32(inputSize+k))\n\t\t\tk++\n\t\t}\n\t\tk = 0\n\t\toutputSize := len(matcher.SessionData.MergedSplitTx.TxOut)\n\t\tfor _, txout := range req.splitTx.TxOut {\n\t\t\tmatcher.SessionData.MergedSplitTx.AddTxOut(txout)\n\t\t\toutputIndes = append(outputIndes, int32(outputSize+k))\n\t\t\tk++\n\t\t}\n\t}\n\n\tparticipant.InputIndes = inputIndes\n\tparticipant.OutputIndes = outputIndes\n\n\tif matcher.SessionData.CheckTxSubmitted() {\n\t\tmatcher.SendTxData()\n\t}\n\treturn inputIndes, outputIndes, nil\n}", "func (znp *Znp) ZdoMgmtPermitJoinReq(addrMode AddrMode, dstAddr string, duration uint8, tcSignificance uint8) (rsp *StatusResponse, err error) {\n\treq := &ZdoMgmtPermitJoinReq{AddrMode: addrMode, DstAddr: dstAddr, Duration: duration, TCSignificance: tcSignificance}\n\terr = znp.ProcessRequest(unp.C_SREQ, unp.S_ZDO, 0x36, req, &rsp)\n\treturn\n}", "func (m *IncomingContext) SetObservedParticipantId(value *string)() {\n m.observedParticipantId = value\n}", "func (req Request) EndpointReq() (string,int,error) {\n\treturn (Create(req)).EndpointReq()\n}", "func (a *Client) ProjectParticipantGet(params *ProjectParticipantGetParams, authInfo runtime.ClientAuthInfoWriter) (*ProjectParticipantGetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewProjectParticipantGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ProjectParticipant_get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/project/participant/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ProjectParticipantGetReader{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\tsuccess, ok := result.(*ProjectParticipantGetOK)\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 ProjectParticipant_get: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (duo *DatumUpdateOne) SetParticipantID(id string) *DatumUpdateOne {\n\tduo.mutation.SetParticipantID(id)\n\treturn duo\n}", "func (m *IncomingContext) GetObservedParticipantId()(*string) {\n return m.observedParticipantId\n}", "func ParticipationCreateView(req helios.Request) {\n\tuser, ok := req.GetContextData(auth.UserContextKey).(auth.User)\n\tif !ok {\n\t\treq.SendJSON(helios.ErrInternalServerError.GetMessage(), helios.ErrInternalServerError.GetStatusCode())\n\t\treturn\n\t}\n\n\tvar eventSlug string = req.GetURLParam(\"eventSlug\")\n\tvar participationData ParticipationData\n\tvar participation Participation\n\tvar err helios.Error\n\terr = req.DeserializeRequestData(&participationData)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\terr = DeserializeParticipationWithKey(participationData, &participation)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\terr = UpsertParticipation(user, eventSlug, participationData.UserUsername, &participation)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\treq.SendJSON(SerializeParticipation(participation), http.StatusOK)\n}", "func (j Job) Req() *request.CoordinatedRequest {\n\treturn j.req\n}", "func (p *PeerSubscription) RequestLease(ctx context.Context, msg []byte) (interfaces.PeerLease, error) {\n\tp.RLock()\n\tdefer p.RUnlock()\n\tpeers, ok := p.actives.getPeers()\n\tif ok {\n\t\tfor i := 0; i < len(peers); i++ {\n\t\t\tclient, ok := peers[i].(*p2PClient)\n\t\t\tif ok {\n\t\t\t\tif client.Contains(msg) {\n\t\t\t\t\treturn client, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn p.PeerLease(ctx)\n}", "func (r *Room) Participate(p Player, x, y int, color string) bool {\n\tif r.Status != Waiting {\n\t\treturn false\n\t}\n\treturn r.board.Add(p, x, y, color)\n}", "func (f *Controller) ParticipantUpdated(p *models.ChannelParticipant) error {\n\treturn f.handleParticipantOperation(p)\n}", "func (model *meetingModel) AddParticipatorToMeeting(meeting *Meeting, participator string) {\n\tlogger.Println(\"[meetingmodel] try adding a participator to meeting\", meeting.Title)\n\tcurMeetingParticipators := model.meetings[meeting.Title].Participators\n\tmodel.meetings[meeting.Title].Participators = append(curMeetingParticipators, participator)\n\tmodel.dump()\n\tlogger.Println(\"[meetingmodel] added a participator to meeting\", meeting.Title)\n}", "func NewUnifiedRoleAssignmentScheduleRequest()(*UnifiedRoleAssignmentScheduleRequest) {\n m := &UnifiedRoleAssignmentScheduleRequest{\n Request: *NewRequest(),\n }\n return m\n}", "func (*UserRoleRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_casbin_proto_rawDescGZIP(), []int{12}\n}", "func OutcomeOverviewParticipantsNEQ(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (s *SessionTrackerV1) RemoveParticipant(id string) error {\n\tfor i, participant := range s.Spec.Participants {\n\t\tif participant.ID == id {\n\t\t\ts.Spec.Participants[i], s.Spec.Participants = s.Spec.Participants[len(s.Spec.Participants)-1], s.Spec.Participants[:len(s.Spec.Participants)-1]\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn trace.NotFound(\"participant %v not found\", id)\n}", "func (o ServicePrincipalOutput) AppRoleAssignmentRequired() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *ServicePrincipal) pulumi.BoolPtrOutput { return v.AppRoleAssignmentRequired }).(pulumi.BoolPtrOutput)\n}", "func (r *MergeRequestsService) GetMergeRequestParticipants(project int, mergeRequest int, options ...gitlab.RequestOptionFunc) ([]*gitlab.BasicUser, *gitlab.Response, error) {\n\tu := fmt.Sprintf(\"projects/%d/merge_requests/%d/participants\", project, mergeRequest)\n\n\treq, err := r.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar p []*gitlab.BasicUser\n\tresp, err := r.client.Do(req, &p)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn p, resp, err\n}", "func (m NoPartyIDs) SetPartyRole(v enum.PartyRole) {\n\tm.Set(field.NewPartyRole(v))\n}", "func (n *QriNode) RequestPeername(peername string) error {\n\treturn nil\n}", "func NewParticipant(name string, peerConnectionConfig webrtc.Configuration, media *webrtc.MediaEngine, customPayloadType uint8, codec string) (*Participant, error) {\n\n\tapi := webrtc.NewAPI(webrtc.WithMediaEngine(*media))\n\n\t// Create a PeerConnection\n\tpc, err := api.NewPeerConnection(peerConnectionConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpart := Participant{\n\t\tID: utils.RandSeq(5),\n\t\tName: name,\n\t\tPeer: pc,\n\t\tAPI: api,\n\t\tMediaEngine: media,\n\t\tPayloadType: customPayloadType,\n\t\tCodec: codec,\n\t\tDataChannels: map[string]*webrtc.DataChannel{},\n\t}\n\n\treturn &part, nil\n}", "func (a *Client) HPCResourceRequest(ctx context.Context, params *HPCResourceRequestParams) (*HPCResourceRequestOK, error) {\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"HPCResourceRequest\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/approval_system/resourceRequest/{HPCResourceID}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &HPCResourceRequestReader{formats: a.formats},\n\t\tAuthInfo: a.authInfo,\n\t\tContext: ctx,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*HPCResourceRequestOK), nil\n\n}", "func (self *Event) ParticipantFeedbackIterator() model.Iterator {\n\treturn FeedbackParticipants.Filter(\"Event\", self.ID).Iterator()\n}", "func (m *MockRoleClient) CreateRoleRequest(input *iam.CreateRoleInput) iam.CreateRoleRequest {\n\treturn m.MockCreateRoleRequest(input)\n}", "func (s *Database) Request(in *rpc.UserPartnerRequest) (*rpc.UserPartnerResponse, error) {\n\tvar list []*UserPartner\n\tcondi := UserPartner{\n\t\tUserId: in.UserId,\n\t\tPhone: in.Phone,\n\t}\n\terr := s.Engine.Limit(int(in.Limit), 0).Find(&list, condi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar users []*rpc.UserPartner\n\tfor i := range list {\n\t\ttemp := rpc.UserPartner{\n\t\t\tId: list[i].Id,\n\t\t\tUserId: list[i].UserId,\n\t\t\tPartnerId: list[i].PartnerId,\n\t\t\tAliasUserId: list[i].AliasUserId,\n\t\t\tApps: list[i].Apps,\n\t\t\tPhone: list[i].Phone,\n\t\t\tCreated: list[i].Created,\n\t\t\tUpdatedAt: list[i].UpdatedAt,\n\t\t}\n\t\tusers = append(users, &temp)\n\t}\n\treturn &rpc.UserPartnerResponse{\n\t\tUserPartners: users,\n\t}, nil\n}", "func (rrc *ReserveRoomCreate) SetRequest(s string) *ReserveRoomCreate {\n\trrc.mutation.SetRequest(s)\n\treturn rrc\n}", "func (o ApiOperationRequestHeaderOutput) Required() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v ApiOperationRequestHeader) bool { return v.Required }).(pulumi.BoolOutput)\n}", "func ValidateRole(ctx context.Context, projectID string, requiredRoles []model.MemberRole, invitation string) error {\n\tclaims := ctx.Value(authorization.UserClaim).(jwt.MapClaims)\n\tuid := claims[\"uid\"].(string)\n\n\tfilter := bson.D{{\"members\", bson.D{{\"$elemMatch\", bson.D{{\"user_id\", uid}, {\"role\", bson.D{{\"$in\", requiredRoles}}}, {\"invitation\", invitation}}}}}, {\"_id\", projectID}}\n\t_, err := dbOperationsProject.GetProject(ctx, filter)\n\n\tif err != nil {\n\t\treturn errors.New(\"Permission Denied\")\n\t}\n\n\treturn nil\n}", "func PromIncRequest(sc int, m string) {\n\tTotalRequestCounter.With(prometheus.Labels{\"code\": fmt.Sprintf(\"%v\", sc), \"method\": m}).Inc()\n}", "func (p *Participant) StartParticipation(i InstanceNumber, s SequenceNumber, cluster string, self Member, master Member, members []Member, snapshot []byte) error {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\t// StartParticipation can be used to re-initialize the state in case some changes were missed\n\tif p.participantState != state_UNJOINED && p.participantState != state_PARTICIPANT_CLEAN && p.participantState != state_PARTICIPANT_PENDING {\n\t\treturn NewError(ERR_STATE, fmt.Sprintf(\"Expected state UNJOINED/PARTICIPANT*, am in state %d\", p.participantState), nil)\n\t}\n\n\t// Don't allow for snapshots to be installed that are older than our state\n\tif i < p.instance || (i == p.instance && s < p.sequence) {\n\t\treturn NewError(ERR_SEQUENCE, fmt.Sprintf(\"Received bad snapshot. We're at %d/%d; snapshot is %d/%d\", p.instance, p.sequence, i, s), nil)\n\t}\n\n\tp.cluster = cluster\n\tp.members = members\n\tp.master[i] = master\n\tp.self = self\n\tp.instance = i\n\tp.sequence = s\n\tp.state.Install(snapshot)\n\n\tif self == master {\n\t\t// Bootstrapped externally\n\t\tp.participantState = state_MASTER\n\t\tp.eventHandler.OnBecomeMaster(p)\n\t} else {\n\t\tp.participantState = state_PARTICIPANT_CLEAN\n\t}\n\n\tfor _, member := range members {\n\t\t// Try connecting already.\n\t\tp.getConnectedClient(member)\n\t}\n\n\treturn nil\n}", "func (e *Environment) Required() *Environment {\n\te.required = true\n\treturn e\n}", "func CreateCreateMeetingRequest() (request *CreateMeetingRequest) {\n\trequest = &CreateMeetingRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"aliyuncvc\", \"2019-10-30\", \"CreateMeeting\", \"aliyuncvc\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (mb *messageBuilder) SetRoleProof(sig types.VrfSignature) *messageBuilder {\n\tmb.msg.Eligibility.Proof = sig\n\treturn mb\n}", "func RequestUser(s string) QueryOption {\n\treturn func(q *queryOptions) error {\n\t\tq.requestProperties.Options[RequestUserValue] = s\n\t\treturn nil\n\t}\n}", "func (t *Trade) FindParticipant(user *User) (*TradeParticipant, errstack.E) {\n\tif t.Buyer.UserID == user.ID {\n\t\treturn &t.Buyer, nil\n\t}\n\tif t.Seller.UserID == user.ID {\n\t\treturn &t.Seller, nil\n\t}\n\tif user.IsModerator() {\n\t\t// HACK! HD wallets won't work\n\t\t// TODO: Remove it during HD wallet refactoring\n\t\tsw, ok := user.StaticWallets[user.DefaultWalletID]\n\t\tif !ok {\n\t\t\t// Not telling that it's a moderator user\n\t\t\treturn nil, errstack.NewReqF(\"User '%s' doesn't have a default wallet\", user.ID)\n\t\t}\n\t\treturn &TradeParticipant{\n\t\t\tUserID: user.ID,\n\t\t\t//KeyDerivationPath: \"under construction\",\n\t\t\t//WalletID: \"under construction\",\n\t\t\tPubKey: sw.PubKey,\n\t\t}, nil\n\t}\n\treturn nil, errstack.NewReqF(\"User '%s' is not a participant of trade '%s'\", user.ID, t.ID)\n}", "func (*CreateRoleRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{0}\n}", "func (s *ParticipantTokenCredentials) SetParticipantToken(v string) *ParticipantTokenCredentials {\n\ts.ParticipantToken = &v\n\treturn s\n}", "func (self *Event) updateEventParticipantFromAmiandoParticipant(logger *log.Logger, person *Person, eventParticipant *EventParticipant, amiandoParticipant *amiando.Participant) error {\n\teventParticipant.Event.Set(self)\n\teventParticipant.Person.Set(person)\n\n\tdate, err := amiandoToModelDateTime(amiandoParticipant.CreatedDate)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = eventParticipant.AppliedDate.Set(date)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Background\n\taBackgroundData := amiandoData[\"Background\"]\n\tfor i := 0; i < len(aBackgroundData); i++ {\n\t\tif background, ok := amiandoParticipant.FindUserData(aBackgroundData[i]); ok {\n\t\t\teventParticipant.Background.Set(background.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Other Background\n\taOtherData := amiandoData[\"Other\"]\n\tfor i := 0; i < len(aOtherData); i++ {\n\t\tif bgother, ok := amiandoParticipant.FindUserData(aOtherData[i]); ok {\n\t\t\teventParticipant.Background2.Set(bgother.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Pitching?\n\taIsPichtingData := amiandoData[\"IsPitching\"]\n\tfor i := 0; i < len(aIsPichtingData); i++ {\n\t\tif isPitching, ok := amiandoParticipant.FindUserData(aIsPichtingData[i]); ok {\n\t\t\tif isPitching.String() == \"yes\" || isPitching.String() == \"Yes\" {\n\t\t\t\teventParticipant.PresentsIdea = true\n\t\t\t\tlogger.Printf(\"Presents an idea\")\n\n\t\t\t\t// aTeamNameData := amiandoData[\"TeamName\"]\n\t\t\t\t// for j:=0; j < len(aTeamNameData); j++ {\n\t\t\t\t// \tif teamname, ok := amiandoParticipant.FindUserData(aTeamNameData[j]); ok {\n\t\t\t\t// \t\tteam, created := createTeamFromAmiando(amiandoParticipant)\n\n\t\t\t\t// \t\tif created {\n\t\t\t\t// \t\t\tperson.Team = team.Ref()\n\t\t\t\t// \t\t}\n\n\t\t\t\t// \t}\n\t\t\t\t// }\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Name\n\taStartupNameData := amiandoData[\"StartupName\"]\n\tfor i := 0; i < len(aStartupNameData); i++ {\n\t\tif startupname, ok := amiandoParticipant.FindUserData(aStartupNameData[i]); ok {\n\t\t\teventParticipant.Startup.Name.Set(startupname.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Website\n\taStartupWebsiteData := amiandoData[\"StartupWebsite\"]\n\tfor i := 0; i < len(aStartupWebsiteData); i++ {\n\t\tif startupWebsite, ok := amiandoParticipant.FindUserData(aStartupWebsiteData[i]); ok {\n\t\t\teventParticipant.Startup.Website.Set(startupWebsite.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup #Employee\n\taStartupEmployeeData := amiandoData[\"StartupNrEmployee\"]\n\tfor i := 0; i < len(aStartupEmployeeData); i++ {\n\t\tif startupNrEmployees, ok := amiandoParticipant.FindUserData(aStartupEmployeeData[i]); ok {\n\t\t\teventParticipant.Startup.NrEmployees.Set(startupNrEmployees.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Years active\n\taStartupYearsData := amiandoData[\"StartupYears\"]\n\tfor i := 0; i < len(aStartupYearsData); i++ {\n\t\tif startupYearsActive, ok := amiandoParticipant.FindUserData(aStartupYearsData[i]); ok {\n\t\t\teventParticipant.Startup.YearsActive.Set(startupYearsActive.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Accommodation\n\taAccomodationData := amiandoData[\"Accommodation\"]\n\tfor i := 0; i < len(aAccomodationData); i++ {\n\t\taccommodation, ok := amiandoParticipant.FindUserData(aAccomodationData[i])\n\t\tif ok {\n\n\t\t\teventParticipant.Accommodation.Set(accommodation.String())\n\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\t// Ticket Data\n\teventParticipant.Ticket.AmiandoTicketID.Set(amiandoParticipant.TicketID.String())\n\teventParticipant.Ticket.Type.Set(string(amiandoParticipant.TicketType))\n\teventParticipant.Ticket.InvoiceNumber.Set(amiandoParticipant.InvoiceNumber)\n\teventParticipant.Ticket.RegistrationNumber.Set(amiandoParticipant.RegistrationNumber)\n\tif amiandoParticipant.CheckedDate != \"\" {\n\t\tdate, err := amiandoToModelDateTime(amiandoParticipant.CheckedDate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = eventParticipant.Ticket.CheckedDate.Set(date)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif amiandoParticipant.CancelledDate != \"\" {\n\t\tdate, err := amiandoToModelDateTime(amiandoParticipant.CancelledDate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = eventParticipant.Ticket.CancelledDate.Set(date)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn eventParticipant.Save()\n}", "func (a *API) GetRoomParticipantPayload(\n\troom *RoomModel,\n\tuserID string,\n) (*RoomParticipantEventPayload, error) {\n\tuserIDs := []string{}\n\tfor _, u := range room.Members {\n\t\tuserIDs = append(userIDs, u.ID)\n\t}\n\treturn &RoomParticipantEventPayload{\n\t\tRoomID: room.ID,\n\t\tUserID: userID,\n\t\tParticipantIDs: userIDs,\n\t}, nil\n}", "func (piuo *ProviderIDUpdateOne) SetParticpant(p *Participant) *ProviderIDUpdateOne {\n\treturn piuo.SetParticpantID(p.ID)\n}", "func (c Create) EndpointReq() (string,int,error) {\n\tif authreq.AUTH_VERSION != authreq.AUTH_V4 {\n\t\te := fmt.Sprintf(\"create_table(Create).EndpointReq \" +\n\t\t\t\"auth must be v4\")\n\t\treturn \"\",0,errors.New(e)\n\t}\n\treturn authreq.RetryReq_V4(&c,CREATETABLE_ENDPOINT)\n}", "func (ctc *ClinicalTrialCreate) SetResponsibleParty(s string) *ClinicalTrialCreate {\n\tctc.mutation.SetResponsibleParty(s)\n\treturn ctc\n}", "func (n *Client) RequestConfirmedTransaction(addr ledgerstate.Address, txid ledgerstate.TransactionID) {\n\tn.sendMessage(&txstream.MsgGetConfirmedTransaction{\n\t\tAddress: addr,\n\t\tTxID: txid,\n\t})\n}", "func (client *NpmClient) EndpointCreateReq(epinfo *netproto.Endpoint) (*netproto.Endpoint, error) {\n\treturn nil, nil\n}", "func (twilio *Twilio) GetConferenceParticipant(conferenceSid, callSid string) (*ConferenceParticipant, *Exception, error) {\n\tres, err := twilio.get(twilio.buildUrl(fmt.Sprintf(\"Conferences/%s/Participants/%s.json\", conferenceSid, callSid)))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdecoder := json.NewDecoder(res.Body)\n\n\t// handle NULL response\n\tif res.StatusCode != http.StatusOK {\n\t\texception := new(Exception)\n\t\terr = decoder.Decode(exception)\n\t\treturn nil, exception, err\n\t}\n\n\tconf := new(ConferenceParticipant)\n\terr = decoder.Decode(conf)\n\treturn conf, nil, err\n}", "func (d *device) RequestConsent(recipientdevice device, c contentinfo) error {\n\t//pointer not nil; checked above\n\tif !recipientdevice.Online {\n\t\tSetConsoleColor(RED)\n\t\tfmt.Printf(\"device [%s] is offline. Request Canceled.\\n\", recipientdevice.Deviceid)\n\t\tSetConsoleColor(RESET)\n\t\treturn errors.New(ERRMSG_DEVICEOFFLINE)\n\t}\n\trecipientdevice.Inrequests <- c\n\treturn nil\n}", "func (_obj *Apichannels) Channels_getParticipant(params *TLchannels_getParticipant, _opt ...map[string]string) (ret Channels_ChannelParticipant, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"channels_getParticipant\", _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 = ret.ReadBlock(_is, 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 (s *SessionTrackerV1) GetParticipants() []Participant {\n\treturn s.Spec.Participants\n}", "func (*QueryRoleRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{2}\n}", "func EncodeGRPCLoremRequest(_ context.Context, r interface{}) (interface{}, error) {\n\treq := r.(endpoints.LoremRequest)\n\treturn &pb.LoremRequest{\n\t\tRequestType: req.RequestType,\n\t\tMax: req.Max,\n\t\tMin: req.Min,\n\t} , nil\n}", "func ParticipationVerifyView(req helios.Request) {\n\tuser, ok := req.GetContextData(auth.UserContextKey).(auth.User)\n\tif !ok {\n\t\treq.SendJSON(helios.ErrInternalServerError.GetMessage(), helios.ErrInternalServerError.GetStatusCode())\n\t\treturn\n\t}\n\n\tvar eventSlug string = req.GetURLParam(\"eventSlug\")\n\tvar verificationData VerificationData\n\tvar err helios.Error\n\terr = req.DeserializeRequestData(&verificationData)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\terr = VerifyParticipation(user, eventSlug, verificationData.KeyHashedOnce)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\treq.SendJSON(\"OK\", http.StatusOK)\n}", "func (p *Participant) SubmitRequest(c []Change) error {\n\tif p.participantState != state_MASTER {\n\t\treturn NewError(ERR_STATE, \"Can't request changes to be submitted on non-master\", nil)\n\t} else {\n\t\treturn p.submitAsMaster(c)\n\t}\n}" ]
[ "0.6335902", "0.6020651", "0.5960029", "0.59365475", "0.59108174", "0.58237433", "0.55794024", "0.55225873", "0.5517706", "0.53861356", "0.5348708", "0.53117955", "0.5155773", "0.5102707", "0.50262994", "0.49464083", "0.4815764", "0.4769822", "0.47673255", "0.47654703", "0.475025", "0.47013423", "0.47007304", "0.46990824", "0.46672106", "0.46621078", "0.46593913", "0.46578142", "0.46379545", "0.4616383", "0.4613999", "0.46123958", "0.45860082", "0.45175648", "0.44922438", "0.447618", "0.44578907", "0.44506603", "0.4446851", "0.4445191", "0.4438574", "0.44260985", "0.44236624", "0.44198623", "0.43995744", "0.43929112", "0.43777817", "0.43775824", "0.43753374", "0.43515596", "0.4321856", "0.43211055", "0.4315712", "0.4304527", "0.4298128", "0.42958608", "0.4295675", "0.42884418", "0.4284851", "0.4277455", "0.42766407", "0.42751336", "0.42663628", "0.42662516", "0.42599303", "0.4256123", "0.42556146", "0.42441055", "0.4240266", "0.42396605", "0.42039594", "0.4198731", "0.41939032", "0.41933495", "0.41911438", "0.41896424", "0.41887417", "0.41871783", "0.4178168", "0.4174949", "0.4166922", "0.41661555", "0.41627592", "0.41601107", "0.4155518", "0.41534463", "0.41482845", "0.41450745", "0.41445", "0.41343158", "0.41327536", "0.41203994", "0.41184968", "0.41172785", "0.41132322", "0.4111836", "0.41102892", "0.41098452", "0.410371", "0.41000572" ]
0.8265217
0
OptParticipant specifies the participation role for the calendar user specified by the property is an optional participant, OPTPARTICIPANT.
OptParticipant определяет роль участия для пользователя календаря, указываемого свойством, являющегося необязательным участником, OPTPARTICIPANT.
func OptParticipant() parameter.Parameter { return Other("OPT-PARTICIPANT") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ReqParticipant() parameter.Parameter {\n\treturn Other(\"REQ-PARTICIPANT\")\n}", "func (s *TranscriptFilter) SetParticipantRole(v string) *TranscriptFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *ParticipantTimerConfiguration) SetParticipantRole(v string) *ParticipantTimerConfiguration {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *ChannelDefinition) SetParticipantRole(v string) *ChannelDefinition {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *InterruptionFilter) SetParticipantRole(v string) *InterruptionFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (s *SentimentFilter) SetParticipantRole(v string) *SentimentFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (duo *DatumUpdateOne) SetParticipant(p *Participant) *DatumUpdateOne {\n\treturn duo.SetParticipantID(p.ID)\n}", "func (du *DatumUpdate) SetParticipant(p *Participant) *DatumUpdate {\n\treturn du.SetParticipantID(p.ID)\n}", "func (s *ParticipantDetailsToAdd) SetParticipantRole(v string) *ParticipantDetailsToAdd {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func (user *User) SetAsParticipant() {\n\tuser.Role = UserRoleParticipant\n}", "func (user *User) IsParticipant() bool {\n\treturn user.Role == UserRoleParticipant\n}", "func (m *MeetingParticipants) SetOrganizer(value MeetingParticipantInfoable)() {\n m.organizer = value\n}", "func (opt OptResumeAfter) Option(d *bson.Document) error {\n\tif opt.ResumeAfter != nil {\n\t\td.Append(bson.EC.SubDocument(\"resumeAfter\", opt.ResumeAfter))\n\t}\n\treturn nil\n}", "func NonParticipant() parameter.Parameter {\n\treturn Other(\"NON-PARTICIPANT\")\n}", "func (s *DealService) DeleteParticipant(ctx context.Context, dealID int, participantID int) (*Response, error) {\n\turi := fmt.Sprintf(\"/deals/%v/participants/%v\", dealID, participantID)\n\treq, err := s.client.NewRequest(http.MethodDelete, uri, nil, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(ctx, req, nil)\n}", "func (store *Store) DebugSetParticipant(ctx context.Context, p *model.Participant) error {\n\tkey := participantKey(p.ID)\n\t_, err := store.dsClient.Put(ctx, key, p)\n\treturn err\n}", "func DelegateCandidateOption() AccountCreationOption {\n\treturn func(account *Account) error {\n\t\taccount.isCandidate = true\n\t\treturn nil\n\t}\n}", "func OutcomeOverviewParticipantsNEQ(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (s *SessionTrackerV1) AddParticipant(participant Participant) {\n\ts.Spec.Participants = append(s.Spec.Participants, participant)\n}", "func OutcomeOverviewParticipantsEQ(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (opt OptMaxAwaitTime) Option(d *bson.Document) error {\n\td.Append(bson.EC.Int64(\"maxAwaitTimeMS\", int64(time.Duration(opt)/time.Millisecond)))\n\treturn nil\n}", "func (opt OptProjection) Option(d *bson.Document) error {\n\tvar key = \"projection\"\n\n\tdoc, err := transformDocument(opt.Registry, opt.Projection)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Append(bson.EC.SubDocument(key, doc))\n\treturn nil\n}", "func (s *StartChatContactOutput) SetParticipantId(v string) *StartChatContactOutput {\n\ts.ParticipantId = &v\n\treturn s\n}", "func (self *Event) updateEventParticipantFromAmiandoParticipant(logger *log.Logger, person *Person, eventParticipant *EventParticipant, amiandoParticipant *amiando.Participant) error {\n\teventParticipant.Event.Set(self)\n\teventParticipant.Person.Set(person)\n\n\tdate, err := amiandoToModelDateTime(amiandoParticipant.CreatedDate)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = eventParticipant.AppliedDate.Set(date)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Background\n\taBackgroundData := amiandoData[\"Background\"]\n\tfor i := 0; i < len(aBackgroundData); i++ {\n\t\tif background, ok := amiandoParticipant.FindUserData(aBackgroundData[i]); ok {\n\t\t\teventParticipant.Background.Set(background.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Other Background\n\taOtherData := amiandoData[\"Other\"]\n\tfor i := 0; i < len(aOtherData); i++ {\n\t\tif bgother, ok := amiandoParticipant.FindUserData(aOtherData[i]); ok {\n\t\t\teventParticipant.Background2.Set(bgother.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Pitching?\n\taIsPichtingData := amiandoData[\"IsPitching\"]\n\tfor i := 0; i < len(aIsPichtingData); i++ {\n\t\tif isPitching, ok := amiandoParticipant.FindUserData(aIsPichtingData[i]); ok {\n\t\t\tif isPitching.String() == \"yes\" || isPitching.String() == \"Yes\" {\n\t\t\t\teventParticipant.PresentsIdea = true\n\t\t\t\tlogger.Printf(\"Presents an idea\")\n\n\t\t\t\t// aTeamNameData := amiandoData[\"TeamName\"]\n\t\t\t\t// for j:=0; j < len(aTeamNameData); j++ {\n\t\t\t\t// \tif teamname, ok := amiandoParticipant.FindUserData(aTeamNameData[j]); ok {\n\t\t\t\t// \t\tteam, created := createTeamFromAmiando(amiandoParticipant)\n\n\t\t\t\t// \t\tif created {\n\t\t\t\t// \t\t\tperson.Team = team.Ref()\n\t\t\t\t// \t\t}\n\n\t\t\t\t// \t}\n\t\t\t\t// }\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Name\n\taStartupNameData := amiandoData[\"StartupName\"]\n\tfor i := 0; i < len(aStartupNameData); i++ {\n\t\tif startupname, ok := amiandoParticipant.FindUserData(aStartupNameData[i]); ok {\n\t\t\teventParticipant.Startup.Name.Set(startupname.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Website\n\taStartupWebsiteData := amiandoData[\"StartupWebsite\"]\n\tfor i := 0; i < len(aStartupWebsiteData); i++ {\n\t\tif startupWebsite, ok := amiandoParticipant.FindUserData(aStartupWebsiteData[i]); ok {\n\t\t\teventParticipant.Startup.Website.Set(startupWebsite.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup #Employee\n\taStartupEmployeeData := amiandoData[\"StartupNrEmployee\"]\n\tfor i := 0; i < len(aStartupEmployeeData); i++ {\n\t\tif startupNrEmployees, ok := amiandoParticipant.FindUserData(aStartupEmployeeData[i]); ok {\n\t\t\teventParticipant.Startup.NrEmployees.Set(startupNrEmployees.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Startup Years active\n\taStartupYearsData := amiandoData[\"StartupYears\"]\n\tfor i := 0; i < len(aStartupYearsData); i++ {\n\t\tif startupYearsActive, ok := amiandoParticipant.FindUserData(aStartupYearsData[i]); ok {\n\t\t\teventParticipant.Startup.YearsActive.Set(startupYearsActive.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Accommodation\n\taAccomodationData := amiandoData[\"Accommodation\"]\n\tfor i := 0; i < len(aAccomodationData); i++ {\n\t\taccommodation, ok := amiandoParticipant.FindUserData(aAccomodationData[i])\n\t\tif ok {\n\n\t\t\teventParticipant.Accommodation.Set(accommodation.String())\n\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\t// Ticket Data\n\teventParticipant.Ticket.AmiandoTicketID.Set(amiandoParticipant.TicketID.String())\n\teventParticipant.Ticket.Type.Set(string(amiandoParticipant.TicketType))\n\teventParticipant.Ticket.InvoiceNumber.Set(amiandoParticipant.InvoiceNumber)\n\teventParticipant.Ticket.RegistrationNumber.Set(amiandoParticipant.RegistrationNumber)\n\tif amiandoParticipant.CheckedDate != \"\" {\n\t\tdate, err := amiandoToModelDateTime(amiandoParticipant.CheckedDate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = eventParticipant.Ticket.CheckedDate.Set(date)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif amiandoParticipant.CancelledDate != \"\" {\n\t\tdate, err := amiandoToModelDateTime(amiandoParticipant.CancelledDate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = eventParticipant.Ticket.CancelledDate.Set(date)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn eventParticipant.Save()\n}", "func (twilio *Twilio) AddConferenceParticipant(conferenceSid string, participant *ConferenceParticipantOptions) (*ConferenceParticipant, *Exception, error) {\n\tform, err := query.Values(participant)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tres, err := twilio.post(form, twilio.buildUrl(fmt.Sprintf(\"Conferences/%s/Participants.json\", conferenceSid)))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdecoder := json.NewDecoder(res.Body)\n\n\tif res.StatusCode != http.StatusCreated {\n\t\texception := new(Exception)\n\t\terr = decoder.Decode(exception)\n\t\treturn nil, exception, err\n\t}\n\n\tconf := new(ConferenceParticipant)\n\terr = decoder.Decode(conf)\n\treturn conf, nil, err\n}", "func (opt OptHint) Option(d *bson.Document) error {\n\tswitch t := (opt).Hint.(type) {\n\tcase string:\n\t\td.Append(bson.EC.String(\"hint\", t))\n\tcase *bson.Document:\n\t\td.Append(bson.EC.SubDocument(\"hint\", t))\n\t}\n\treturn nil\n}", "func (r *ChannelsReportSpamRequest) GetParticipant() (value InputPeerClass) {\n\tif r == nil {\n\t\treturn\n\t}\n\treturn r.Participant\n}", "func (m *MeetingParticipants) GetOrganizer()(MeetingParticipantInfoable) {\n return m.organizer\n}", "func (opt OptAllowPartialResults) Option(d *bson.Document) error {\n\td.Append(bson.EC.Boolean(\"allowPartialResults\", bool(opt)))\n\treturn nil\n}", "func (s *SessionTrackerV1) RemoveParticipant(id string) error {\n\tfor i, participant := range s.Spec.Participants {\n\t\tif participant.ID == id {\n\t\t\ts.Spec.Participants[i], s.Spec.Participants = s.Spec.Participants[len(s.Spec.Participants)-1], s.Spec.Participants[:len(s.Spec.Participants)-1]\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn trace.NotFound(\"participant %v not found\", id)\n}", "func OutcomeOverviewParticipants(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (opt OptOplogReplay) Option(d *bson.Document) error {\n\td.Append(bson.EC.Boolean(\"oplogReplay\", bool(opt)))\n\treturn nil\n}", "func NewParticipant(participantType ParticipantType, ID string, name string, username string) (Participant, error){\n\tif participantType == \"\" {\n\t\treturn nil, errors.New(\"Participant Type must not be empty.\")\n\t}\n\n\tif participantType == UserParticipant {\n\n\t\tif ID != \"\" {\n\t\t\treturn participant{ID:ID, Type:participantType}, nil\n\t\t} else if username != \"\" {\n\t\t\treturn participant{Username:username, Type:participantType}, nil\n\t\t} else {\n\t\t\treturn nil, errors.New(\"Username or ID must not be empty for UserParticipant\")\n\t\t}\n\n\t} else if participantType == TeamParticipant || participantType == EscalationParticipant {\n\n\t\tif ID != \"\" {\n\t\t\treturn participant{ID:ID, Type:participantType}, nil\n\t\t} else if name != \"\" {\n\t\t\treturn participant{Name:name, Type:participantType}, nil\n\t\t} else {\n\t\t\treturn nil, errors.New(\"Name or ID must not be empty for TeamParticipant or EscalationParticipant\")\n\t\t}\n\n\t} else if participantType == NoneParticipant {\n\n\t\treturn participant{Type:participantType}, nil\n\n\t} else {\n\n\t\treturn nil, errors.New(\"ParticipantType must not be empty\")\n\t}\n}", "func (s *CreateParticipantOutput) SetParticipantId(v string) *CreateParticipantOutput {\n\ts.ParticipantId = &v\n\treturn s\n}", "func OutcomeOverviewParticipantsGTE(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func WithActor(actor *url.URL) Opt {\n\treturn func(opts *Options) {\n\t\topts.Actor = actor\n\t}\n}", "func AddParticipant(id bson.ObjectId, userID bson.ObjectId) (Event, User) {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"insapp\").C(\"event\")\n\teventID := bson.M{\"_id\": id}\n\tchange := bson.M{\"$addToSet\": bson.M{\n\t\t\"participants\": userID,\n\t}}\n\tdb.Update(eventID, change)\n\tvar event Event\n\tdb.Find(bson.M{\"_id\": id}).One(&event)\n\tuser := AddEventToUser(userID, event.ID)\n\treturn event, user\n}", "func (duo *DatumUpdateOne) SetParticipantID(id string) *DatumUpdateOne {\n\tduo.mutation.SetParticipantID(id)\n\treturn duo\n}", "func (e *EncryptedChatRequested) GetParticipantID() (value int) {\n\treturn e.ParticipantID\n}", "func (t *Trade) FindParticipant(user *User) (*TradeParticipant, errstack.E) {\n\tif t.Buyer.UserID == user.ID {\n\t\treturn &t.Buyer, nil\n\t}\n\tif t.Seller.UserID == user.ID {\n\t\treturn &t.Seller, nil\n\t}\n\tif user.IsModerator() {\n\t\t// HACK! HD wallets won't work\n\t\t// TODO: Remove it during HD wallet refactoring\n\t\tsw, ok := user.StaticWallets[user.DefaultWalletID]\n\t\tif !ok {\n\t\t\t// Not telling that it's a moderator user\n\t\t\treturn nil, errstack.NewReqF(\"User '%s' doesn't have a default wallet\", user.ID)\n\t\t}\n\t\treturn &TradeParticipant{\n\t\t\tUserID: user.ID,\n\t\t\t//KeyDerivationPath: \"under construction\",\n\t\t\t//WalletID: \"under construction\",\n\t\t\tPubKey: sw.PubKey,\n\t\t}, nil\n\t}\n\treturn nil, errstack.NewReqF(\"User '%s' is not a participant of trade '%s'\", user.ID, t.ID)\n}", "func (m *MeetingParticipants) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetAttendees() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAttendees())\n err := writer.WriteCollectionOfObjectValues(\"attendees\", cast)\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(\"organizer\", m.GetOrganizer())\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}", "func (model *meetingModel) AddParticipatorToMeeting(meeting *Meeting, participator string) {\n\tlogger.Println(\"[meetingmodel] try adding a participator to meeting\", meeting.Title)\n\tcurMeetingParticipators := model.meetings[meeting.Title].Participators\n\tmodel.meetings[meeting.Title].Participators = append(curMeetingParticipators, participator)\n\tmodel.dump()\n\tlogger.Println(\"[meetingmodel] added a participator to meeting\", meeting.Title)\n}", "func (matcher *JoinSession) AddParticipant(maxAmount uint64, sessID SessionID) (*SessionParticipant, error) {\n\n\treq := addParticipantReq{\n\t\tmaxAmount: maxAmount,\n\t\tsessID: sessID,\n\t\tresp: make(chan addParticipantRes),\n\t}\n\tmatcher.addParticipantReq <- req\n\n\tresp := <-req.resp\n\treturn resp.participant, resp.err\n}", "func (g Config) ClientOption(scopes ...string) (option.ClientOption, error) {\n\tif len(g.Token) > 0 {\n\t\treturn g.optionFromToken(scopes...)\n\t}\n\n\tif len(g.JSONAuthPath) > 0 {\n\t\treturn g.optionFromJSON(scopes...)\n\t}\n\n\tif g.FlexibleVM {\n\t\treturn option.WithScopes(scopes...), nil\n\t}\n\n\tif len(scopes) == 0 {\n\t\tscopes = append(scopes, compute.ComputeScope)\n\t}\n\n\treturn option.WithScopes(scopes...), nil\n}", "func (c *Client) UseOpt(opts ...grpc.DialOption) *Client {\n\tc.opts = append(c.opts, opts...)\n\treturn c\n}", "func (res *respondent) SetOption(name string, value interface{}) (err error) {\n\treturn nil\n}", "func (opt OptComment) Option(d *bson.Document) error {\n\td.Append(bson.EC.String(\"comment\", string(opt)))\n\treturn nil\n}", "func RemoveParticipant(id bson.ObjectId, userID bson.ObjectId) (Event, User) {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"insapp\").C(\"event\")\n\teventID := bson.M{\"_id\": id}\n\tchange := bson.M{\"$pull\": bson.M{\n\t\t\"participants\": userID,\n\t}}\n\tdb.Update(eventID, change)\n\tvar event Event\n\tdb.Find(bson.M{\"_id\": id}).One(&event)\n\tuser := RemoveEventFromUser(userID, event.ID)\n\treturn event, user\n}", "func OutcomeOverviewParticipantsLTE(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (s *ParticipantTokenCredentials) SetParticipantToken(v string) *ParticipantTokenCredentials {\n\ts.ParticipantToken = &v\n\treturn s\n}", "func (opt OptCollation) Option(d *bson.Document) error {\n\td.Append(bson.EC.SubDocument(\"collation\", opt.Collation.toDocument()))\n\treturn nil\n}", "func (opt OptUpsert) Option(d *bson.Document) error {\n\td.Append(bson.EC.Boolean(\"upsert\", bool(opt)))\n\treturn nil\n}", "func (c *Client) UseOpt(opt ...grpc.DialOption) *Client {\n\tc.opt = append(c.opt, opt...)\n\treturn c\n}", "func (a *Client) ProjectParticipantPut(params *ProjectParticipantPutParams, authInfo runtime.ClientAuthInfoWriter) (*ProjectParticipantPutOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewProjectParticipantPutParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ProjectParticipant_put\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/project/participant/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json; charset=utf-8\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ProjectParticipantPutReader{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\tsuccess, ok := result.(*ProjectParticipantPutOK)\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 ProjectParticipant_put: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func PrometheusOpt(port *string) Opt {\n\treturn &promInitOpt{\n\t\tport: port,\n\t}\n}", "func (s *StartChatContactOutput) SetParticipantToken(v string) *StartChatContactOutput {\n\ts.ParticipantToken = &v\n\treturn s\n}", "func AddParticipatorToMeeting(title string, participatorNames []string) (err error) {\n\tif err = checkIfLoggedin(); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, participatorName := range participatorNames {\n\t\tentity.AddParticipatorToMeeting(title, participatorName, err)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn nil\n}", "func OutcomeOverviewParticipantsHasSuffix(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (e *EncryptedChat) GetParticipantID() (value int) {\n\treturn e.ParticipantID\n}", "func (a *Application) SetOption(option string, param ...interface{}) {\r\n\toleutil.MustPutProperty(a._Application, option, param...).ToIDispatch()\r\n}", "func NewMeetingParticipants()(*MeetingParticipants) {\n m := &MeetingParticipants{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func TeamSpecializationPEducationStaff() *TeamSpecialization {\n\tv := TeamSpecializationVEducationStaff\n\treturn &v\n}", "func RouteOpt(route Route) Option {\n\treturn func(s *Service) {\n\t\ts.routes = append(s.routes, route)\n\t}\n}", "func (c *Client) Option(string) error {\n\treturn nil\n}", "func (ch *CertHandler) GetParticipantID() string {\n\t// TODO: implement\n\treturn \"participant1\"\n}", "func OutcomeOverviewParticipantsNotIn(vs ...string) predicate.OutcomeOverview {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.OutcomeOverview(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.NotIn(s.C(FieldOutcomeOverviewParticipants), v...))\n\t})\n}", "func OptionSubject(subject *Subject) func(t *Tracker) {\n\treturn func(t *Tracker) { t.Subject = subject }\n}", "func (opt OptSnapshot) Option(d *bson.Document) error {\n\td.Append(bson.EC.Boolean(\"snapshot\", bool(opt)))\n\treturn nil\n}", "func IncludeOpt(vals ...string) Option {\n\treturn &arropt{\n\t\tkey: \"include[]\",\n\t\tvals: vals,\n\t}\n}", "func (opt OptSkip) Option(d *bson.Document) error {\n\td.Append(bson.EC.Int64(\"skip\", int64(opt)))\n\treturn nil\n}", "func (duo *DatumUpdateOne) ClearParticipant() *DatumUpdateOne {\n\tduo.mutation.ClearParticipant()\n\treturn duo\n}", "func (self *Event) updatePersonFromAmiandoParticipant(logger *log.Logger, person *Person, amiandoParticipant *amiando.Participant) error {\n\tperson.Name.SetForPerson(\"\", amiandoParticipant.FirstName, \"\", amiandoParticipant.LastName, \"\")\n\t//debug.Print(\"Person Name: \" + person.Name.String())\n\n\tif !person.HasEmail(amiandoParticipant.Email) {\n\t\terr := person.AddEmail(amiandoParticipant.Email, \"via Amiando\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t////\n\t//// SYNC PERSON DATA\n\t////\n\n\t// PHONE\n\taPhoneData := amiandoData[\"Phone\"]\n\tfor i := 0; i < len(aPhoneData); i++ {\n\t\tif phone, ok := amiandoParticipant.FindUserData(aPhoneData[i]); ok {\n\t\t\tif !person.HasPhone(phone.String()) {\n\t\t\t\tperson.AddPhone(phone.String(), \"via Amiando\")\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// TWITTER\n\taTwitterData := amiandoData[\"Twitter\"]\n\tfor i := 0; i < len(aTwitterData); i++ {\n\t\tif amiandotwitter, ok := amiandoParticipant.FindUserData(aTwitterData[i]); ok {\n\t\t\ttwitter := amiandotwitter.String()\n\t\t\tpos := strings.LastIndex(twitter, \"@\")\n\t\t\tif pos != -1 {\n\t\t\t\ttwitter = twitter[pos+1:]\n\t\t\t}\n\t\t\ttwitterfound := false\n\t\t\tfor j := 0; j < len(person.Twitter); j++ {\n\t\t\t\tif person.Twitter[j].Name.String() == twitter {\n\t\t\t\t\ttwitterfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !twitterfound {\n\t\t\t\tvar twitterIdentity user.TwitterIdentity\n\t\t\t\ttwitterIdentity.Name.Set(twitter)\n\n\t\t\t\tperson.Twitter = append(person.Twitter, twitterIdentity)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// FACEBOOK\n\taFacebookData := amiandoData[\"Facebook\"]\n\tfor i := 0; i < len(aFacebookData); i++ {\n\t\tif facebook, ok := amiandoParticipant.FindUserData(aFacebookData[i]); ok {\n\t\t\tfacebookfound := false\n\t\t\tfor j := 0; j < len(person.Facebook); j++ {\n\t\t\t\tif person.Facebook[j].Name.String() == facebook.String() {\n\t\t\t\t\tfacebookfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !facebookfound {\n\t\t\t\tvar facebookIdentity user.FacebookIdentity\n\t\t\t\tfacebookIdentity.Name.Set(facebook.String())\n\n\t\t\t\tperson.Facebook = append(person.Facebook, facebookIdentity)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Linked In\n\taLinkedInData := amiandoData[\"LinkedIn\"]\n\tfor i := 0; i < len(aLinkedInData); i++ {\n\t\tif linkedin, ok := amiandoParticipant.FindUserData(aLinkedInData[i]); ok {\n\t\t\tlinkedinfound := false\n\t\t\tfor j := 0; j < len(person.LinkedIn); j++ {\n\t\t\t\tif person.LinkedIn[j].Name.String() == linkedin.String() {\n\t\t\t\t\tlinkedinfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !linkedinfound {\n\t\t\t\tvar linkedinIdentity user.LinkedInIdentity\n\t\t\t\tlinkedinIdentity.Name.Set(linkedin.String())\n\n\t\t\t\tperson.LinkedIn = append(person.LinkedIn, linkedinIdentity)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Address\n\tif address, ok := amiandoParticipant.FindUserData(\"Address\"); ok {\n\t\ta := address.Address()\n\t\tif a.Street != \"\" {\n\t\t\tperson.PostalAddress.FirstLine.Set(a.Street)\n\t\t}\n\t\tif a.Street2 != \"\" {\n\t\t\tperson.PostalAddress.SecondLine.Set(a.Street2)\n\t\t}\n\t\tif a.City != \"\" {\n\t\t\tperson.PostalAddress.City.Set(a.City)\n\t\t}\n\t\tif a.ZipCode != \"\" {\n\t\t\tperson.PostalAddress.ZIP.Set(a.ZipCode)\n\t\t}\n\t\tif a.Country != \"\" {\n\t\t\tperson.PostalAddress.Country.Set(a.Country)\n\t\t}\n\t}\n\n\t// Citizenship\n\taCitizenshipData := amiandoData[\"Citizenship\"]\n\tfor i := 0; i < len(aCitizenshipData); i++ {\n\t\tif country, ok := amiandoParticipant.FindUserData(aCitizenshipData[i]); ok {\n\t\t\tperson.Citizenship.Set(country.String())\n\t\t}\n\t}\n\n\t// Gender\n\taGenderData := amiandoData[\"Gender\"]\n\tfor i := 0; i < len(aGenderData); i++ {\n\t\tif gender, ok := amiandoParticipant.FindUserData(aGenderData[i], amiando.UserDataGender); ok {\n\t\t\tswitch gender.Value.(float64) {\n\t\t\tcase amiando.Male:\n\t\t\t\tperson.Gender.Set(\"Male\")\n\n\t\t\tcase amiando.Female:\n\t\t\t\tperson.Gender.Set(\"Female\")\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Age\n\taAgeData := amiandoData[\"Gender\"]\n\tfor i := 0; i < len(aAgeData); i++ {\n\t\tif age, ok := amiandoParticipant.FindUserData(aAgeData[i]); ok {\n\t\t\ta, err := strconv.ParseInt(age.String(), 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tperson.BirthYear.Set(int64(time.Now().UTC().Year()) - a)\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Date of Birth\n\taBirthData := amiandoData[\"Birthday\"]\n\tfor i := 0; i < len(aBirthData); i++ {\n\t\tif dateOfBirth, ok := amiandoParticipant.FindUserData(aBirthData[i]); ok {\n\t\t\tdate, err := amiandoToModelDate(dateOfBirth.String())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = person.BirthDate.Set(date)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt, err := time.Parse(amiando.DateFormat, dateOfBirth.String())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tperson.BirthYear.Set(int64(t.Year()))\n\t\t}\n\t}\n\n\t// University\n\taUniData := amiandoData[\"University\"]\n\tfor i := 0; i < len(aUniData); i++ {\n\t\tif university, ok := amiandoParticipant.FindUserData(aUniData[i]); ok {\n\t\t\tperson.University.Set(university.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// University\n\taCompanyData := amiandoData[\"Company\"]\n\tfor i := 0; i < len(aCompanyData); i++ {\n\t\tif company, ok := amiandoParticipant.FindUserData(aCompanyData[i]); ok {\n\t\t\tperson.Company.Set(company.String())\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn person.Save()\n}", "func (opt OptBypassDocumentValidation) Option(d *bson.Document) error {\n\td.Append(bson.EC.Boolean(\"bypassDocumentValidation\", bool(opt)))\n\treturn nil\n}", "func OutcomeOverviewParticipantsEqualFold(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.EqualFold(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func OutcomeOverviewParticipantsLT(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (du *DatumUpdate) SetParticipantID(id string) *DatumUpdate {\n\tdu.mutation.SetParticipantID(id)\n\treturn du\n}", "func MarshalerOpt(m Marshaler) Option {\n\treturn func(o *options) {\n\t\to.marshaler = m\n\t}\n}", "func (*TeleportRoleMarshaler) MarshalRole(u Role, opts ...MarshalOption) ([]byte, error) {\n\treturn json.Marshal(u)\n}", "func (s *ParticipantTimerValue) SetParticipantTimerAction(v string) *ParticipantTimerValue {\n\ts.ParticipantTimerAction = &v\n\treturn s\n}", "func (m NoPartyIDs) SetPartyRole(v enum.PartyRole) {\n\tm.Set(field.NewPartyRole(v))\n}", "func (s *AppAuthorization) SetPersona(v string) *AppAuthorization {\n\ts.Persona = &v\n\treturn s\n}", "func (du *DatumUpdate) ClearParticipant() *DatumUpdate {\n\tdu.mutation.ClearParticipant()\n\treturn du\n}", "func (m *IncomingContext) SetSourceParticipantId(value *string)() {\n m.sourceParticipantId = value\n}", "func (e *EncryptedChatWaiting) GetParticipantID() (value int) {\n\treturn e.ParticipantID\n}", "func InstanceRole(role string) RequestOptionFunc {\n\treturn func(body *RequestBody) error {\n\t\tbody.Role = role\n\t\treturn nil\n\t}\n}", "func (mb *messageBuilder) SetRoleProof(sig types.VrfSignature) *messageBuilder {\n\tmb.msg.Eligibility.Proof = sig\n\treturn mb\n}", "func Registrant(contact Contact) DomainPurchaseOpt {\n\treturn func(rec *DomainPurchase) error {\n\t\trec.RegistrantContact = &contact\n\t\treturn nil\n\t}\n}", "func WithIntentProcessor(s intentProcessor) Option {\n\treturn func(o *options) {\n\t\to.intent = s\n\t}\n}", "func OutcomeOverviewParticipantsContains(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func OutcomeOverviewParticipantsGT(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (opt AddCollaboratorOption) Validate() error {\n\tif opt.Permission != nil {\n\t\tif *opt.Permission == AccessModeOwner {\n\t\t\t*opt.Permission = AccessModeAdmin\n\t\t\treturn nil\n\t\t}\n\t\tif *opt.Permission == AccessModeNone {\n\t\t\topt.Permission = nil\n\t\t\treturn nil\n\t\t}\n\t\tif *opt.Permission != AccessModeRead && *opt.Permission != AccessModeWrite && *opt.Permission != AccessModeAdmin {\n\t\t\treturn fmt.Errorf(\"permission mode invalid\")\n\t\t}\n\t}\n\treturn nil\n}", "func (opt OptOrdered) Option(d *bson.Document) error {\n\td.Append(bson.EC.Boolean(\"ordered\", bool(opt)))\n\treturn nil\n}", "func WriterOpt(w io.Writer) Option {\n\treturn func(o *options) {\n\t\to.writer = w\n\t}\n}", "func RetrierOption(retrier *retry.Retrier) ClientOption {\n\treturn func(client *Client) {\n\t\tclient.Retrier = retrier\n\t}\n}", "func (opt OptNameOnly) Option(d *bson.Document) error {\n\td.Append(bson.EC.Boolean(\"nameOnly\", bool(opt)))\n\treturn nil\n}", "func (e Elem) Participants(raw *tg.Client) (*participants.GetParticipantsQueryBuilder, bool) {\n\tchannel, ok := peer.ToInputChannel(e.Peer)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn participants.NewQueryBuilder(raw).GetParticipants(channel), true\n}", "func (opt OptMaxTime) Option(d *bson.Document) error {\n\td.Append(bson.EC.Int64(\"maxTimeMS\", int64(time.Duration(opt)/time.Millisecond)))\n\treturn nil\n}", "func (pgq *PlayGroupQuery) WithParticipants(opts ...func(*PetQuery)) *PlayGroupQuery {\n\tquery := &PetQuery{config: pgq.config}\n\tfor _, opt := range opts {\n\t\topt(query)\n\t}\n\tpgq.withParticipants = query\n\treturn pgq\n}", "func WithUserProfileService(userProfileService UserProfileService) CESOptionFunc {\n\treturn func(f *CompositeExperimentService) {\n\t\tf.userProfileService = userProfileService\n\t}\n}", "func NewParticipant(participant_number int) *Participant {\n\tp := new(Participant)\n\tp.i = participant_number\n\tp.pid = []byte(\"XXXsomethingunique\")\n\n\t// Generate long-term private/public keypair\n\tp.sk = rand_int(group_q)\n\tp.pk = new(big.Int).Exp(group_g, p.sk, group_p)\n\n\tdebug.Printf(\"Created participant %d:\\nsk = %x\\npk = %x\\n\",\n\t\tp.i, p.sk, p.pk)\n\n\treturn p\n}" ]
[ "0.6225694", "0.5972394", "0.5920174", "0.58749056", "0.5850301", "0.582409", "0.577012", "0.5664515", "0.5388283", "0.532105", "0.53170985", "0.5031255", "0.49427384", "0.4867233", "0.4839651", "0.47024885", "0.46469593", "0.46357363", "0.4633046", "0.4591002", "0.45416632", "0.45410547", "0.45388943", "0.45299786", "0.4502833", "0.4494319", "0.4465583", "0.44564506", "0.44169953", "0.44129243", "0.44042006", "0.43912107", "0.43691134", "0.4366773", "0.43471405", "0.43341962", "0.4332858", "0.43307102", "0.43100166", "0.4272979", "0.42502373", "0.42434543", "0.42389402", "0.42389223", "0.4236876", "0.42294565", "0.4222306", "0.42204225", "0.42173848", "0.42124772", "0.42113402", "0.41924748", "0.4183994", "0.41654843", "0.41522884", "0.41396835", "0.41130254", "0.41119638", "0.41027084", "0.40941942", "0.40934652", "0.4076373", "0.40684086", "0.40639994", "0.4060664", "0.4056924", "0.40506393", "0.40496886", "0.40433434", "0.4039356", "0.40330213", "0.40267673", "0.4026766", "0.40160277", "0.40130103", "0.40055615", "0.40027422", "0.3995292", "0.39889553", "0.39834785", "0.39832377", "0.3976414", "0.39589316", "0.39237416", "0.39220983", "0.39187938", "0.39163777", "0.39004284", "0.39002246", "0.38983804", "0.38949353", "0.38901043", "0.3889877", "0.3889509", "0.38867462", "0.38859105", "0.3885124", "0.38672522", "0.3864767", "0.3859334" ]
0.80076027
0
NonParticipant specifies the participation role for the calendar user specified by the property is a nonparticipant, NONPARTICIPANT.
NonParticipant определяет роль участия для календарного пользователя, указанного свойством является неучастником, NONPARTICIPANT.
func NonParticipant() parameter.Parameter { return Other("NON-PARTICIPANT") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (rec *RawEventCreate) SetNonInteractive(b bool) *RawEventCreate {\n\trec.mutation.SetNonInteractive(b)\n\treturn rec\n}", "func OutcomeOverviewParticipantsNotIn(vs ...string) predicate.OutcomeOverview {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.OutcomeOverview(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.NotIn(s.C(FieldOutcomeOverviewParticipants), v...))\n\t})\n}", "func OutcomeOverviewParticipantsNEQ(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.User) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Patientofphysician) predicate.Patientofphysician {\n\treturn predicate.Patientofphysician(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (s *Rule) SetNonTalkTimeFilter(v *NonTalkTimeFilter) *Rule {\n\ts.NonTalkTimeFilter = v\n\treturn s\n}", "func Not(p predicate.Permission) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func Not(p predicate.Account) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.CoveredPerson) predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Property) predicate.Property {\n\treturn predicate.Property(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (a Possibility) Not() Possibility {\n\tswitch a {\n\tcase False:\n\t\treturn True\n\tcase True:\n\t\treturn False\n\tcase Impossible:\n\t\treturn Impossible\n\tdefault:\n\t\treturn Maybe\n\t}\n}", "func OptParticipant() parameter.Parameter {\n\treturn Other(\"OPT-PARTICIPANT\")\n}", "func Not(e TemporalExpression) NotExpression {\n\treturn NotExpression{e}\n}", "func Not(p predicate.ProfileUKM) predicate.ProfileUKM {\n\treturn predicate.ProfileUKM(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.OnlineSession) predicate.OnlineSession {\n\treturn predicate.OnlineSession(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.RoomStatus) predicate.RoomStatus {\n\treturn predicate.RoomStatus(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (user *User) IsParticipant() bool {\n\treturn user.Role == UserRoleParticipant\n}", "func not(e semantic.Expression) semantic.Expression {\n\treturn &semantic.UnaryOp{Type: semantic.BoolType, Expression: e, Operator: ast.OpNot}\n}", "func Not(p predicate.ValidMessage) predicate.ValidMessage {\n\treturn predicate.ValidMessage(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Ethnicity) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (self *Event) NotPitchingTeamIterator() model.Iterator {\n\treturn EventTeams.Filter(\"Event\", self.ID).Filter(\"Pitching\", false).SortFunc(compareTeamNames)\n}", "func (ctx *ValidatorContext) Not() *ValidatorContext {\n\tctx.boolOperation = false\n\treturn ctx\n}", "func Not(p predicate.OutcomeOverview) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func NotExpected(message string) *Rule {\n\treturn NewRule(func(field string, value *gjson.Result, parent *gjson.Result, source *gjson.Result, violations *Violations, validator *Validator) {\n\t\tif value.Exists() {\n\t\t\tviolations.Add(field, message)\n\t\t}\n\t})\n}", "func NotAuthorized(name string) string {\n\treturn \"user \" + name + \" not authorized\"\n}", "func Not(p predicate.Announcement) predicate.Announcement {\n\treturn predicate.Announcement(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Agent) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func DisabledNEQ(v bool) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldDisabled), v))\n\t})\n}", "func (m Message) NoRequestedPartyRoles() (*field.NoRequestedPartyRolesField, quickfix.MessageRejectError) {\n\tf := &field.NoRequestedPartyRolesField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func Not(p predicate.Patient) predicate.Patient {\n\treturn predicate.Patient(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Patient) predicate.Patient {\n\treturn predicate.Patient(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func NonNegative(paraValue int) (NonNeg int) {\n\tif paraValue < 0 {\n\t\treturn 0\n\t} else {\n\t\treturn paraValue\n\t}\n}", "func Not(p predicate.Token) predicate.Token {\n\treturn predicate.Token(\n\t\tfunc(s *sql.Selector) {\n\t\t\tp(s.Not())\n\t\t},\n\t)\n}", "func Not(p predicate.OfflineSession) predicate.OfflineSession {\n\treturn predicate.OfflineSession(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (d *WindowsDesktopV3) NonAD() bool {\n\treturn d.Spec.NonAD\n}", "func Not(p predicate.Menugroup) predicate.Menugroup {\n\treturn predicate.Menugroup(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Token) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(a *ROBDD) (*ROBDD, error) {\n\treturn &ROBDD{a.Vocabulary, seq.Not(a.Node)}, nil\n}", "func NewNotRule(nestedRule DynamicRule) DynamicRule {\n\tr := []DynamicRule{nestedRule}\n\tcdr := newCompoundDynamicRule(r)\n\n\tndr := notDynamicRule{\n\t\tcompoundDynamicRule: cdr,\n\t}\n\treturn &ndr\n}", "func Not(p predicate.Pet) predicate.Pet {\n\treturn predicate.Pet(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (a *Principal) IsNegate() bool {\n return a!=nil && a.negate\n}", "func Not(p predicate.Media) predicate.Media {\n\treturn predicate.Media(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func CoveredPersonNumberNotIn(vs ...string) predicate.CoveredPerson {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.CoveredPerson(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.NotIn(s.C(FieldCoveredPersonNumber), v...))\n\t})\n}", "func (f BooleanField) Not() Predicate {\n\tf.negative = !f.negative\n\treturn f\n}", "func Not(p *Pattern) *Pattern {\n\treturn Seq(\n\t\t&IChoice{3},\n\t\tp,\n\t\t&IFailTwice{},\n\t)\n}", "func Not(p predicate.Task) predicate.Task {\n\treturn predicate.Task(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func NonTerm(name string) Pattern {\n\treturn &NonTermNode{\n\t\tName: name,\n\t}\n}", "func NewOutcomeNotCompleted() Outcome { return Outcome{Winner: Transparent, Reason: notCompleted} }", "func WorkplaceNotIn(vs ...string) predicate.User {\n\treturn predicate.User(sql.FieldNotIn(FieldWorkplace, vs...))\n}", "func Not(p Pattern) Pattern {\n\treturn &NotNode{\n\t\tPatt: p,\n\t}\n}", "func Not(m Matcher) Matcher {\n\treturn func(i echo.Instance) bool {\n\t\treturn !m(i)\n\t}\n}", "func Not(p predicate.Conversion) predicate.Conversion {\n\treturn predicate.Conversion(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (s *SentimentFilter) SetParticipantRole(v string) *SentimentFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func Not(p predicate.Rent) predicate.Rent {\n\treturn predicate.Rent(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (app App) IsNotMember(userUuid string) bool {\n\tfor _, member := range app.Members {\n\t\tif member.Uuid == userUuid {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Not(p predicate.FlowInstance) predicate.FlowInstance {\n\treturn predicate.FlowInstance(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func CoveredPersonNoteNotIn(vs ...string) predicate.CoveredPerson {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.CoveredPerson(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.NotIn(s.C(FieldCoveredPersonNote), v...))\n\t})\n}", "func Not(p predicate.Step) predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.AppointmentResults) predicate.AppointmentResults {\n\treturn predicate.AppointmentResults(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (s *TranscriptFilter) SetParticipantRole(v string) *TranscriptFilter {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func Not(x meta.ConstValue) meta.ConstValue {\n\tv, ok := x.ToBool()\n\tif !ok {\n\t\treturn meta.UnknownValue\n\t}\n\treturn meta.NewBoolConst(!v)\n}", "func Not(p predicate.GameServer) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.ProcedureType) predicate.ProcedureType {\n\treturn predicate.ProcedureType(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Equipmenttype) predicate.Equipmenttype {\n\treturn predicate.Equipmenttype(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Medicalfile) predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(expectedValue Matcher) *notValueMatcher {\n\tm := new(notValueMatcher)\n\tm.expectedValue = expectedValue\n\treturn m\n}", "func Not(p predicate.ResultsDefinition) predicate.ResultsDefinition {\n\treturn predicate.ResultsDefinition(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (FolderPropertyOption) Unspecified() FolderPropertyOption { return FolderPropertyOption(0) }", "func Not(p predicate.Opt) predicate.Opt {\n\treturn predicate.Opt(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Babystatus) predicate.Babystatus {\n\treturn predicate.Babystatus(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (o GetDeliveriesDeliveryOutput) NonCompliantNotification() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v GetDeliveriesDelivery) bool { return v.NonCompliantNotification }).(pulumi.BoolOutput)\n}", "func (o GetAggregateDeliveriesDeliveryOutput) NonCompliantNotification() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v GetAggregateDeliveriesDelivery) bool { return v.NonCompliantNotification }).(pulumi.BoolOutput)\n}", "func (v *VerbalExpression) Not(value string) *VerbalExpression {\n\t//return v.add(`(?!(` + quote(value) + `))`)\n\t// because Golang doesn't implement ?!\n\t// we create a pseudo negative system...\n\n\trunes := []rune(quote(value))\n\tparts := make([]string, 0)\n\tprev := \"\"\n\tfor _, r := range runes {\n\t\tparts = append(parts, prev+\"[^\"+string(r)+\"]\")\n\t\tprev += string(r)\n\t}\n\n\texp := strings.Join(parts, \"|\")\n\texp = \"(?:\" + exp + \")*?\"\n\treturn v.add(exp)\n}", "func RoleIDNEQ(v uuid.UUID) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldRoleID), v))\n\t})\n}", "func Not(p predicate.Surgeryappointment) predicate.Surgeryappointment {\n\treturn predicate.Surgeryappointment(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (page RoleEligibilityScheduleListResultPage) NotDone() bool {\n\treturn !page.reslr.IsEmpty()\n}", "func (c *SharedAlbumsListCall) ExcludeNonAppCreatedData(excludeNonAppCreatedData bool) *SharedAlbumsListCall {\n\tc.urlParams_.Set(\"excludeNonAppCreatedData\", fmt.Sprint(excludeNonAppCreatedData))\n\treturn c\n}", "func NewNotRule(rule IValidationRule) *NotRule {\n\treturn &NotRule{\n\t\trule: rule,\n\t}\n}", "func Not(p predicate.Repairinvoice) predicate.Repairinvoice {\n\treturn predicate.Repairinvoice(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (s *ChannelDefinition) SetParticipantRole(v string) *ChannelDefinition {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func TeamNotIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(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.NotIn(s.C(FieldTeam), v...))\n\t})\n}", "func Not(p predicate.Job) predicate.Job {\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Prohibited() Constraint {\n\treturn prohibited{}\n}", "func (c StoppingCondition) Not() StoppingCondition {\n\treturn StoppingCondition{\n\t\tIsMet: func(statistic IterationStatistic) bool { return !c.IsMet(statistic) },\n\t}\n}", "func (s *ParticipantTimerConfiguration) SetParticipantRole(v string) *ParticipantTimerConfiguration {\n\ts.ParticipantRole = &v\n\treturn s\n}", "func Not(p predicate.BaselineClass) predicate.BaselineClass {\n\treturn predicate.BaselineClass(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func (page RoleEligibilityScheduleInstanceListResultPage) NotDone() bool {\n\treturn !page.resilr.IsEmpty()\n}", "func (op *ListOp) NotGroupID(val string) *ListOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"not_group_id\", val)\n\t}\n\treturn op\n}", "func (parser *Parser) not_expr() (*SubExpr, error) {\n\tparser.trace(\"NOT_EXPR\")\n\tdefer parser.untrace()\n\n\top, err := parser.not_op()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tval, err := parser.val()\n\tif op != fxsymbols.None && err == ErrNoMatch {\n\t\treturn nil, parser.Errorf(ErrNoVal)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op == fxsymbols.None {\n\t\treturn val, nil\n\t}\n\treturn NewExprSubExpr(NewExpr(op, val, nil)), nil\n}", "func (cluster *HttpCluster) NonActive() []string {\n\tcluster.RLock()\n\tdefer cluster.RUnlock()\n\tmember := cluster.active\n\tlist := make([]string, 0)\n\tfor i := 0; i < cluster.size; i++ {\n\t\tif member.status == MEMBER_UNAVAILABLE {\n\t\t\tlist = append(list, member.hostname)\n\t\t}\n\t}\n\treturn list\n}" ]
[ "0.54938054", "0.5477978", "0.5378485", "0.5321094", "0.5321094", "0.5321094", "0.5321094", "0.5321094", "0.5321094", "0.5321094", "0.5321094", "0.5321094", "0.5321094", "0.5267588", "0.52520335", "0.52256835", "0.51861835", "0.51774764", "0.5175691", "0.516526", "0.5157808", "0.5142492", "0.51109", "0.5082491", "0.5071004", "0.50614226", "0.5050573", "0.50335705", "0.50274503", "0.49910793", "0.49862266", "0.4979742", "0.49547175", "0.49497092", "0.49472743", "0.49388883", "0.4909614", "0.4895973", "0.48934942", "0.48921522", "0.48921522", "0.48672748", "0.48653916", "0.48546693", "0.48524642", "0.48483944", "0.48403013", "0.48384896", "0.48358533", "0.48312616", "0.48298138", "0.48271632", "0.4816363", "0.4816331", "0.4808582", "0.4805629", "0.48042318", "0.48031512", "0.48012283", "0.47978708", "0.47974896", "0.47950605", "0.47876316", "0.47875294", "0.4769598", "0.47674054", "0.47524825", "0.47524235", "0.47521377", "0.47446826", "0.4743273", "0.4740111", "0.47397783", "0.47340086", "0.47290862", "0.47236338", "0.47233662", "0.47226757", "0.47136143", "0.47121397", "0.4707589", "0.4706153", "0.47002637", "0.4697696", "0.46915534", "0.46847087", "0.4681452", "0.46758306", "0.46753168", "0.46710515", "0.4643178", "0.46385273", "0.46333516", "0.46313465", "0.46313092", "0.46193436", "0.46185082", "0.46161437", "0.46148503", "0.46125028" ]
0.7944042
0
EscrowBalance returns the escrow balance for the ID.
EscrowBalance возвращает баланс эскроу для идентификатора.
func (s *ImmutableState) EscrowBalance(id signature.PublicKey) *quantity.Quantity { account := s.Account(id) return account.Escrow.Active.Balance.Clone() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetAccountBalanceById(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\n\taccountID, erro := strconv.ParseUint(params[\"accountID\"], 10, 64)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, erro)\n\t\treturn\n\t}\n\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repositories.NewAccountRepository(db)\n\taccount, erro := repository.FindBalanceById(accountID)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusOK, account)\n}", "func (eth *EthClient) GetERC20Balance(address common.Address, contractAddress common.Address) (*big.Int, error) {\n\tresult := \"\"\n\tnumLinkBigInt := new(big.Int)\n\tfunctionSelector := models.HexToFunctionSelector(\"0x70a08231\") // balanceOf(address)\n\tdata, err := utils.ConcatBytes(functionSelector.Bytes(), common.LeftPadBytes(address.Bytes(), utils.EVMWordByteLen))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\targs := callArgs{\n\t\tTo: contractAddress,\n\t\tData: data,\n\t}\n\terr = eth.Call(&result, \"eth_call\", args, \"latest\")\n\tif err != nil {\n\t\treturn numLinkBigInt, err\n\t}\n\tnumLinkBigInt.SetString(result, 0)\n\treturn numLinkBigInt, nil\n}", "func (c *Client) GetBalance() (*BalanceSheet, error) {\n\turl := fmt.Sprintf(\"%v%v\", c.Host, totalOwedURL())\n\tledgerRequest, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not make ledger request: %v\", err)\n\t}\n\tledgerResponse, err := c.Do(ledgerRequest)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error making request: %v\", err)\n\t}\n\tif ledgerResponse.StatusCode >= 400 {\n\t\treturn nil, fmt.Errorf(\"bad response code from ledger request: %v\", ledgerResponse.StatusCode)\n\t}\n\tdefer ledgerResponse.Body.Close()\n\tledgerBody, err := ioutil.ReadAll(ledgerResponse.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ledger response body: %v\", err)\n\t}\n\tbalance, err := balanceFromHTML(ledgerBody)\n\tif err != nil {\n\t\tfmt.Println(\" == == == Ledger Body == == ==\")\n\t\tfmt.Println(string(ledgerBody))\n\t\tfmt.Println(\" == == == == == == == == == ==\")\n\t\treturn nil, err\n\t}\n\treturn balance, nil\n}", "func (c *Client) RetrieveBalance(\n\tctx context.Context,\n\tid string,\n) (*BalanceResource, error) {\n\towner, _, err := NormalizedOwnerAndTokenFromID(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\t_, host, err := UsernameAndMintHostFromAddress(ctx, owner)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\",\n\t\tFullMintURL(ctx,\n\t\t\thost, fmt.Sprintf(\"/balances/%s\", id), url.Values{}).String(), nil)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treq.Header.Add(\"Mint-Protocol-Version\", ProtocolVersion)\n\tr, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefer r.Body.Close()\n\n\tvar raw svc.Resp\n\tif err := json.NewDecoder(r.Body).Decode(&raw); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tif r.StatusCode != http.StatusOK && r.StatusCode != http.StatusCreated {\n\t\tvar e errors.ConcreteUserError\n\t\terr = raw.Extract(\"error\", &e)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn nil, errors.Trace(ErrMintClient{\n\t\t\tr.StatusCode, e.ErrCode, e.ErrMessage,\n\t\t})\n\t}\n\n\tvar balance BalanceResource\n\tif err := raw.Extract(\"balance\", &balance); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &balance, nil\n}", "func (_OrderValidationUtils *OrderValidationUtilsSession) GetBalance(ownerAddress common.Address, assetData []byte) (*big.Int, error) {\n\treturn _OrderValidationUtils.Contract.GetBalance(&_OrderValidationUtils.CallOpts, ownerAddress, assetData)\n}", "func (c Client) GetBalance(addr string) (*big.Int, error) {\n\tvar result hexutil.Big\n\terr := c.Call(&result, \"eth_getBalance\", addr, \"latest\")\n\treturn (*big.Int)(&result), err\n}", "func (_Withdrawable *WithdrawableSession) GetDepositedBalance(arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\treturn _Withdrawable.Contract.GetDepositedBalance(&_Withdrawable.CallOpts, arg0, arg1)\n}", "func Erc20Balance(userAddress string, contractAddress string) (*BalanceAmount, error) {\n\tvar resp string\n\tparams := map[string]string{\"to\": contractAddress, \"data\": utils.PaddingData(ERC20MethodBalanceOf, userAddress)}\n\terr := endpointsManager.RPC(&resp, \"eth_call\", params, \"latest\")\n\tif err != nil {\n\t\tcommon.Logger.Debug(err)\n\t\treturn &BalanceAmount{}, err\n\t}\n\n\tamount := \"0\"\n\tt, ok := utils.ParseBig256(resp)\n\tif ok && t != nil {\n\t\tamount = t.Text(10)\n\t}\n\treturn &BalanceAmount{Amount: amount}, err\n}", "func (_DevUtils *DevUtilsTransactorSession) GetBalance(ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.Contract.GetBalance(&_DevUtils.TransactOpts, ownerAddress, assetData)\n}", "func (_DevUtils *DevUtilsTransactor) GetBalance(opts *bind.TransactOpts, ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.contract.Transact(opts, \"getBalance\", ownerAddress, assetData)\n}", "func (_DevUtils *DevUtilsSession) GetBalance(ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.Contract.GetBalance(&_DevUtils.TransactOpts, ownerAddress, assetData)\n}", "func (_OrderValidationUtils *OrderValidationUtilsCallerSession) GetBalance(ownerAddress common.Address, assetData []byte) (*big.Int, error) {\n\treturn _OrderValidationUtils.Contract.GetBalance(&_OrderValidationUtils.CallOpts, ownerAddress, assetData)\n}", "func (a Account) Balance() (Balance, error) {\n\treq, err := a.client.NewRequest(http.MethodGet, \"balance\", nil)\n\tif err != nil {\n\t\treturn Balance{}, err\n\t}\n\n\tq := req.URL.Query()\n\tq.Add(\"account_id\", a.ID)\n\treq.URL.RawQuery = q.Encode()\n\n\tresp, _ := a.client.Do(req)\n\n\tb := new(bytes.Buffer)\n\tb.ReadFrom(resp.Body)\n\tstr := b.String()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn Balance{}, fmt.Errorf(\"failed to fetch balance: %s\", str)\n\t}\n\n\tvar bal Balance\n\tif err := json.Unmarshal(b.Bytes(), &bal); err != nil {\n\t\treturn Balance{}, err\n\t}\n\n\treturn bal, nil\n}", "func (m *controller) Withdraw(db weave.KVStore, escrow *Escrow, escrowID []byte, dest weave.Address, amounts coin.Coins) error {\n\tavailable := coin.Coins(escrow.Amount).Clone()\n\terr := m.moveCoins(db, Condition(escrowID).Address(), dest, amounts)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// remove coin from remaining balance\n\tfor _, c := range amounts {\n\t\tavailable, err = available.Subtract(*c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tescrow.Amount = available\n\t// if there is something left, just update the balance...\n\tif available.IsPositive() {\n\t\treturn m.bucket.Save(db, orm.NewSimpleObj(escrowID, escrow))\n\t}\n\t// otherwise we finished the escrow and can delete it\n\treturn m.bucket.Delete(db, escrowID)\n}", "func (w *Wallet) Balance() Shivcoin {\n\treturn w.balance\n}", "func (a Account) Balance() string {\n\treturn a.client.Request(\"GET\", \"api/accounts/balance\", \"\")\n}", "func (_Withdrawable *WithdrawableCallerSession) GetDepositedBalance(arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\treturn _Withdrawable.Contract.GetDepositedBalance(&_Withdrawable.CallOpts, arg0, arg1)\n}", "func (_Registry *RegistryCaller) BalanceOf(opts *bind.CallOpts, account common.Address, id *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Registry.contract.Call(opts, &out, \"balanceOf\", account, id)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetBalance(ctx context.Context, table api.BatchBalanceTable, addr types.AccAddress, key uint64) (*api.BatchBalance, error) {\n\tbal, err := table.Get(ctx, addr, key)\n\tif err != nil {\n\t\tif !ormerrors.IsNotFound(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tbal = &api.BatchBalance{\n\t\t\tBatchKey: key,\n\t\t\tAddress: addr,\n\t\t\tTradableAmount: \"0\",\n\t\t\tRetiredAmount: \"0\",\n\t\t\tEscrowedAmount: \"0\",\n\t\t}\n\t}\n\treturn bal, nil\n}", "func (s *Client) GetBalance(ctx context.Context, scripthash string) (GetBalanceResult, error) {\n\tvar resp GetBalanceResp\n\n\terr := s.request(ctx, \"blockchain.scripthash.get_balance\", []interface{}{scripthash}, &resp)\n\tif err != nil {\n\t\treturn GetBalanceResult{}, err\n\t}\n\n\treturn resp.Result, err\n}", "func (r *Cash) Balance() (types.Balance, error) {\n\trequest := apirequest.NewAPIRequest()\n\tresult := types.Balance{}\n\tsetCustomConfigErr := request.SetCustomConfig(r.Config)\n\tif setCustomConfigErr != nil {\n\t\treturn result, setCustomConfigErr\n\t}\n\tparams := map[string]string{}\n\terr := request.GET(\"cash/v1/balance\", params, &result)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn result, nil\n}", "func (theAccount Account) Balance() int {\n\treturn theAccount.balance\n}", "func (a *Ethereum) Balance(addr string) (string, error) {\n\tvar (\n\t\tctx, _ = context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))\n\t)\n\tvar address = common.HexToAddress(addr)\n\tvar bignum, err = ethclient.NewClient(a.rpcclient).BalanceAt(ctx, address, nil)\n\tif err != nil {\n\t\tlog.Printf(\"aqua: %v\", err)\n\t\treturn \"ERR\", err\n\t}\n\tdots := new(big.Float).Quo(new(big.Float).SetInt(bignum), big.NewFloat(OneEther))\n\treturn fmt.Sprintf(\"%.8f\", dots), nil\n}", "func (_DogsOfRome *DogsOfRomeSession) Balance(arg0 common.Address) (*big.Int, error) {\n\treturn _DogsOfRome.Contract.Balance(&_DogsOfRome.CallOpts, arg0)\n}", "func (pr *ProvenAccountResource) GetBalance() uint64 {\n\tif !pr.proven {\n\t\tpanic(\"not valid proven account resource\")\n\t}\n\treturn pr.accountResource.Balance\n}", "func GetBalance(accountKey id.AccountKey) *data.Balance {\n\t// TODO: This is wrong, should pass by type, not encode/decode\n\trequest := action.Message(\"accountKey=\" + hex.EncodeToString(accountKey))\n\tresponse := comm.Query(\"/balance\", request)\n\tif response == nil {\n\t\t// New Accounts don't have a balance yet.\n\t\tresult := data.NewBalance()\n\t\treturn result\n\t}\n\tif serial.GetBaseType(response).Kind() == reflect.String {\n\t\tlog.Error(\"Error:\", \"response\", response)\n\t\treturn nil\n\t}\n\tbalance := response.(*data.Balance)\n\treturn balance\n}", "func (_FCToken *FCTokenSession) GetBalance() (*big.Int, error) {\n\treturn _FCToken.Contract.GetBalance(&_FCToken.CallOpts)\n}", "func GetBalance(tx *gorm.DB, requestCreated *models.TransactionRequests) (responses.TransactionResponse, error) {\n\t//first get Balance of the DebitAccount\n\tresponse := responses.TransactionResponse{}\n\tcbalance := models.Accounts{}\n\n\terr := tx.Debug().Model(&models.Accounts{}).Where(\"account_no = ?\", requestCreated.DebitAccount).Take(&cbalance).Error\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\tresponse.Procode = requestCreated.Procode\n\tresponse.ResponseCode = Successful\n\tresponse.Remarks = \"Balance Enquiry Successful\"\n\tresponse.Reference = requestCreated.TxnRef\n\tamt, _ := strconv.ParseFloat(\"0.00\", 64)\n\tresponse.Amount = amt\n\tresponse.Account = cbalance.AccountNo\n\tbal, _ := strconv.ParseFloat(cbalance.AvailableBal, 64)\n\tresponse.AvailableBalance = bal\n\n\treturn response, nil\n}", "func (ps *PubsubApi) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {\n\tstate, _, err := ps.backend().StateAndHeaderByNumber(ctx, blockNr)\n\tif state == nil || err != nil {\n\t\treturn nil, err\n\t}\n\tb := state.GetBalance(address)\n\treturn b, state.Error()\n}", "func (_Registry *RegistrySession) BalanceOf(account common.Address, id *big.Int) (*big.Int, error) {\n\treturn _Registry.Contract.BalanceOf(&_Registry.CallOpts, account, id)\n}", "func (o *ReservationModel) GetBalance() MonetaryValueModel {\n\tif o == nil {\n\t\tvar ret MonetaryValueModel\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func (dcr *ExchangeWallet) Balance() (*asset.Balance, error) {\n\tbalances, err := dcr.node.GetBalanceMinConf(dcr.ctx, dcr.acct, 0)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\tlocked, err := dcr.lockedAtoms()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar balance asset.Balance\n\tvar acctFound bool\n\tfor i := range balances.Balances {\n\t\tab := &balances.Balances[i]\n\t\tif ab.AccountName == dcr.acct {\n\t\t\tacctFound = true\n\t\t\tbalance.Available = toAtoms(ab.Spendable) - locked\n\t\t\tbalance.Immature = toAtoms(ab.ImmatureCoinbaseRewards) +\n\t\t\t\ttoAtoms(ab.ImmatureStakeGeneration)\n\t\t\tbalance.Locked = locked + toAtoms(ab.LockedByTickets)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !acctFound {\n\t\treturn nil, fmt.Errorf(\"account not found: %q\", dcr.acct)\n\t}\n\n\treturn &balance, err\n}", "func (client *Client) GetBalance(address string) (*big.Int, error) {\n\n\tresponse := &balanceResp{}\n\n\tresp, err := client.client.Post(\"/eth/getBalance\").BodyJSON(&nonceRequest{\n\t\tAddress: address,\n\t}).ReceiveSuccess(response)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif code := resp.StatusCode; 200 < code || code > 299 {\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\n\tjsontext, _ := json.Marshal(response)\n\n\tclient.DebugF(\"response(%d) :%s\", resp.StatusCode, string(jsontext))\n\n\tvar count hexutil.Big\n\n\tcount.UnmarshalText([]byte(response.Value))\n\n\treturn count.ToInt(), nil\n}", "func (t *Trans) GetBalance() (string, error) {\n\tif t.Account == nil {\n\t\treturn \"\", common.ErrInvalidAccount\n\t}\n\treturn t.GetBalanceDetail()\n}", "func (n NemClient) GetBalance(addr string) (*transport.Balance, error) {\n\tvar account NemAccountResponse\n\n\tif err := n.GET(\"/account/get\", map[string]string{\"address\": addr}, &account); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &transport.Balance{\n\t\tData: transport.BalanceData{\n\t\t\tAssets: []transport.Asset{\n\t\t\t\t{\n\t\t\t\t\tAsset: NemAssetID,\n\t\t\t\t\tBalance: fmt.Sprintf(\"%d\", account.Account.Balance),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (a *Account) Balance() numeric.Numeric {\n\treturn a.AccountTransactionList[len(a.AccountTransactionList)-1].Balance\n}", "func (s *StateDB) GetBalance(addr types.AddressHash) *big.Int {\n\tstateObject := s.getStateObject(addr)\n\tif stateObject != nil {\n\t\treturn stateObject.Balance()\n\t}\n\treturn common.Big0\n}", "func (_FCToken *FCTokenCallerSession) GetBalance() (*big.Int, error) {\n\treturn _FCToken.Contract.GetBalance(&_FCToken.CallOpts)\n}", "func (d *AddressCacheItem) Balance() (*dbtypes.AddressBalance, *BlockID) {\n\td.mtx.RLock()\n\tdefer d.mtx.RUnlock()\n\tif d.balance == nil {\n\t\treturn nil, nil\n\t}\n\treturn d.balance, d.blockID()\n}", "func (c *Client) GetBalance(ctx context.Context) (Balances, error) {\n\treq, err := c.newAuthenticatedRequest(ctx, \"GetBalance\", nil)\n\tif err != nil {\n\t\treturn Balances{}, errors.Wrap(err, \"Faild to new authenticated request\")\n\t}\n\n\tvar ret = &Balances{}\n\t_, err = c.do(req, ret)\n\tif err != nil {\n\t\treturn *ret, errors.Wrap(err, \"Faild to do request\")\n\t}\n\treturn *ret, nil\n}", "func (_Vault *VaultSession) GetDepositedBalance(token common.Address, owner common.Address) (*big.Int, error) {\n\treturn _Vault.Contract.GetDepositedBalance(&_Vault.CallOpts, token, owner)\n}", "func (_OrderValidationUtils *OrderValidationUtilsCaller) GetBalance(opts *bind.CallOpts, ownerAddress common.Address, assetData []byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _OrderValidationUtils.contract.Call(opts, out, \"getBalance\", ownerAddress, assetData)\n\treturn *ret0, err\n}", "func (p *P2C) Balance(key string) (string, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tif len(p.hosts) == 0 {\n\t\treturn \"\", liblb.ErrNoHost\n\t}\n\n\t// chosen host\n\tvar host string\n\n\tvar n1, n2 string\n\n\tif len(key) > 0 {\n\t\tn1, n2 = p.hash(key)\n\t} else {\n\t\tn1 = p.hosts[p.rndm.Intn(len(p.hosts))].name\n\t\tn2 = p.hosts[p.rndm.Intn(len(p.hosts))].name\n\t}\n\n\thost = n2\n\n\tif p.loadMap[n1].load <= p.loadMap[n2].load {\n\t\thost = n1\n\t}\n\n\tp.loadMap[host].load++\n\treturn host, nil\n}", "func (_Withdrawable *WithdrawableCaller) GetDepositedBalance(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Withdrawable.contract.Call(opts, out, \"getDepositedBalance\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_Registry *RegistryCallerSession) BalanceOf(account common.Address, id *big.Int) (*big.Int, error) {\n\treturn _Registry.Contract.BalanceOf(&_Registry.CallOpts, account, id)\n}", "func (_Vault *VaultCallerSession) GetDepositedBalance(token common.Address, owner common.Address) (*big.Int, error) {\n\treturn _Vault.Contract.GetDepositedBalance(&_Vault.CallOpts, token, owner)\n}", "func (eth *EthClient) GetEthBalance(address common.Address) (*assets.Eth, error) {\n\tbalance, err := eth.GetWeiBalance(address)\n\tif err != nil {\n\t\treturn assets.NewEth(0), err\n\t}\n\treturn (*assets.Eth)(balance), nil\n}", "func (c *CoordinatorHelper) Balance(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) (*types.Amount, error) {\n\tamount, _, err := c.balanceStorage.GetBalanceTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t\tcurrency,\n\t\tnil,\n\t)\n\n\treturn amount, err\n}", "func (a *Account) GetBalance() uint64 {\n\treturn a.account.GetBalance()\n}", "func (o *AUMPortfolioRisk) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func (dcr *ExchangeWallet) Balance() (*asset.Balance, error) {\n\tlocked, err := dcr.lockedAtoms(dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tab, err := dcr.wallet.AccountBalance(dcr.ctx, 0, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbal := &asset.Balance{\n\t\tAvailable: toAtoms(ab.Spendable) - locked,\n\t\tImmature: toAtoms(ab.ImmatureCoinbaseRewards) +\n\t\t\ttoAtoms(ab.ImmatureStakeGeneration),\n\t\tLocked: locked + toAtoms(ab.LockedByTickets),\n\t}\n\n\tif dcr.unmixedAccount == \"\" {\n\t\treturn bal, nil\n\t}\n\n\t// Mixing is enabled, consider ...\n\t// 1) trading account spendable (-locked) as available,\n\t// 2) all unmixed funds as immature, and\n\t// 3) all locked utxos in the trading account as locked (for swapping).\n\ttradingAcctBal, err := dcr.wallet.AccountBalance(dcr.ctx, 0, dcr.tradingAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttradingAcctLocked, err := dcr.lockedAtoms(dcr.tradingAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tunmixedAcctBal, err := dcr.wallet.AccountBalance(dcr.ctx, 0, dcr.unmixedAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbal.Available += toAtoms(tradingAcctBal.Spendable) - tradingAcctLocked\n\tbal.Immature += toAtoms(unmixedAcctBal.Total)\n\tbal.Locked += tradingAcctLocked\n\treturn bal, nil\n}", "func (_DogsOfRome *DogsOfRomeCallerSession) Balance(arg0 common.Address) (*big.Int, error) {\n\treturn _DogsOfRome.Contract.Balance(&_DogsOfRome.CallOpts, arg0)\n}", "func (_Token *TokenSession) GetBalance() (struct {\n\tTokenList [][32]byte\n\tBalances []*big.Int\n}, error) {\n\treturn _Token.Contract.GetBalance(&_Token.CallOpts)\n}", "func (s *StateDB) SubBalance(addr types.AddressHash, amount *big.Int) {\n\tstateObject := s.getOrNewStateObject(addr)\n\tif stateObject != nil {\n\t\tstateObject.SubBalance(amount)\n\t}\n}", "func (c *rpcclient) dumbBalance(ctx context.Context, ec *ethConn, assetID uint32, addr common.Address) (bal *big.Int, err error) {\n\tif assetID == BipID {\n\t\treturn ec.BalanceAt(ctx, addr, nil)\n\t}\n\ttkn := ec.tokens[assetID]\n\tif tkn == nil {\n\t\treturn nil, fmt.Errorf(\"no tokener for asset ID %d\", assetID)\n\t}\n\treturn tkn.balanceOf(ctx, addr)\n}", "func (_FCToken *FCTokenCaller) GetBalance(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"getBalance\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func Balance() int {\n\treturn <-balances\n}", "func (i Item) Balance(clnt Client, accountIDs ...string) ([]Account, error) {\n\tbts, err := get(fmt.Sprintf(\"%v/balance/get\", clnt.envURL), clnt, i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbr := balanceResponse{}\n\tif err := json.Unmarshal(bts, &br); err != nil {\n\t\treturn nil, err\n\t}\n\treturn br.Accounts, nil\n}", "func (_Vault *VaultCaller) GetDepositedBalance(opts *bind.CallOpts, token common.Address, owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDepositedBalance\", token, owner)\n\treturn *ret0, err\n}", "func getBalance(account horizon.Account) string {\n\tbalance, _ := account.GetNativeBalance()\n\treturn balance\n}", "func (token *Token) GetBalance(addr crypto.Address) (uint64, error) {\n\tret, _, err := token.invokeContract(addr, \"get_balance\", []string{addr.String()})\n\treturn ret, err\n}", "func (c *Channel) Balance() *big.Int {\n\tx := new(big.Int)\n\tx.Sub(c.OurState.ContractBalance, c.OurState.TransferAmount())\n\tx.Add(x, c.PartnerState.TransferAmount())\n\treturn x\n}", "func (c *Channel) Balance() *big.Int {\n\tx := new(big.Int)\n\tx.Sub(c.OurState.ContractBalance, c.OurState.TransferAmount())\n\tx.Add(x, c.PartnerState.TransferAmount())\n\treturn x\n}", "func (api *PublicEthereumAPI) GetBalance(address common.Address, blockNum rpctypes.BlockNumber) (*hexutil.Big, error) {\n\tapi.logger.Debug(\"eth_getBalance\", \"address\", address, \"block number\", blockNum)\n\n\tclientCtx := api.clientCtx\n\tif !(blockNum == rpctypes.PendingBlockNumber || blockNum == rpctypes.LatestBlockNumber) {\n\t\tclientCtx = api.clientCtx.WithHeight(blockNum.Int64())\n\t}\n\n\tres, _, err := clientCtx.QueryWithData(fmt.Sprintf(\"custom/%s/balance/%s\", evmtypes.ModuleName, address.Hex()), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar out evmtypes.QueryResBalance\n\tapi.clientCtx.Codec.MustUnmarshalJSON(res, &out)\n\tval, err := utils.UnmarshalBigInt(out.Balance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif blockNum != rpctypes.PendingBlockNumber {\n\t\treturn (*hexutil.Big)(val), nil\n\t}\n\n\t// update the address balance with the pending transactions value (if applicable)\n\tpendingTxs, err := api.backend.PendingTransactions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, tx := range pendingTxs {\n\t\tif tx == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif tx.From == address {\n\t\t\tval = new(big.Int).Sub(val, tx.Value.ToInt())\n\t\t}\n\t\tif *tx.To == address {\n\t\t\tval = new(big.Int).Add(val, tx.Value.ToInt())\n\t\t}\n\t}\n\n\treturn (*hexutil.Big)(val), nil\n}", "func EthereumBalance(userAddress string) (*BalanceAmount, error) {\n\tvar resp string\n\terr := endpointsManager.RPC(&resp, \"eth_getBalance\", userAddress, \"latest\")\n\tif err != nil {\n\t\tcommon.Logger.Debug(err)\n\t\treturn &BalanceAmount{}, err\n\t}\n\n\tamount := \"0\"\n\tt, ok := utils.ParseBig256(resp)\n\tif ok && t != nil {\n\t\tamount = t.Text(10)\n\t}\n\treturn &BalanceAmount{Amount: amount}, err\n\n}", "func (a *Api) BalanceAtHeight(address string, height int) ([]Balance, error) {\n\tresponse, err := a.AddressAtHeight(address, height)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response.Balance, nil\n}", "func (_GameJam *GameJamSession) Balance() (*big.Int, error) {\n\treturn _GameJam.Contract.Balance(&_GameJam.CallOpts)\n}", "func (_Token *TokenCallerSession) GetBalance() (struct {\n\tTokenList [][32]byte\n\tBalances []*big.Int\n}, error) {\n\treturn _Token.Contract.GetBalance(&_Token.CallOpts)\n}", "func GetAccountBalance(ee engine.Exchange) sknet.HandlerFunc {\n\treturn func(c *sknet.Context) error {\n\t\trlt := &pp.EmptyRes{}\n\t\tfor {\n\t\t\treq := pp.GetAccountBalanceReq{}\n\t\t\tif err := c.BindJSON(&req); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_WrongRequest)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// validate pubkey\n\t\t\tpubkey := req.GetPubkey()\n\t\t\tif err := validatePubkey(pubkey); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_WrongPubkey)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ta, err := ee.GetAccount(pubkey)\n\t\t\tif err != nil {\n\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_NotExits)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tbal := a.GetBalance(req.GetCoinType())\n\t\t\tbres := pp.GetAccountBalanceRes{\n\t\t\t\tResult: pp.MakeResultWithCode(pp.ErrCode_Success),\n\t\t\t\tBalance: &pp.Balance{Amount: pp.PtrUint64(bal)},\n\t\t\t}\n\t\t\treturn c.SendJSON(&bres)\n\t\t}\n\t\treturn c.Error(rlt)\n\t}\n}", "func (r *Wallet) Balance() Bitcoin {\n\treturn r.balance\n}", "func GetBalance() (uint64, error) {\n\tfwallet, err := os.Open(\"aurum_wallet.json\")\n\tif err != nil {\n\t\treturn 0, errors.New(\"Failed to open wallet file: \" + err.Error())\n\t}\n\tdefer fwallet.Close()\n\n\tjsonEncoded, err := ioutil.ReadAll(fwallet)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Failed to read wallet file: \" + err.Error())\n\t}\n\n\ttype jsonStruct struct {\n\t\tBalance uint64\n\t}\n\n\tvar j jsonStruct\n\terr = json.Unmarshal(jsonEncoded, &j)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Failed to parse data from json file: \" + err.Error())\n\t}\n\n\treturn j.Balance, nil\n}", "func (app *TokenAccountState) GetBalance() *big.Int {\n\treturn &app.Balance\n}", "func (e *RetrieveBalance) Execute(\n\tctx context.Context,\n) (*int, *svc.Resp, error) {\n\tctx = db.Begin(ctx, \"mint\")\n\tdefer db.LoggedRollback(ctx)\n\n\tbalance, err := model.LoadCanonicalBalanceByOwnerToken(ctx,\n\t\te.Owner, e.Token)\n\tif err != nil {\n\t\treturn nil, nil, errors.Trace(err) // 500\n\t} else if balance == nil {\n\t\treturn nil, nil, errors.Trace(errors.NewUserErrorf(nil,\n\t\t\t404, \"balance_not_found\",\n\t\t\t\"The balance you are trying to retrieve does not exist: %s.\",\n\t\t\te.ID,\n\t\t))\n\t}\n\n\tdb.Commit(ctx)\n\n\treturn ptr.Int(http.StatusOK), &svc.Resp{\n\t\t\"balance\": format.JSONPtr(model.NewBalanceResource(ctx, balance)),\n\t}, nil\n}", "func (a *Account) Balance() (balance int64, ok bool) {\n\tif a.isClosed {\n\t\treturn 0, false\n\t}\n\treturn a.sold, true\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (eth *EthClient) GetWeiBalance(address common.Address) (*big.Int, error) {\n\tresult := \"\"\n\tnumWeiBigInt := new(big.Int)\n\terr := eth.Call(&result, \"eth_getBalance\", address.Hex(), \"latest\")\n\tif err != nil {\n\t\treturn numWeiBigInt, err\n\t}\n\tnumWeiBigInt.SetString(result, 0)\n\treturn numWeiBigInt, nil\n}", "func (root *TreeNode) getBalance() int64 {\n\tif root == nil {\n\t\treturn 0\n\t}\n\treturn root.left.getHeight() - root.right.getHeight()\n}", "func (c *Client) GetBalance(ctx context.Context, base58Addr string) (uint64, error) {\n\tres, err := c.RpcClient.GetBalance(ctx, base58Addr)\n\terr = checkRpcResult(res.GeneralResponse, err)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn res.Result.Value, nil\n}", "func (h ReturnEscrowHandler) Deliver(ctx weave.Context, db weave.KVStore, tx weave.Tx) (*weave.DeliverResult, error) {\n\tkey, escrow, err := h.validate(ctx, db, tx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tavailable, err := h.bank.Balance(db, escrow.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// withdraw all coins from escrow to the defined \"source\"\n\tdest := weave.Address(escrow.Source)\n\tif err := cash.MoveCoins(db, h.bank, escrow.Address, dest, available); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := h.bucket.Delete(db, key); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &weave.DeliverResult{}, nil\n}", "func GetBalance(client *rpcclient.Client, addresses []soterutil.Address, params *chaincfg.Params) (soterutil.Amount, soterutil.Amount, error) {\n\tvar balance = soterutil.Amount(0)\n\tvar spendableBalance = soterutil.Amount(0)\n\tvar transactions []TxInfo\n\tvar txIndex = make(map[chainhash.Hash]TxInfo)\n\n\ttransactions, err := AllTransactions(client)\n\tif err != nil {\n\t\treturn balance, spendableBalance, err\n\t}\n\n\tfor _, info := range transactions {\n\t\ttxIndex[info.Tx.TxHash()] = info\n\t}\n\n\tfor _, info := range transactions {\n\t\t// Deduct matching inputs from the balance\n\t\tfor i, txIn := range info.Tx.TxIn {\n\t\t\tif txIn.PreviousOutPoint.Hash.IsEqual(&zeroHash) {\n\t\t\t\t// We don't attempt to find the previous output for the input of the genesis transactions,\n\t\t\t\t// because there won't be any.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprev, ok := txIndex[txIn.PreviousOutPoint.Hash]\n\t\t\tif !ok {\n\t\t\t\terr := fmt.Errorf(\"missing previous transaction %s for transaction %s input %d\",\n\t\t\t\t\ttxIn.PreviousOutPoint.Hash, info.Tx.TxHash(), i)\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tprevOut := prev.Tx\n\t\t\tprevValue := prevOut.TxOut[txIn.PreviousOutPoint.Index].Value\n\n\t\t\tprevPkScript := prevOut.TxOut[txIn.PreviousOutPoint.Index].PkScript\n\t\t\t_, outAddrs, _, err := txscript.ExtractPkScriptAddrs(prevPkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, prevAddress := range outAddrs {\n\t\t\t\tif !IsAddressIn(prevAddress, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprevAmount := soterutil.Amount(prevValue)\n\t\t\t\t// Deduct the input amount from the balance\n\t\t\t\tbalance -= prevAmount\n\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance -= prevAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add matching outputs to the balance\n\t\tfor _, txOut := range info.Tx.TxOut {\n\t\t\t// Extract output addresses from the script in the output\n\t\t\t_, outAddresses, _, err := txscript.ExtractPkScriptAddrs(txOut.PkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, address := range outAddresses {\n\t\t\t\tif !IsAddressIn(address, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tamount := soterutil.Amount(txOut.Value)\n\t\t\t\tbalance += amount\n\n\t\t\t\t// TODO(cedric): Base spendability off of the highest transaction input, not the first\n\t\t\t\tprev := txIndex[info.Tx.TxIn[0].PreviousOutPoint.Hash]\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance += amount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn balance, spendableBalance, nil\n}", "func Updatebalance(c *gin.Context) {\r\n\r\n\tid := c.Params.ByName(\"id\")\r\n\tvar resp models.Response\r\n\tvar flag bool = false\r\n\tvar customer models.Customer\r\n\tnewbalance, errs := strconv.Atoi(c.Params.ByName(\"amount\"))\r\n\tif errs != nil {\r\n\t\tc.AbortWithStatus(http.StatusBadRequest)\r\n\t}\r\n\tif id != \"\" {\r\n\t\tp, err := models.Askdata()\r\n\t\tif err != nil {\r\n\t\t\tc.AbortWithStatus(http.StatusInternalServerError)\r\n\t\t} else {\r\n\t\t\tfor i, val := range p {\r\n\t\t\t\tif val.Id == id {\r\n\t\t\t\t\tp[i].Balance = newbalance\r\n\t\t\t\t\tcustomer = p[i]\r\n\t\t\t\t\tflag = true\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif flag == true {\r\n\t\t\t\tresp.Status = \"success\"\r\n\t\t\t\tresp.Message = \"new balance updated\"\r\n\t\t\t\tresp.Data = append(resp.Data, customer)\r\n\t\t\t\tc.JSON(http.StatusOK, resp)\r\n\t\t\t} else {\r\n\t\t\t\tresp.Status = \"error\"\r\n\t\t\t\tresp.Message = \"Customer does not exist\"\r\n\t\t\t\tc.JSON(http.StatusBadRequest, resp)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}", "func (f *Fund) Balance() int {\r\n\treturn f.balance\r\n}", "func (_DogsOfRome *DogsOfRomeCaller) Balance(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DogsOfRome.contract.Call(opts, out, \"balance\", arg0)\n\treturn *ret0, err\n}", "func (c BaseController) Balance(store weave.KVStore, src weave.Address) (coin.Coins, error) {\n\tstate, err := c.bucket.Get(store, src)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot get account state\")\n\t}\n\tif state == nil {\n\t\treturn nil, errors.Wrap(errors.ErrNotFound, \"no account\")\n\t}\n\treturn AsCoins(state), nil\n}", "func (_Harberger *HarbergerSession) BalanceExpiration(_tokenId *big.Int) (uint64, error) {\n\treturn _Harberger.Contract.BalanceExpiration(&_Harberger.CallOpts, _tokenId)\n}", "func (s *SmartContract) ClientAccountBalance(ctx contractapi.TransactionContextInterface) (int, error) {\n\n\t// Get ID of submitting client identity\n\tclientID, err := ctx.GetClientIdentity().GetID()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to get client id: %v\", err)\n\t}\n\n\tbalanceBytes, err := ctx.GetStub().GetState(clientID)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to read from world state: %v\", err)\n\t}\n\tif balanceBytes == nil {\n\t\treturn 0, fmt.Errorf(\"the account %s does not exist\", clientID)\n\t}\n\n\tbalance, _ := strconv.Atoi(string(balanceBytes)) // Error handling not needed since Itoa() was used when setting the account balance, guaranteeing it was an integer.\n\n\treturn balance, nil\n}", "func (w WavesClient) GetBalance(addr string) (*transport.Balance, error) {\n\tvar res WavesGetBalanceResponse\n\n\terr := w.GET(\"/addresses/balance/details/\"+addr, nil, &res)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error getting waves balance for address\")\n\t}\n\n\treturn &transport.Balance{\n\t\tData: transport.BalanceData{\n\t\t\tAssets: []transport.Asset{\n\t\t\t\t{\n\t\t\t\t\tAsset: WavesAssetID,\n\t\t\t\t\tBalance: fmt.Sprintf(\"%d\", res.Regular),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (_Harberger *HarbergerCaller) BalanceExpiration(opts *bind.CallOpts, _tokenId *big.Int) (uint64, error) {\n\tvar (\n\t\tret0 = new(uint64)\n\t)\n\tout := ret0\n\terr := _Harberger.contract.Call(opts, out, \"balanceExpiration\", _tokenId)\n\treturn *ret0, err\n}", "func (c *Client) GetBalance(addr Address, block string) (*QuantityResponse, error) {\n\trequest := c.newRequest(EthGetBalance)\n\n\trequest.Params = []string{\n\t\tstring(addr),\n\t\tblock,\n\t}\n\n\tresponse := &QuantityResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (s *FundServer) Balance() int {\n\tvar balance int\n\ts.Transact(func(f *Fund) {\n\t\tbalance = f.Balance()\n\t})\n\treturn balance\n}", "func (_ArbSys *ArbSysSession) WithdrawERC721(dest common.Address, id *big.Int) (*types.Transaction, error) {\n\treturn _ArbSys.Contract.WithdrawERC721(&_ArbSys.TransactOpts, dest, id)\n}", "func (_ArbSys *ArbSysTransactor) WithdrawERC721(opts *bind.TransactOpts, dest common.Address, id *big.Int) (*types.Transaction, error) {\n\treturn _ArbSys.contract.Transact(opts, \"withdrawERC721\", dest, id)\n}", "func (_GameJam *GameJamCallerSession) Balance() (*big.Int, error) {\n\treturn _GameJam.Contract.Balance(&_GameJam.CallOpts)\n}", "func (a *Account) Balance() (int, bool) {\n\tif !a.isOpen {\n\t\treturn 0, false\n\t}\n\treturn a.balance, true\n}", "func (w *Wallet) Balance() (balance Bitcoin) {\n\treturn w.balance\n}", "func (_ElvTradable *ElvTradableCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradable.contract.Call(opts, &out, \"balanceOf\", owner)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_ERC20 *ERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ERC20.contract.Call(opts, &out, \"balanceOf\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_IERC20 *IERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _IERC20.contract.Call(opts, &out, \"balanceOf\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}" ]
[ "0.55822587", "0.54363596", "0.54326504", "0.52948654", "0.5267713", "0.52443856", "0.5239745", "0.52388304", "0.5234785", "0.5226584", "0.5223258", "0.51968634", "0.51808625", "0.5170468", "0.51638365", "0.5147292", "0.51023656", "0.5096022", "0.5095926", "0.50698835", "0.5067149", "0.50465006", "0.50428444", "0.50387174", "0.50366414", "0.5025499", "0.50211585", "0.5014738", "0.50072134", "0.50070596", "0.50049204", "0.5000904", "0.4989593", "0.4971977", "0.49701792", "0.49689475", "0.49669176", "0.49574775", "0.49558002", "0.4946388", "0.49361473", "0.4928438", "0.49179396", "0.4914081", "0.491062", "0.48991302", "0.48983693", "0.48955002", "0.48946926", "0.48817793", "0.48760155", "0.48743817", "0.486932", "0.4862679", "0.4862477", "0.48596975", "0.48451555", "0.48371118", "0.4823711", "0.48188698", "0.48162773", "0.48103735", "0.48103735", "0.48088512", "0.48085618", "0.48016134", "0.4798627", "0.47966003", "0.47932556", "0.47931543", "0.47905174", "0.47893417", "0.4788643", "0.4779625", "0.47785348", "0.47785348", "0.47785348", "0.47674727", "0.47632152", "0.4762002", "0.47608104", "0.47577912", "0.47570395", "0.47545096", "0.4753798", "0.47520974", "0.47507724", "0.47464943", "0.47447434", "0.47395492", "0.473913", "0.47370496", "0.47327244", "0.47315627", "0.47206372", "0.471562", "0.47112098", "0.47069594", "0.47066098", "0.47064418" ]
0.80400485
0
TransferFromCommon transfers up to the amount from the global common pool to the general balance of the account, returning true iff the amount transferred is > 0. WARNING: This is an internal routine to be used to implement incentivization policy, and MUST NOT be exposed outside of backend implementations.
TransferFromCommon переносит до указанной суммы из глобального общего пула на общий баланс аккаунта, возвращая true, если сумма переведена больше нуля. ВНИМАНИЕ: Это внутренняя процедура, предназначенная для реализации политики стимулирования, и ЕЕ НЕ СЛЕДУЕТ ЭКСПОНИРОВАТЬ ВНЕ СЕРВЕРНЫХ ИМПЛЕМЕНТАЦИЙ.
func (s *MutableState) TransferFromCommon(ctx *abci.Context, toID signature.PublicKey, amount *quantity.Quantity) (bool, error) { commonPool, err := s.CommonPool() if err != nil { return false, errors.Wrap(err, "staking: failed to query common pool for transfer") } to := s.Account(toID) transfered, err := quantity.MoveUpTo(&to.General.Balance, commonPool, amount) if err != nil { return false, errors.Wrap(err, "staking: failed to transfer from common pool") } ret := !transfered.IsZero() if ret { s.SetCommonPool(commonPool) s.SetAccount(toID, to) if !ctx.IsCheckOnly() { ev := cbor.Marshal(&staking.TransferEvent{ // XXX: Reserve an id for the common pool? To: toID, Tokens: *transfered, }) ctx.EmitEvent(api.NewEventBuilder(AppName).Attribute(KeyTransfer, ev)) } } return ret, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CanTransfer(view *txo.UtxoViewpoint, block *asiutil.Block, db fvm.StateDB, addr common.Address,\n\tamount *big.Int, vtx *virtualtx.VirtualTransaction, calculateBalanceFunc fvm.CalculateBalanceFunc, assets *protos.Asset) bool {\n\tif amount.Cmp(common.Big0) == 0 {\n\t\treturn true\n\t}\n\tif assets == nil {\n\t\treturn false\n\t}\n\tif assets.IsIndivisible() {\n\t\tif amount.Cmp(common.Big0) < 0 || amount.Cmp(common.BigMaxint64) > 0 {\n\t\t\treturn false\n\t\t}\n\t\ttotal := vtx.GetIncoming(addr, assets, amount.Int64())\n\t\tif total.Cmp(amount) == 0 {\n\t\t\treturn true\n\t\t}\n\t\tbalance, _ := calculateBalanceFunc(view, block, addr, assets, amount.Int64())\n\t\treturn amount.Cmp(big.NewInt(balance)) == 0\n\t} else {\n\t\tif amount.Cmp(common.Big0) < 0 || amount.Cmp(common.BigMaxxing) > 0 {\n\t\t\treturn false\n\t\t}\n\n\t\t//check if there's incoming in the previous transfers from the same contract call.\n\t\ttotal := vtx.GetIncoming(addr, assets, amount.Int64())\n\t\tif total.Cmp(amount) >= 0 {\n\t\t\treturn true\n\t\t}\n\n\t\t//now check the balance.\n\t\tbalance, err := calculateBalanceFunc(view, block, addr, assets, amount.Int64())\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\ttotal.Add(total, big.NewInt(balance))\n\t\treturn total.Cmp(amount) >= 0\n\t}\n}", "func Transfer(from interop.Hash160, to interop.Hash160, amount int, data interface{}) bool {\n\treturn token.Transfer(ctx, from, to, amount, data)\n}", "func CanTransfer(db StateDB, addr common.Address, amount *big.Int) bool {\n\treturn db.GetBalance(addr).Cmp(amount) >= 0\n}", "func CanTransfer(db vm.StateDB, addr types.AddressHash, amount *big.Int) bool {\n\treturn db.GetBalance(addr).Cmp(amount) >= 0\n}", "func (s *StorageInMemory) Transfer(accountFrom, accountTo storage.AccountID, amountToTransfer storage.AccountBalance) error {\n\tbalanceFrom, err := s.getBalance(accountFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbalanceTo, err := s.getBalance(accountTo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbalanceFrom.mu.Lock()\n\tbalanceTo.mu.Lock()\n\tdefer balanceFrom.mu.Unlock()\n\tdefer balanceTo.mu.Unlock()\n\n\tif balanceFrom.amount < amountToTransfer {\n\t\treturn ErrNotEnoughBalance\n\t}\n\t// todo del (для отладки)\n\t// fmt.Println(\"операция: \", balanceFrom.amount, balanceTo.amount, balanceFrom.amount+balanceTo.amount)\n\tbalanceFrom.amount -= amountToTransfer\n\tbalanceTo.amount += amountToTransfer\n\treturn nil\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.MainnetCryptoCardsContractTransactor.contract.Transfer(opts)\n}", "func (_ERC20Basic *ERC20BasicSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Basic.Contract.Transfer(&_ERC20Basic.TransactOpts, to, value)\n}", "func (_ERC20Basic *ERC20BasicSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Basic.Contract.Transfer(&_ERC20Basic.TransactOpts, to, value)\n}", "func (_Constants *ConstantsRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Constants.Contract.ConstantsTransactor.contract.Transfer(opts)\n}", "func (_ERC20Basic *ERC20BasicTransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Basic.Contract.Transfer(&_ERC20Basic.TransactOpts, to, value)\n}", "func (_ERC20Basic *ERC20BasicTransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Basic.Contract.Transfer(&_ERC20Basic.TransactOpts, to, value)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.contract.Transfer(opts)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.SafeTransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId, _data)\n}", "func (_SafeERC20 *SafeERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeERC20.Contract.SafeERC20Transactor.contract.Transfer(opts)\n}", "func (_SafeERC20 *SafeERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeERC20.Contract.SafeERC20Transactor.contract.Transfer(opts)\n}", "func (_SafeERC20 *SafeERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeERC20.Contract.SafeERC20Transactor.contract.Transfer(opts)\n}", "func (c *contract) transfer(ctx sdk.Context, from string, to string, value uint64) error {\n\tfromAmount, err := c.State.ReadUint64ByKey(ctx, from)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttoAmount, err := c.State.ReadUint64ByKey(ctx, to)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//totalSupply, err := c.State.ReadUint64ByKey(ctx,\"totalSupply\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//if fromAmount < value {\n\t//\treturn nil\n\t//}\n\t//\n\t//if toAmount+value < totalSupply {\n\t//\treturn nil\n\t//}\n\n\tc.State.WriteUint64ByKey(ctx, from, fromAmount-value)\n\treturn c.State.WriteUint64ByKey(ctx, to, toAmount+value)\n}", "func (_Governable *GovernableRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Governable.Contract.GovernableTransactor.contract.Transfer(opts)\n}", "func (c *ContaCorrente) Transferir(contaDestino *ContaCorrente, valorTransferencia float64) bool {\n\n\tif valorTransferencia > 0 && c.saldo > valorTransferencia {\n\t\tc.Sacar(valorTransferencia)\n\t\tcontaDestino.Depositar(valorTransferencia)\n\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.SafeTransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId, _data)\n}", "func (_ReentrancyGuard *ReentrancyGuardRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _ReentrancyGuard.Contract.ReentrancyGuardTransactor.contract.Transfer(opts)\n}", "func (_DetailedERC20 *DetailedERC20Session) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _DetailedERC20.Contract.Transfer(&_DetailedERC20.TransactOpts, to, value)\n}", "func (_DetailedERC20 *DetailedERC20Session) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _DetailedERC20.Contract.Transfer(&_DetailedERC20.TransactOpts, to, value)\n}", "func (_CrToken *CrTokenSession) Transfer(dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.Transfer(&_CrToken.TransactOpts, dst, amount)\n}", "func (_ERC20 *ERC20Session) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20.Contract.Transfer(&_ERC20.TransactOpts, to, value)\n}", "func (_ERC20 *ERC20Session) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20.Contract.Transfer(&_ERC20.TransactOpts, to, value)\n}", "func (_IERC20 *IERC20Session) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\r\n\treturn _IERC20.Contract.Transfer(&_IERC20.TransactOpts, to, value)\r\n}", "func (_Erc20Mock *Erc20MockSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Erc20Mock.Contract.Transfer(&_Erc20Mock.TransactOpts, to, value)\n}", "func (_ReentrancyGuard *ReentrancyGuardTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _ReentrancyGuard.Contract.contract.Transfer(opts)\n}", "func (_ERC20Interface *ERC20InterfaceSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Interface.Contract.Transfer(&_ERC20Interface.TransactOpts, _to, _value)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId, _data)\n}", "func (unitImpl *UnitImpl) Transfer(unit stardash.Unit, amount int64, material string) bool {\n\treturn unitImpl.RunOnServer(\"transfer\", map[string]interface{}{\n\t\t\"unit\": unit,\n\t\t\"amount\": amount,\n\t\t\"material\": material,\n\t}).(bool)\n}", "func (_FeeCurrencyWhitelist *FeeCurrencyWhitelistRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.Contract.FeeCurrencyWhitelistTransactor.contract.Transfer(opts)\n}", "func (_Constants *ConstantsTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Constants.Contract.contract.Transfer(opts)\n}", "func (_ERC20 *ERC20TransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20.Contract.Transfer(&_ERC20.TransactOpts, to, value)\n}", "func (_ERC20 *ERC20TransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20.Contract.Transfer(&_ERC20.TransactOpts, to, value)\n}", "func (_ERC20Basic *ERC20BasicTransactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Basic.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_ERC20Basic *ERC20BasicTransactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Basic.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_CrToken *CrTokenTransactorSession) Transfer(dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.Transfer(&_CrToken.TransactOpts, dst, amount)\n}", "func (_MiniSafe *MiniSafeRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _MiniSafe.Contract.MiniSafeTransactor.contract.Transfer(opts)\n}", "func (_DetailedERC20 *DetailedERC20TransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _DetailedERC20.Contract.Transfer(&_DetailedERC20.TransactOpts, to, value)\n}", "func (_DetailedERC20 *DetailedERC20TransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _DetailedERC20.Contract.Transfer(&_DetailedERC20.TransactOpts, to, value)\n}", "func (_FeeCurrencyWhitelist *FeeCurrencyWhitelistTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.Contract.contract.Transfer(opts)\n}", "func (_TokensNetwork *TokensNetworkRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.TokensNetworkTransactor.contract.Transfer(opts)\n}", "func (_BtlCoin *BtlCoinSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _BtlCoin.Contract.Transfer(&_BtlCoin.TransactOpts, to, value)\n}", "func (_SafeERC20 *SafeERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeERC20.Contract.contract.Transfer(opts)\n}", "func (_SafeERC20 *SafeERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeERC20.Contract.contract.Transfer(opts)\n}", "func (_SafeERC20 *SafeERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeERC20.Contract.contract.Transfer(opts)\n}", "func (_BasicToken *BasicTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func (_BasicToken *BasicTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func (_BasicToken *BasicTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func (_BasicToken *BasicTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func (_ERC20Interface *ERC20InterfaceSession) Transfer(to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Interface.Contract.Transfer(&_ERC20Interface.TransactOpts, to, tokens)\n}", "func (_CrToken *CrTokenTransactor) Transfer(opts *bind.TransactOpts, dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"transfer\", dst, amount)\n}", "func (_IERC20 *IERC20TransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\r\n\treturn _IERC20.Contract.Transfer(&_IERC20.TransactOpts, to, value)\r\n}", "func (_HasNoEther *HasNoEtherRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _HasNoEther.Contract.HasNoEtherTransactor.contract.Transfer(opts)\n}", "func (_StandardToken *StandardTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.Transfer(&_StandardToken.TransactOpts, _to, _value)\n}", "func (_StandardToken *StandardTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.Transfer(&_StandardToken.TransactOpts, _to, _value)\n}", "func (_BtlCoin *BtlCoinTransactorSession) Transfer(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _BtlCoin.Contract.Transfer(&_BtlCoin.TransactOpts, to, value)\n}", "func (_StandardToken *StandardTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.Transfer(&_StandardToken.TransactOpts, _to, _value)\n}", "func (_StandardToken *StandardTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.Transfer(&_StandardToken.TransactOpts, _to, _value)\n}", "func (_Governable *GovernableTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Governable.Contract.contract.Transfer(opts)\n}", "func (_DevUtils *DevUtilsRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DevUtils.Contract.DevUtilsTransactor.contract.Transfer(opts)\n}", "func (_TokensNetwork *TokensNetworkTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.contract.Transfer(opts)\n}", "func (_BREMToken *BREMTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.Transfer(&_BREMToken.TransactOpts, _to, _value)\n}", "func transferHelper(ctx contractapi.TransactionContextInterface, from string, to string, value int) error {\n\n\tif value < 0 { // transfer of 0 is allowed in ERC-20, so just validate against negative amounts\n\t\treturn fmt.Errorf(\"transfer amount cannot be negative\")\n\t}\n\n\tfromCurrentBalanceBytes, err := ctx.GetStub().GetState(from)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read client account %s from world state: %v\", from, err)\n\t}\n\n\tif fromCurrentBalanceBytes == nil {\n\t\treturn fmt.Errorf(\"client account %s has no balance\", from)\n\t}\n\n\tfromCurrentBalance, _ := strconv.Atoi(string(fromCurrentBalanceBytes)) // Error handling not needed since Itoa() was used when setting the account balance, guaranteeing it was an integer.\n\n\tif fromCurrentBalance < value {\n\t\treturn fmt.Errorf(\"client account %s has insufficient funds\", from)\n\t}\n\n\ttoCurrentBalanceBytes, err := ctx.GetStub().GetState(to)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read recipient account %s from world state: %v\", to, err)\n\t}\n\n\tvar toCurrentBalance int\n\t// If recipient current balance doesn't yet exist, we'll create it with a current balance of 0\n\tif toCurrentBalanceBytes == nil {\n\t\ttoCurrentBalance = 0\n\t} else {\n\t\ttoCurrentBalance, _ = strconv.Atoi(string(toCurrentBalanceBytes)) // Error handling not needed since Itoa() was used when setting the account balance, guaranteeing it was an integer.\n\t}\n\n\tfromUpdatedBalance := fromCurrentBalance - value\n\ttoUpdatedBalance := toCurrentBalance + value\n\n\terr = ctx.GetStub().PutState(from, []byte(strconv.Itoa(fromUpdatedBalance)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ctx.GetStub().PutState(to, []byte(strconv.Itoa(toUpdatedBalance)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"client %s balance updated from %d to %d\", from, fromCurrentBalance, fromUpdatedBalance)\n\tlog.Printf(\"recipient %s balance updated from %d to %d\", to, toCurrentBalance, toUpdatedBalance)\n\n\treturn nil\n}", "func (_VorRandomnessRequestMock *VorRandomnessRequestMockTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _VorRandomnessRequestMock.Contract.contract.Transfer(opts)\n}", "func (_Bindings *BindingsSession) Transfer(dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.Transfer(&_Bindings.TransactOpts, dst, amount)\n}", "func (_ERC20Capped *ERC20CappedTransactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Capped.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_ERC20Interface *ERC20InterfaceTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Interface.Contract.Transfer(&_ERC20Interface.TransactOpts, _to, _value)\n}", "func (_GovernmentContract *GovernmentContractRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _GovernmentContract.Contract.GovernmentContractTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\r\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\r\n}", "func (s *BatchSender) Transfer(req TransferRequest) error {\n\tif req.Memo == \"\" {\n\t\treturn errors.New(\"empty transfer request memo is invalid\")\n\t}\n\n\tif req.Amount == 0 {\n\t\treturn nil\n\t}\n\n\tkey := fmt.Sprintf(\"%s:%s:%s:%d\", req.Memo, req.To, req.Mint, req.Amount)\n\n\tvar status TransferStatus\n\tfound, err := s.store.Get(key, &status)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !found && (s.cfg.VerifyConfirm || s.cfg.RetryError) {\n\t\t// don't create new transactions in verify or retry\n\t\treturn nil\n\t}\n\n\tvar retryError bool\n\tif found {\n\t\tretryError = s.cfg.RetryError && status.ErrLogs != \"\"\n\t}\n\n\tif !found || retryError {\n\t\ttxid, err := s.atp.Transfer(req.Mint, s.wallet, req.To, req.Amount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Println(\"submitted tx:\", key, txid)\n\n\t\tstatus = TransferStatus{\n\t\t\tTXID: txid,\n\t\t\tTransferRequest: req,\n\t\t}\n\n\t\terr = s.store.Set(key, status)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif status.ConnfirmedSlot > 0 && !s.cfg.VerifyConfirm {\n\t\t// already confirmed\n\t\treturn nil\n\t}\n\n\ttxres, err := s.atp.ConfirmTx(s.ctx, status.TXID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"confirm tx: %s\", err)\n\t}\n\n\t// verify mode\n\tif txres.Meta.Err != nil {\n\t\tstatus.ErrLogs = fmt.Sprintf(\"error: %v\", txres.Meta.LogMessages)\n\t}\n\n\tstatus.ConnfirmedSlot = txres.Slot\n\terr = s.store.Set(key, status)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.SafeMathTransactor.contract.Transfer(opts)\n}", "func (_ERC20HecoManager *ERC20HecoManagerRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _ERC20HecoManager.Contract.ERC20HecoManagerTransactor.contract.Transfer(opts)\n}", "func (_DemoERC20 *DemoERC20Session) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _DemoERC20.Contract.Transfer(&_DemoERC20.TransactOpts, _to, _value)\n}", "func (_DemoERC20 *DemoERC20Session) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _DemoERC20.Contract.Transfer(&_DemoERC20.TransactOpts, _to, _value)\n}", "func (_MiniSafe *MiniSafeTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _MiniSafe.Contract.contract.Transfer(opts)\n}", "func (_BtlCoin *BtlCoinTransactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _BtlCoin.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_VorRandomnessRequestMock *VorRandomnessRequestMockRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _VorRandomnessRequestMock.Contract.VorRandomnessRequestMockTransactor.contract.Transfer(opts)\n}", "func (_BasicToken *BasicTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_BasicToken *BasicTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_DetailedERC20 *DetailedERC20Transactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _DetailedERC20.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_DetailedERC20 *DetailedERC20Transactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _DetailedERC20.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_OrderValidationUtils *OrderValidationUtilsRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _OrderValidationUtils.Contract.OrderValidationUtilsTransactor.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\r\n\treturn _SafeMath.Contract.contract.Transfer(opts)\r\n}", "func (_FCToken *FCTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _FCToken.Contract.Transfer(&_FCToken.TransactOpts, _to, _value)\n}", "func (_SafeMath *SafeMathTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.contract.Transfer(opts)\n}", "func (_SafeMath *SafeMathTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SafeMath.Contract.contract.Transfer(opts)\n}" ]
[ "0.59644663", "0.5832566", "0.576338", "0.5730674", "0.54021853", "0.5374337", "0.53338605", "0.53338605", "0.5328754", "0.5288938", "0.5288938", "0.5288416", "0.5273202", "0.5263543", "0.5263543", "0.5263543", "0.52464753", "0.52325016", "0.5202835", "0.5197652", "0.51842266", "0.5183029", "0.5183029", "0.5176497", "0.51747066", "0.51747066", "0.5172752", "0.5149184", "0.51292104", "0.5128873", "0.5125473", "0.5112947", "0.5112076", "0.5111401", "0.51096493", "0.51096493", "0.51073813", "0.51073813", "0.5106502", "0.510536", "0.5103296", "0.5103296", "0.5084834", "0.50841224", "0.5081878", "0.5072495", "0.5072495", "0.5072495", "0.5068902", "0.5068902", "0.5064214", "0.5064214", "0.50601363", "0.50592417", "0.5054832", "0.5051603", "0.5051393", "0.5051393", "0.5050226", "0.50500953", "0.50500953", "0.50476336", "0.5036295", "0.5032478", "0.5019303", "0.501868", "0.50136256", "0.5012168", "0.5010221", "0.5006336", "0.5005312", "0.5002455", "0.5000951", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.50003856", "0.49969274", "0.4994215", "0.4994215", "0.4992381", "0.49914163", "0.4987686", "0.49849126", "0.49849126", "0.4983961", "0.4983961", "0.4982921", "0.49801412", "0.49758282", "0.49736935", "0.49736935", "0.49736935" ]
0.7480716
0
AddRewards computes and transfers a staking reward to active escrow accounts. If an error occurs, the pool and affected accounts are left in an invalid state. This may fail due to the common pool running out of tokens. In this case, the returned error's cause will be `staking.ErrInsufficientBalance`, and it should be safe for the caller to roll back to an earlier state tree and continue from there.
AddRewards вычисляет и переводит стакинговое вознаграждение на активные счета в режиме эскроу. Если произойдет ошибка, пулы и затронутые аккаунты останутся в неверном состоянии. Это может завершиться неудачей из-за исчерпания токенов в общем пуле. В этом случае причина возвращаемой ошибки будет `staking.ErrInsufficientBalance`, и вызывающему коду будет безопасно откатиться к более раннему состоянию дерева и продолжить работу с него.
func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error { steps, err := s.RewardSchedule() if err != nil { return err } var activeStep *staking.RewardStep for _, step := range steps { if time < step.Until { activeStep = &step break } } if activeStep == nil { // We're past the end of the schedule. return nil } commonPool, err := s.CommonPool() if err != nil { return errors.Wrap(err, "loading common pool") } for _, id := range accounts { ent := s.Account(id) q := ent.Escrow.Active.Balance.Clone() // Multiply first. if err := q.Mul(factor); err != nil { return errors.Wrap(err, "multiplying by reward factor") } if err := q.Mul(&activeStep.Scale); err != nil { return errors.Wrap(err, "multiplying by reward step scale") } if err := q.Quo(staking.RewardAmountDenominator); err != nil { return errors.Wrap(err, "dividing by reward amount denominator") } if q.IsZero() { continue } var com *quantity.Quantity rate := ent.Escrow.CommissionSchedule.CurrentRate(time) if rate != nil { com = q.Clone() // Multiply first. if err := com.Mul(rate); err != nil { return errors.Wrap(err, "multiplying by commission rate") } if err := com.Quo(staking.CommissionRateDenominator); err != nil { return errors.Wrap(err, "dividing by commission rate denominator") } if err := q.Sub(com); err != nil { return errors.Wrap(err, "subtracting commission") } } if !q.IsZero() { if err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil { return errors.Wrap(err, "transferring to active escrow balance from common pool") } } if com != nil && !com.IsZero() { delegation := s.Delegation(id, id) if err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil { return errors.Wrap(err, "depositing commission") } s.SetDelegation(id, id, delegation) } s.SetAccount(id, ent) } s.SetCommonPool(commonPool) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func (_RandomBeacon *RandomBeaconTransactor) WithdrawRewards(opts *bind.TransactOpts, stakingProvider common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"withdrawRewards\", stakingProvider)\n}", "func (path *Path) AddRewards(rewards map[*Reward]int) {\n\tfor key, value := range rewards {\n\t\tpath.rewards[key] += value\n\t}\n}", "func (_RandomBeacon *RandomBeaconTransactorSession) WithdrawRewards(stakingProvider common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.WithdrawRewards(&_RandomBeacon.TransactOpts, stakingProvider)\n}", "func (_XStaking *XStakingSession) Rewards(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Rewards(&_XStaking.CallOpts, arg0)\n}", "func (_XStaking *XStakingCallerSession) Rewards(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Rewards(&_XStaking.CallOpts, arg0)\n}", "func (_RandomBeacon *RandomBeaconSession) WithdrawRewards(stakingProvider common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.WithdrawRewards(&_RandomBeacon.TransactOpts, stakingProvider)\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Token *TokenTransactor) SetupRewards(opts *bind.TransactOpts, multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"setupRewards\", multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (c *gRPCClient) AccountRewards(address gosmtypes.Address, offset uint32, maxResults uint32) ([]*apitypes.Reward, uint32, error) {\n\tgsc := c.getGlobalStateServiceClient()\n\tresp, err := gsc.AccountDataQuery(context.Background(), &apitypes.AccountDataQueryRequest{\n\t\tFilter: &apitypes.AccountDataFilter{\n\t\t\tAccountId: &apitypes.AccountId{Address: address.Bytes()},\n\t\t\tAccountDataFlags: uint32(apitypes.AccountDataFlag_ACCOUNT_DATA_FLAG_REWARD),\n\t\t},\n\n\t\tMaxResults: maxResults,\n\t\tOffset: offset,\n\t})\n\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\trewards := make([]*apitypes.Reward, 0)\n\n\tfor _, data := range resp.AccountItem {\n\t\tr := data.GetReward()\n\t\tif r != nil {\n\t\t\trewards = append(rewards, r)\n\t\t}\n\t}\n\n\treturn rewards, resp.TotalResults, nil\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (_Token *TokenTransactorSession) SetupRewards(multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.SetupRewards(&_Token.TransactOpts, multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (_Token *TokenSession) SetupRewards(multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.SetupRewards(&_Token.TransactOpts, multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (_XStaking *XStakingTransactor) SetRewardsDuration(opts *bind.TransactOpts, _rewardsDuration *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"setRewardsDuration\", _rewardsDuration)\n}", "func NewIStakingRewardsTransactor(address common.Address, transactor bind.ContractTransactor) (*IStakingRewardsTransactor, error) {\n\tcontract, err := bindIStakingRewards(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IStakingRewardsTransactor{contract: contract}, nil\n}", "func (_XStaking *XStakingTransactorSession) SetRewardsDuration(_rewardsDuration *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDuration(&_XStaking.TransactOpts, _rewardsDuration)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (_XStaking *XStakingSession) SetRewardsDuration(_rewardsDuration *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDuration(&_XStaking.TransactOpts, _rewardsDuration)\n}", "func NewIStakingRewards(address common.Address, backend bind.ContractBackend) (*IStakingRewards, error) {\n\tcontract, err := bindIStakingRewards(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IStakingRewards{IStakingRewardsCaller: IStakingRewardsCaller{contract: contract}, IStakingRewardsTransactor: IStakingRewardsTransactor{contract: contract}, IStakingRewardsFilterer: IStakingRewardsFilterer{contract: contract}}, nil\n}", "func (_Lmc *LmcSession) UserAccruedRewards(arg0 common.Address) (*big.Int, error) {\n\treturn _Lmc.Contract.UserAccruedRewards(&_Lmc.CallOpts, arg0)\n}", "func TxWithdrawRewards(f *cli.Fixtures, valAddr sdk.ValAddress, from string, flags ...string) bool {\n\tcmd := fmt.Sprintf(\"%s tx distribution withdraw-rewards %s %v --keyring-backend=test --from=%s\", f.SimcliBinary, valAddr, f.Flags(), from)\n\treturn cli.ExecuteWrite(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass)\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (c *gRPCClient) SmesherRewards(smesherId []byte, offset uint32, maxResults uint32) ([]*apitypes.Reward, uint32, error) {\n\tgsc := c.getGlobalStateServiceClient()\n\tresp, err := gsc.SmesherDataQuery(context.Background(), &apitypes.SmesherDataQueryRequest{\n\t\tSmesherId: &apitypes.SmesherId{Id: smesherId},\n\t\tMaxResults: maxResults,\n\t\tOffset: offset,\n\t})\n\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn resp.Rewards, resp.TotalResults, nil\n}", "func (_Lmc *LmcCallerSession) UserAccruedRewards(arg0 common.Address) (*big.Int, error) {\n\treturn _Lmc.Contract.UserAccruedRewards(&_Lmc.CallOpts, arg0)\n}", "func (k Keeper) WithdrawDelegationRewards(ctx sdk.Context, delAddr chainTypes.AccountID, valAddr chainTypes.AccountID) (Coins, error) {\n\n\tval := k.stakingKeeper.Validator(ctx, valAddr)\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"val:\", val)\n\tif val == nil {\n\t\treturn nil, types.ErrNoValidatorDistInfo\n\t}\n\n\tdel := k.stakingKeeper.Delegation(ctx, delAddr, valAddr)\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"del:\", del)\n\tif del == nil {\n\t\treturn nil, types.ErrEmptyDelegationDistInfo\n\t}\n\n\t// withdraw rewards\n\trewards, err := k.withdrawDelegationRewards(ctx, val, del)\n\tif err != nil {\n\t\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"err:\", err)\n\t\treturn nil, err\n\t}\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"rewards:\", rewards)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeWithdrawRewards,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, rewards.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t),\n\t)\n\n\t// reinitialize the delegation\n\tk.initializeDelegation(ctx, valAddr, delAddr)\n\treturn rewards, nil\n}", "func EstimatedRewards(request []string) (float64, error) {\n\tcoinId, err := strconv.ParseUint(request[0], 10, 64)\n\tif err != nil {\n\t\treturn 0.00, errors.New(\"Invalid coinid format\")\n\t}\n\n\twtmClient := NewWhatToMineClient(nil, BASE, userAgent)\n\twtmClient.SetDebug(debug)\n\tstatus, err := wtmClient.GetCoin(coinId, 1000000, 0, 0)\n\tif err != nil {\n\t\treturn 0.00, err\n\t}\n\treturn status.EstimatedRewards, nil\n}", "func (_IStakingRewards *IStakingRewardsTransactor) Withdraw(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"withdraw\", amount)\n}", "func (_RandomBeacon *RandomBeaconCallerSession) AvailableRewards(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.AvailableRewards(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Withdraw(&_IStakingRewards.TransactOpts, amount)\n}", "func (_RandomBeacon *RandomBeaconSession) AvailableRewards(stakingProvider common.Address) (*big.Int, error) {\n\treturn _RandomBeacon.Contract.AvailableRewards(&_RandomBeacon.CallOpts, stakingProvider)\n}", "func (_RandomBeacon *RandomBeaconCaller) AvailableRewards(opts *bind.CallOpts, stakingProvider common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _RandomBeacon.contract.Call(opts, &out, \"availableRewards\", stakingProvider)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func addCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\toldCoins := getCoins(ctx, am, addr)\n\tnewCoins := oldCoins.Plus(amt)\n\tif !newCoins.IsNotNegative() {\n\t\treturn amt, sdk.ErrInsufficientCoins(fmt.Sprintf(\"%s < %s\", oldCoins, amt))\n\t}\n\terr := setCoins(ctx, am, addr, newCoins)\n\treturn newCoins, err\n}", "func (_XStaking *XStakingSession) RewardsDuration() (*big.Int, error) {\n\treturn _XStaking.Contract.RewardsDuration(&_XStaking.CallOpts)\n}", "func (_XStaking *XStakingCallerSession) RewardsDuration() (*big.Int, error) {\n\treturn _XStaking.Contract.RewardsDuration(&_XStaking.CallOpts)\n}", "func (_Lmc *LmcCaller) UserAccruedRewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"userAccruedRewards\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) ([]wasmvmtypes.Coin, error) {\n\t// Try to get *delegator* reward info!\n\tparams := distributiontypes.QueryDelegationRewardsRequest{\n\t\tDelegatorAddress: delegation.DelegatorAddress,\n\t\tValidatorAddress: delegation.ValidatorAddress,\n\t}\n\tcache, _ := ctx.CacheContext()\n\tqres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), &params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// now we have it, convert it into wasmvm types\n\trewards := make([]wasmvmtypes.Coin, len(qres.Rewards))\n\tfor i, r := range qres.Rewards {\n\t\trewards[i] = wasmvmtypes.Coin{\n\t\t\tDenom: r.Denom,\n\t\t\tAmount: r.Amount.TruncateInt().String(),\n\t\t}\n\t}\n\treturn rewards, nil\n}", "func (_RandomBeacon *RandomBeaconSession) WithdrawIneligibleRewards(recipient common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.WithdrawIneligibleRewards(&_RandomBeacon.TransactOpts, recipient)\n}", "func (_IStakingRewards *IStakingRewardsSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Withdraw(&_IStakingRewards.TransactOpts, amount)\n}", "func (c *DPOS) CheckRewards(ctx contract.StaticContext, req *CheckRewardsRequest) (*CheckRewardsResponse, error) {\n\tctx.Logger().Debug(\"DPOSv3 CheckRewards\", \"request\", req)\n\n\tstate, err := LoadState(ctx)\n\tif err != nil {\n\t\treturn nil, logStaticDposError(ctx, err, req.String())\n\t}\n\n\treturn &CheckRewardsResponse{TotalRewardDistribution: state.TotalRewardDistribution}, nil\n}", "func (_RandomBeacon *RandomBeaconTransactor) WithdrawIneligibleRewards(opts *bind.TransactOpts, recipient common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"withdrawIneligibleRewards\", recipient)\n}", "func (_Token *TokenTransactor) ToggleRewards(opts *bind.TransactOpts, enabled bool) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"toggleRewards\", enabled)\n}", "func (s SmesherService) EstimatedRewards(context.Context, *pb.EstimatedRewardsRequest) (*pb.EstimatedRewardsResponse, error) {\n\tlog.Info(\"GRPC SmesherService.EstimatedRewards\")\n\treturn nil, status.Errorf(codes.Unimplemented, \"this endpoint is not implemented\")\n}", "func (_RandomBeacon *RandomBeaconTransactorSession) WithdrawIneligibleRewards(recipient common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.WithdrawIneligibleRewards(&_RandomBeacon.TransactOpts, recipient)\n}", "func (a *StoragePowerActorCode_I) AddBalance(rt Runtime, minerAddr addr.Address) {\n\tRT_MinerEntry_ValidateCaller_DetermineFundsLocation(rt, minerAddr, vmr.MinerEntrySpec_MinerOnly)\n\n\tmsgValue := rt.ValueReceived()\n\n\th, st := a.State(rt)\n\tnewTable, ok := autil.BalanceTable_WithAdd(st.EscrowTable(), minerAddr, msgValue)\n\tif !ok {\n\t\trt.AbortStateMsg(\"Escrow operation failed\")\n\t}\n\tst.Impl().EscrowTable_ = newTable\n\tUpdateRelease(rt, h, st)\n}", "func (m *mover) EarnCoins(tx *TX, limits, coins map[string]int) error {\n\tbank, err := tx.GetCoins()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpurse, err := tx.GetPlayerCoins(m.userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor color, limit := range limits {\n\t\tif bank[color] < limit {\n\t\t\treturn ErrInsufficientCoins\n\t\t}\n\t}\n\n\tnewbank := map[string]int{}\n\tnewpurse := map[string]int{}\n\n\tfor color, count := range coins {\n\t\tnewbank[color] = bank[color] - count\n\t\tnewpurse[color] = purse[color] + count\n\t}\n\n\tif err := tx.UpdateCoins(newbank); err != nil {\n\t\treturn err\n\t}\n\tif err := tx.UpdatePlayerCoins(m.userID, newpurse); err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: If player has more than 10 coins now, make then give some back.\n\n\treturn nil\n}", "func (_Token *TokenTransactorSession) ToggleRewards(enabled bool) (*types.Transaction, error) {\n\treturn _Token.Contract.ToggleRewards(&_Token.TransactOpts, enabled)\n}", "func (c *DPOS) ClaimRewardsFromAllValidators(ctx contract.Context, req *ClaimDelegatorRewardsRequest) (*ClaimDelegatorRewardsResponse, error) {\n\tif ctx.FeatureEnabled(features.DPOSVersion3_6, false) {\n\t\treturn c.claimRewardsFromAllValidators2(ctx, req)\n\t}\n\n\tdelegator := ctx.Message().Sender\n\tvalidators, err := ValidatorList(ctx)\n\tif err != nil {\n\t\treturn nil, logStaticDposError(ctx, err, req.String())\n\t}\n\n\ttotal := big.NewInt(0)\n\tchainID := ctx.Block().ChainID\n\tvar claimedFromValidators []*types.Address\n\tvar amounts []*types.BigUInt\n\tfor _, v := range validators {\n\t\tvalAddress := loom.Address{ChainID: chainID, Local: loom.LocalAddressFromPublicKey(v.PubKey)}\n\t\tdelegation, err := GetDelegation(ctx, REWARD_DELEGATION_INDEX, *valAddress.MarshalPB(), *delegator.MarshalPB())\n\t\tif err == contract.ErrNotFound {\n\t\t\t// Skip reward delegations that were not found.\n\t\t\tctx.Logger().Error(\"DPOS ClaimRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\tclaimedFromValidators = append(claimedFromValidators, valAddress.MarshalPB())\n\t\tamounts = append(amounts, delegation.Amount)\n\n\t\t// Set to UNBONDING and UpdateAmount == Amount, to fully unbond it.\n\t\tdelegation.State = UNBONDING\n\t\tdelegation.UpdateAmount = delegation.Amount\n\n\t\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update delegation\")\n\t\t}\n\n\t\terr = c.emitDelegatorUnbondsEvent(ctx, delegation)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add to the sum\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := &types.BigUInt{Value: *loom.NewBigUInt(total)}\n\n\terr = c.emitDelegatorClaimsRewardsEvent(ctx, delegator.MarshalPB(), claimedFromValidators, amounts, amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClaimDelegatorRewardsResponse{\n\t\tAmount: amount,\n\t}, nil\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func NewIStakingRewardsCaller(address common.Address, caller bind.ContractCaller) (*IStakingRewardsCaller, error) {\n\tcontract, err := bindIStakingRewards(address, caller, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IStakingRewardsCaller{contract: contract}, nil\n}", "func (_XStaking *XStakingTransactor) SetRewardsDistribution(opts *bind.TransactOpts, _rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"setRewardsDistribution\", _rewardsDistribution)\n}", "func (_XStaking *XStakingSession) RewardsToken() (common.Address, error) {\n\treturn _XStaking.Contract.RewardsToken(&_XStaking.CallOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_CrToken *CrTokenTransactor) AddReserves(opts *bind.TransactOpts, addAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"_addReserves\", addAmount)\n}", "func (_CrToken *CrTokenTransactorSession) AddReserves(addAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.AddReserves(&_CrToken.TransactOpts, addAmount)\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (_XStaking *XStakingCallerSession) RewardsToken() (common.Address, error) {\n\treturn _XStaking.Contract.RewardsToken(&_XStaking.CallOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (m *MemoryRewardStorage) Add(reward rewards.Reward) int {\n\treward.ID = len(m.rewards) + 1\n\tm.rewards = append(m.rewards, reward)\n\n\treturn reward.ID\n}", "func (_Token *TokenSession) ToggleRewards(enabled bool) (*types.Transaction, error) {\n\treturn _Token.Contract.ToggleRewards(&_Token.TransactOpts, enabled)\n}", "func bindIStakingRewards(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(IStakingRewardsABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func (k Keeper) GetTotalRewards(ctx sdk.Context) (totalRewards chainTypes.DecCoins) {\n\tk.IterateValidatorOutstandingRewards(ctx,\n\t\tfunc(_ AccountID, rewards types.ValidatorOutstandingRewards) (stop bool) {\n\t\t\ttotalRewards = totalRewards.Add(rewards.Rewards...)\n\t\t\treturn false\n\t\t},\n\t)\n\n\treturn totalRewards\n}", "func (_XStaking *XStakingTransactorSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDistribution(&_XStaking.TransactOpts, _rewardsDistribution)\n}", "func (_Smartchef *SmartchefTransactor) EmergencyRewardWithdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"emergencyRewardWithdraw\", _amount)\n}", "func TxWithdrawAllRewards(f *cli.Fixtures, from string, flags ...string) (bool, string, string) {\n\tcmd := fmt.Sprintf(\"%s tx distribution withdraw-all-rewards %v --keyring-backend=test --from=%s\", f.SimcliBinary, f.Flags(), from)\n\treturn cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass)\n}", "func (_XStaking *XStakingCaller) RewardsToken(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardsToken\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_Token *TokenCaller) RewardsAddress(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Token.contract.Call(opts, out, \"rewardsAddress\")\n\treturn *ret0, err\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (_XStaking *XStakingSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDistribution(&_XStaking.TransactOpts, _rewardsDistribution)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (c RewardsController) GetRewards(page int) revel.Result {\n\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\t//ChangeRewardsModel() // Remove when finish production\n\n\tvar reward models.Reward\n\tif Reward, ok := app.Mapper.GetModel(&reward); ok {\n\t\tvar rewards = []models.Reward{}\n\t\tvar match = bson.M{\"$and\": []bson.M{\n\t\t\tbson.M{\"$or\": []bson.M{\n\t\t\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\t\t\tbson.M{\"users\": bson.M{\"$elemMatch\": bson.M{\"$eq\": c.CurrentUser.GetID().Hex()}}},\n\t\t\t}},\n\t\t\tbson.M{\"is_visible\": true},\n\t\t\tbson.M{\"resource_type\": bson.M{\"$ne\": core.ModelTypeChallenge}},\n\t\t}}\n\t\tif page <= 1 {\n\t\t\tpage = 1\n\t\t}\n\t\tvar pipe = mgomap.Aggregate{}.Match(match).Sort(bson.M{\"updated_at\": -1}).Skip((page - 1) * core.LimitRewards).Limit(core.LimitRewards)\n\n\t\tif err := Reward.Pipe(pipe, &rewards); err != nil {\n\t\t\treturn c.ErrorResponse(c.Message(\"error.notFound\", \"Rewards\"), \"No rewards Found\", 400)\n\t\t}\n\t\treturn c.SuccessResponse(rewards, \"success\", core.ModelsType[core.ModelReward], serializers.RewardSerializer{Lang: c.Request.Locale})\n\n\t}\n\treturn c.ServerErrorResponse()\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func (_Cakevault *CakevaultSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (keeper Keeper) AddCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn addCoins(ctx, keeper.am, addr, amt)\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (_CrToken *CrTokenSession) AddReserves(addAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.AddReserves(&_CrToken.TransactOpts, addAmount)\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (sc stakingClient) AddShares(fromInfo keys.Info, passWd string, valAddrsStr []string, memo string, accNum, seqNum uint64) (\n\tresp sdk.TxResponse, err error) {\n\tif err = params.CheckAddSharesParams(fromInfo, passWd, valAddrsStr); err != nil {\n\t\treturn\n\t}\n\n\tvalAddrs, err := utils.ParseValAddresses(valAddrsStr)\n\tif err != nil {\n\t\treturn resp, fmt.Errorf(\"failed. validator address parsed error: %s\", err.Error())\n\t}\n\n\tmsg := types.NewMsgAddShares(fromInfo.GetAddress(), valAddrs)\n\n\treturn sc.BuildAndBroadcast(fromInfo.GetName(), passWd, memo, []sdk.Msg{msg}, accNum, seqNum)\n\n}", "func (_Cakevault *CakevaultCallerSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (_Smartchef *SmartchefSession) EmergencyRewardWithdraw(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.Contract.EmergencyRewardWithdraw(&_Smartchef.TransactOpts, _amount)\n}", "func (_IStakingRewards *IStakingRewardsSession) Earned(account common.Address) (*big.Int, error) {\n\treturn _IStakingRewards.Contract.Earned(&_IStakingRewards.CallOpts, account)\n}", "func (um *UserManager) AddCredits(username string, credits float64) (*User, error) {\n\tu, err := um.FindByUserName(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// update new credit balance in memory\n\tu.Credits = u.Credits + credits\n\t// save updated credit balance to database\n\tif check := um.DB.Model(u).Update(\"credits\", u.Credits); check.Error != nil {\n\t\treturn nil, check.Error\n\t}\n\treturn u, nil\n}", "func NewIStakingRewardsFilterer(address common.Address, filterer bind.ContractFilterer) (*IStakingRewardsFilterer, error) {\n\tcontract, err := bindIStakingRewards(address, nil, nil, filterer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IStakingRewardsFilterer{contract: contract}, nil\n}", "func (ck CoinKeeper) AddCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\tacc := ck.am.GetAccount(ctx, addr)\n\tif acc == nil {\n\t\tacc = ck.am.NewAccountWithAddress(ctx, addr)\n\t}\n\n\tcoins := acc.GetCoins()\n\tnewCoins := coins.Plus(amt)\n\n\tacc.SetCoins(newCoins)\n\tck.am.SetAccount(ctx, acc)\n\treturn newCoins, nil\n}", "func (_XStaking *XStakingFilterer) FilterRewardAdded(opts *bind.FilterOpts) (*XStakingRewardAddedIterator, error) {\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardAdded\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardAddedIterator{contract: _XStaking.contract, event: \"RewardAdded\", logs: logs, sub: sub}, nil\n}", "func (_Smartchef *SmartchefTransactorSession) EmergencyRewardWithdraw(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.Contract.EmergencyRewardWithdraw(&_Smartchef.TransactOpts, _amount)\n}", "func (_XStaking *XStakingCaller) RewardsDuration(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardsDuration\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Cakevault *CakevaultSession) CalculateHarvestCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateHarvestCakeRewards(&_Cakevault.CallOpts)\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (_Token *TokenSession) RewardsAddress() (common.Address, error) {\n\treturn _Token.Contract.RewardsAddress(&_Token.CallOpts)\n}", "func (_IStakingRewards *IStakingRewardsCallerSession) Earned(account common.Address) (*big.Int, error) {\n\treturn _IStakingRewards.Contract.Earned(&_IStakingRewards.CallOpts, account)\n}", "func (_Token *TokenTransactorSession) AddToMinters(account common.Address) (*types.Transaction, error) {\n\treturn _Token.Contract.AddToMinters(&_Token.TransactOpts, account)\n}", "func NewRewardTx(coinbase common.Address, reward *big.Int, timestamp uint64) (*types.Transaction, error) {\n\tif err := validateReward(reward); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxData := types.TransactionData{\n\t\tType: types.TxTypeReward,\n\t\tFrom: common.EmptyAddress,\n\t\tTo: coinbase,\n\t\tAmount: new(big.Int).Set(reward),\n\t\tGasPrice: common.Big0,\n\t\tTimestamp: timestamp,\n\t\tPayload: emptyPayload,\n\t}\n\n\ttx := types.Transaction{\n\t\tHash: crypto.MustHash(txData),\n\t\tData: txData,\n\t\tSignature: emptySig,\n\t}\n\n\treturn &tx, nil\n}", "func (_Lmc *LmcSession) UpdateRewardMultipliers() (*types.Transaction, error) {\n\treturn _Lmc.Contract.UpdateRewardMultipliers(&_Lmc.TransactOpts)\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}" ]
[ "0.6756725", "0.64123845", "0.6352972", "0.6323859", "0.6277504", "0.6244347", "0.6214062", "0.6086639", "0.598928", "0.59732753", "0.5944851", "0.5910994", "0.58423203", "0.5786412", "0.5620724", "0.5618472", "0.5605595", "0.55774486", "0.5538607", "0.54995674", "0.54924965", "0.5480119", "0.54675364", "0.54530984", "0.5406622", "0.5335373", "0.5303138", "0.52937216", "0.52874947", "0.5283984", "0.52717394", "0.52600104", "0.5248048", "0.5222691", "0.51994324", "0.51977307", "0.51798934", "0.51771486", "0.51731056", "0.5163445", "0.5158901", "0.51465446", "0.51339334", "0.5132652", "0.5123137", "0.51167077", "0.51025355", "0.5060288", "0.5057281", "0.50565165", "0.50510985", "0.5045511", "0.50216305", "0.5004207", "0.5003878", "0.5001088", "0.50010246", "0.49987778", "0.49932265", "0.49928498", "0.49850968", "0.4979262", "0.4964295", "0.4930202", "0.49251068", "0.49246782", "0.49231216", "0.490125", "0.48942912", "0.48854813", "0.48801422", "0.48774415", "0.4864517", "0.4863598", "0.48493218", "0.4846312", "0.48401892", "0.48166043", "0.47898522", "0.4766147", "0.47644636", "0.47583306", "0.47575095", "0.47532538", "0.4751578", "0.47481316", "0.47406146", "0.47227", "0.4710224", "0.47088817", "0.46877208", "0.46823043", "0.46740562", "0.46724907", "0.46689817", "0.46540692", "0.46521086", "0.464042", "0.4637007", "0.46320108" ]
0.76440066
0
AddRewardSingleAttenuated computes, scales, and transfers a staking reward to an active escrow account.
AddRewardSingleAttenuated вычисляет, масштабирует и переносит стакинг-приз в активный счет-гарантия.
func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error { steps, err := s.RewardSchedule() if err != nil { return err } var activeStep *staking.RewardStep for _, step := range steps { if time < step.Until { activeStep = &step break } } if activeStep == nil { // We're past the end of the schedule. return nil } var numQ, denQ quantity.Quantity if err = numQ.FromInt64(int64(attenuationNumerator)); err != nil { return errors.Wrapf(err, "importing attenuation numerator %d", attenuationNumerator) } if err = denQ.FromInt64(int64(attenuationDenominator)); err != nil { return errors.Wrapf(err, "importing attenuation denominator %d", attenuationDenominator) } commonPool, err := s.CommonPool() if err != nil { return errors.Wrap(err, "loading common pool") } ent := s.Account(account) q := ent.Escrow.Active.Balance.Clone() // Multiply first. if err := q.Mul(factor); err != nil { return errors.Wrap(err, "multiplying by reward factor") } if err := q.Mul(&activeStep.Scale); err != nil { return errors.Wrap(err, "multiplying by reward step scale") } if err := q.Mul(&numQ); err != nil { return errors.Wrap(err, "multiplying by attenuation numerator") } if err := q.Quo(staking.RewardAmountDenominator); err != nil { return errors.Wrap(err, "dividing by reward amount denominator") } if err := q.Quo(&denQ); err != nil { return errors.Wrap(err, "dividing by attenuation denominator") } if q.IsZero() { return nil } var com *quantity.Quantity rate := ent.Escrow.CommissionSchedule.CurrentRate(time) if rate != nil { com = q.Clone() // Multiply first. if err := com.Mul(rate); err != nil { return errors.Wrap(err, "multiplying by commission rate") } if err := com.Quo(staking.CommissionRateDenominator); err != nil { return errors.Wrap(err, "dividing by commission rate denominator") } if err := q.Sub(com); err != nil { return errors.Wrap(err, "subtracting commission") } } if !q.IsZero() { if err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil { return errors.Wrap(err, "transferring to active escrow balance from common pool") } } if com != nil && !com.IsZero() { delegation := s.Delegation(account, account) if err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil { return errors.Wrap(err, "depositing commission") } s.SetDelegation(account, account, delegation) } s.SetAccount(account, ent) s.SetCommonPool(commonPool) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func (_XStaking *XStakingFilterer) FilterRewardAdded(opts *bind.FilterOpts) (*XStakingRewardAddedIterator, error) {\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardAdded\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardAddedIterator{contract: _XStaking.contract, event: \"RewardAdded\", logs: logs, sub: sub}, nil\n}", "func (_XStaking *XStakingFilterer) WatchRewardAdded(opts *bind.WatchOpts, sink chan<- *XStakingRewardAdded) (event.Subscription, error) {\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardAdded\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(XStakingRewardAdded)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardAdded\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_Lmc *LmcSession) GetUserAccumulatedReward(_userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserAccumulatedReward(&_Lmc.CallOpts, _userAddress, tokenIndex)\n}", "func (_Lmc *LmcCallerSession) GetUserAccumulatedReward(_userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserAccumulatedReward(&_Lmc.CallOpts, _userAddress, tokenIndex)\n}", "func NewRewardTx(coinbase common.Address, reward *big.Int, timestamp uint64) (*types.Transaction, error) {\n\tif err := validateReward(reward); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxData := types.TransactionData{\n\t\tType: types.TxTypeReward,\n\t\tFrom: common.EmptyAddress,\n\t\tTo: coinbase,\n\t\tAmount: new(big.Int).Set(reward),\n\t\tGasPrice: common.Big0,\n\t\tTimestamp: timestamp,\n\t\tPayload: emptyPayload,\n\t}\n\n\ttx := types.Transaction{\n\t\tHash: crypto.MustHash(txData),\n\t\tData: txData,\n\t\tSignature: emptySig,\n\t}\n\n\treturn &tx, nil\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func (_Lmc *LmcCaller) GetUserAccumulatedReward(opts *bind.CallOpts, _userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"getUserAccumulatedReward\", _userAddress, tokenIndex)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error {\n\treturn action.ProcessReward(ctx, reward, va)\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func (del Delegation) ClaimedReward() (hexutil.Big, error) {\n\tval, err := repository.R().RewardsClaimed(&del.Address, (*big.Int)(del.Delegation.ToStakerId), nil, nil)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn (hexutil.Big)(*val), nil\n}", "func MeanReward(r []*Rollout) float64 {\n\tvar sum float64\n\tfor _, x := range r {\n\t\tsum += x.Reward\n\t}\n\treturn sum / float64(len(r))\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_XStaking *XStakingSession) UserRewardPerTokenPaid(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.UserRewardPerTokenPaid(&_XStaking.CallOpts, arg0)\n}", "func (_XStaking *XStakingCallerSession) UserRewardPerTokenPaid(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.UserRewardPerTokenPaid(&_XStaking.CallOpts, arg0)\n}", "func (_IStakingRewards *IStakingRewardsSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_XStaking *XStakingTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func (_XStaking *XStakingFilterer) ParseRewardAdded(log types.Log) (*XStakingRewardAdded, error) {\n\tevent := new(XStakingRewardAdded)\n\tif err := _XStaking.contract.UnpackLog(event, \"RewardAdded\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (_XStaking *XStakingSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func MiningRewardBalance(block consensus.Block, account []byte) *RTU {\n//\tif bytes, err := block.Lookup([]byte(bytesToHexString(account))); err == nil {\n\tif bytes, err := block.Lookup(account); err == nil {\n\t\treturn BytesToRtu(bytes)\n\t}\n\treturn BytesToRtu(nil)\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}", "func (_XStaking *XStakingFilterer) WatchRewardPaid(opts *bind.WatchOpts, sink chan<- *XStakingRewardPaid, user []common.Address) (event.Subscription, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(XStakingRewardPaid)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardPaid\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func (_XStaking *XStakingTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"getReward\")\n}", "func (_XStaking *XStakingFilterer) FilterRewardPaid(opts *bind.FilterOpts, user []common.Address) (*XStakingRewardPaidIterator, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardPaidIterator{contract: _XStaking.contract, event: \"RewardPaid\", logs: logs, sub: sub}, nil\n}", "func (m *MemoryRewardStorage) Add(reward rewards.Reward) int {\n\treward.ID = len(m.rewards) + 1\n\tm.rewards = append(m.rewards, reward)\n\n\treturn reward.ID\n}", "func (_XStaking *XStakingSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_XStaking *XStakingTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (_SingleAuto *SingleAutoTransactorSession) Add(_allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.Contract.Add(&_SingleAuto.TransactOpts, _allocPoint, _want, _withUpdate, _strat)\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func (_Token *TokenSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (a *StoragePowerActorCode_I) AddBalance(rt Runtime, minerAddr addr.Address) {\n\tRT_MinerEntry_ValidateCaller_DetermineFundsLocation(rt, minerAddr, vmr.MinerEntrySpec_MinerOnly)\n\n\tmsgValue := rt.ValueReceived()\n\n\th, st := a.State(rt)\n\tnewTable, ok := autil.BalanceTable_WithAdd(st.EscrowTable(), minerAddr, msgValue)\n\tif !ok {\n\t\trt.AbortStateMsg(\"Escrow operation failed\")\n\t}\n\tst.Impl().EscrowTable_ = newTable\n\tUpdateRelease(rt, h, st)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (_Lmc *LmcCallerSession) AccumulatedRewardMultiplier(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.AccumulatedRewardMultiplier(&_Lmc.CallOpts, arg0)\n}", "func (_Token *TokenCaller) CurrentReward(opts *bind.CallOpts, account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\tret := new(struct {\n\t\tInitialDeposit *big.Int\n\t\tReward *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"currentReward\", account)\n\treturn *ret, err\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (_Token *TokenCallerSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (transaction *AccountCreateTransaction) SetDeclineStakingReward(decline bool) *AccountCreateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.declineReward = decline\n\treturn transaction\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func NewUpdateRewardOK() *UpdateRewardOK {\n\treturn &UpdateRewardOK{}\n}", "func (_XStaking *XStakingTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (_SingleAuto *SingleAutoSession) Add(_allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.Contract.Add(&_SingleAuto.TransactOpts, _allocPoint, _want, _withUpdate, _strat)\n}", "func (_Lmc *LmcSession) AccumulatedRewardMultiplier(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.AccumulatedRewardMultiplier(&_Lmc.CallOpts, arg0)\n}", "func (n Network) ChainReward(ctx context.Context, launchID uint64) (rewardtypes.RewardPool, error) {\n\tres, err := n.rewardQuery.\n\t\tRewardPool(ctx,\n\t\t\t&rewardtypes.QueryGetRewardPoolRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\n\tif cosmoserror.Unwrap(err) == cosmoserror.ErrNotFound {\n\t\treturn rewardtypes.RewardPool{}, ErrObjectNotFound\n\t} else if err != nil {\n\t\treturn rewardtypes.RewardPool{}, err\n\t}\n\treturn res.RewardPool, nil\n}", "func (ma *FakeActor) AttemptMultiSpend1(ctx exec.VMContext, self, target address.Address) (uint8, error) {\n\t// This will transfer 100 tokens legitimately.\n\t_, code, err := ctx.Send(target, \"callSendTokens\", types.ZeroAttoFIL, []interface{}{self, target})\n\tif code != 0 || err != nil {\n\t\treturn code, errors.FaultErrorWrap(err, \"failed first callSendTokens\")\n\t}\n\t// Try to double spend\n\t_, code, err = ctx.Send(target, \"callSendTokens\", types.ZeroAttoFIL, []interface{}{self, target})\n\tif code != 0 || err != nil {\n\t\treturn code, errors.FaultErrorWrap(err, \"failed second callSendTokens\")\n\t}\n\treturn code, err\n}", "func (_XStaking *XStakingCaller) UserRewardPerTokenPaid(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"userRewardPerTokenPaid\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func (c4 *Connect4) GetReward() int {\n\tif c4.Winner == nil {\n\t\treturn 0\n\t} else if *c4.Winner == 1 {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (_SingleAuto *SingleAutoTransactor) Add(opts *bind.TransactOpts, _allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.contract.Transact(opts, \"add\", _allocPoint, _want, _withUpdate, _strat)\n}", "func (_Lmc *LmcCaller) AccumulatedRewardMultiplier(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"accumulatedRewardMultiplier\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Smartchef *SmartchefTransactor) EmergencyRewardWithdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"emergencyRewardWithdraw\", _amount)\n}", "func (k Keeper) ClaimSavingsReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeSavingsClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetSavingsClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSavingsClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func NewSingleAutoTransactor(address common.Address, transactor bind.ContractTransactor) (*SingleAutoTransactor, error) {\n\tcontract, err := bindSingleAuto(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SingleAutoTransactor{contract: contract}, nil\n}", "func (_Lmc *LmcSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (_Smartchef *SmartchefSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_Lmc *LmcCallerSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (_Redeemable *RedeemableTransactor) AddMinter(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Redeemable.contract.Transact(opts, \"addMinter\", account)\n}", "func (_Smartchef *SmartchefCallerSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (k Keeper) DeleteReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tstore.Delete(types.GetRewardByFarmerAndStakingCoinDenomIndexKey(farmerAcc, stakingCoinDenom))\n}", "func (path *Path) AddRewards(rewards map[*Reward]int) {\n\tfor key, value := range rewards {\n\t\tpath.rewards[key] += value\n\t}\n}", "func (_TrialRulesAbstract *TrialRulesAbstractCallerSession) GetReward() (*big.Int, error) {\n\treturn _TrialRulesAbstract.Contract.GetReward(&_TrialRulesAbstract.CallOpts)\n}", "func NewRewardMerkleTree(rewardMap RewardMap) (*RewardMerkleTree, error) {\n\tmerkleTreeLeaves := make(RewardMerkleTreeLeaves, len(rewardMap))\n\ti := 0\n\tsum := decimal.Zero\n\tfor account, amount := range rewardMap {\n\t\tmerkleTreeLeaves[i] = RewardMerkleTreeLeaf{\n\t\t\tAccount: account,\n\t\t\tAmount: ethereum.ToSmallUnit(amount, furucombo.COMBODecimals),\n\t\t}\n\t\ti++\n\t\tsum = sum.Add(amount)\n\t}\n\tlog.Printf(\"print sum of each amount: %s\", sum.String())\n\n\tsort.Sort(merkleTreeLeaves)\n\n\tmerkleTree, err := merkletree.NewTreeWithConfig(merkleTreeLeaves.ToMerkleTreeContents(), &rewardMerkleTreeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trewardMerkleTree := &RewardMerkleTree{\n\t\tMerkleTree: merkleTree,\n\t\tMerkleTreeLeaves: merkleTreeLeaves,\n\t}\n\n\treturn rewardMerkleTree, nil\n}", "func (_TrialRulesAbstract *TrialRulesAbstractSession) GetReward() (*big.Int, error) {\n\treturn _TrialRulesAbstract.Contract.GetReward(&_TrialRulesAbstract.CallOpts)\n}", "func (m *MemoryRewardStorage) Update(reward rewards.Reward) {\n\tfor index, r := range m.rewards {\n\t\tif r.ID == reward.ID {\n\t\t\tm.rewards[index] = reward\n\t\t}\n\t}\n}", "func (_Dospayment *DospaymentTransactor) ClaimGuardianReward(opts *bind.TransactOpts, guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.contract.Transact(opts, \"claimGuardianReward\", guardianAddr)\n}", "func (_Smartchef *SmartchefSession) EmergencyRewardWithdraw(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.Contract.EmergencyRewardWithdraw(&_Smartchef.TransactOpts, _amount)\n}", "func (c *SkillClient) UpdateOne(s *Skill) *SkillUpdateOne {\n\tmutation := newSkillMutation(c.config, OpUpdateOne, withSkill(s))\n\treturn &SkillUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (aspect LogAspect) AddSingle(level logLevel, writer io.Writer) {\n\tlogger := log.New(writer, aspect.prefix(level), log.LstdFlags)\n\taspect.loggers[level] = append(aspect.loggers[level], logger)\n}", "func (e *engineImpl) Rewarder() reward.Distributor {\n\treturn e.d\n}", "func (_Smartchef *SmartchefTransactorSession) EmergencyRewardWithdraw(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.Contract.EmergencyRewardWithdraw(&_Smartchef.TransactOpts, _amount)\n}", "func (_XStaking *XStakingSession) LastTimeRewardApplicable() (*big.Int, error) {\n\treturn _XStaking.Contract.LastTimeRewardApplicable(&_XStaking.CallOpts)\n}", "func (k Keeper) GetReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) (reward types.Reward, found bool) {\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := store.Get(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tif bz == nil {\n\t\treturn reward, false\n\t}\n\tvar rewardCoins types.RewardCoins\n\tk.cdc.MustUnmarshal(bz, &rewardCoins)\n\treturn types.Reward{\n\t\tFarmer: farmerAcc.String(),\n\t\tStakingCoinDenom: stakingCoinDenom,\n\t\tRewardCoins: rewardCoins.RewardCoins,\n\t}, true\n}" ]
[ "0.612093", "0.59551144", "0.59414524", "0.5776947", "0.5700438", "0.5679214", "0.54675496", "0.53945607", "0.53710365", "0.52962494", "0.52574825", "0.5234012", "0.52230954", "0.5210352", "0.5163299", "0.514713", "0.5118373", "0.5050562", "0.50385445", "0.5029193", "0.49917898", "0.4966482", "0.4942335", "0.4942018", "0.49350587", "0.4911105", "0.4908899", "0.4898163", "0.4893694", "0.48822403", "0.48808378", "0.48719102", "0.4865506", "0.4863003", "0.48468605", "0.48410648", "0.48403218", "0.48379195", "0.4820257", "0.48143905", "0.4810663", "0.4810448", "0.47937718", "0.47862136", "0.47854847", "0.4756857", "0.4725954", "0.47236678", "0.4707887", "0.46933076", "0.4676489", "0.46648288", "0.46568874", "0.4649597", "0.4628068", "0.46095455", "0.45940685", "0.45808586", "0.45504487", "0.4535895", "0.45234293", "0.45185533", "0.45135146", "0.450406", "0.44972974", "0.44930333", "0.44778895", "0.4460262", "0.44484794", "0.44427535", "0.44409144", "0.4426835", "0.44136995", "0.4411044", "0.4406666", "0.44022116", "0.43987373", "0.4395584", "0.43752238", "0.4370012", "0.43677646", "0.43670392", "0.43599728", "0.43580988", "0.43511626", "0.4343114", "0.4337343", "0.43306243", "0.43283513", "0.4321045", "0.43203253", "0.4295555", "0.4293976", "0.42901337", "0.42802247", "0.427984", "0.4275537", "0.42736322", "0.42726573", "0.42692384" ]
0.84411126
0
NewMerkleBlobAccess creates an adapter that validates that blobs read from and written to storage correspond with the digest that is used for identification. It ensures that the size and the SHA256 based checksum match. This is used to ensure clients cannot corrupt the CAS and that if corruption were to occur, use of corrupted data is prevented.
NewMerkleBlobAccess создает адаптер, который проверяет, соответствуют ли данные, считываемые из и записываемые в хранилище, дайджесту, используемому для идентификации. Он гарантирует, что размер и контрольная сумма, основанная на SHA256, совпадают. Это используется для обеспечения того, чтобы клиенты не могли повредить CAS, а также для предотвращения использования поврежденных данных в случае их возникновения.
func NewMerkleBlobAccess(blobAccess BlobAccess) BlobAccess { return &merkleBlobAccess{ BlobAccess: blobAccess, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewFlatBlobAccess(keyLocationMap KeyLocationMap, locationBlobMap LocationBlobMap, digestKeyFormat digest.KeyFormat, lock *sync.RWMutex, storageType string, capabilitiesProvider capabilities.Provider) blobstore.BlobAccess {\n\tflatBlobAccessPrometheusMetrics.Do(func() {\n\t\tprometheus.MustRegister(flatBlobAccessRefreshes)\n\t})\n\n\treturn &flatBlobAccess{\n\t\tProvider: capabilitiesProvider,\n\n\t\tkeyLocationMap: keyLocationMap,\n\t\tlocationBlobMap: locationBlobMap,\n\t\tdigestKeyFormat: digestKeyFormat,\n\t\tlock: lock,\n\n\t\trefreshesGet: flatBlobAccessRefreshes.WithLabelValues(storageType, \"Get\"),\n\t\trefreshesGetFromComposite: flatBlobAccessRefreshes.WithLabelValues(storageType, \"GetFromComposite\"),\n\t\trefreshesFindMissing: flatBlobAccessRefreshes.WithLabelValues(storageType, \"FindMissing\"),\n\t}\n}", "func NewCompletenessCheckingBlobAccess(actionCache, contentAddressableStorage blobstore.BlobAccess, batchSize, maximumMessageSizeBytes int, maximumTotalTreeSizeBytes int64) blobstore.BlobAccess {\n\treturn &completenessCheckingBlobAccess{\n\t\tBlobAccess: actionCache,\n\t\tcontentAddressableStorage: contentAddressableStorage,\n\t\tbatchSize: batchSize,\n\t\tmaximumMessageSizeBytes: maximumMessageSizeBytes,\n\t\tmaximumTotalTreeSizeBytes: maximumTotalTreeSizeBytes,\n\t}\n}", "func NewBlobDigestCalculator() *BlobDigestCalculator {\n\treturn &BlobDigestCalculator{\n\t\th: sha256.New(),\n\t}\n}", "func GetBlob(blobSum string, digest string) *Blob {\n\n\tb := new(Blob)\n\tb.ID = digest\n\n\tif !b.IsExist() {\n\t\tlogger.Errorf(\"blob of %s not exist\\n\", digest)\n\t\treturn nil\n\t}\n\n\tfd, err := os.Open(b.FilePath())\n\tif err != nil {\n\t\tlogger.Errorf(\"open file of %s error\\n\", b.FilePath())\n\t\treturn nil\n\t}\n\n\tdefer fd.Close()\n\n\tdata, err := ioutil.ReadAll(fd)\n\tif err != nil {\n\t\tlogger.Errorf(\"read file from %s error\\n\", b.FilePath())\n\t\treturn nil\n\t}\n\n\tb.Data = data\n\tb.Size = utils.GetFileSize(b.FilePath())\n\tb.RefCount = b.GetRefCount()\n\n\treturn b\n}", "func FromBlob(blob []byte) *repb.Digest {\n\tsha256Arr := sha256.Sum256(blob)\n\treturn mustNew(hex.EncodeToString(sha256Arr[:]), int64(len(blob)))\n}", "func New(ag agent.Agent, validators []types.Address, storage storage.Storage) (*MerkleSyncer, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\treturn &MerkleSyncer{\n\t\twrapperC: make(chan *pb.MerkleWrapper, wrapperCNumber),\n\t\tagent: ag,\n\t\tvalidators: validators,\n\t\tstorage: storage,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t}, nil\n}", "func NewMetricsBlobAccess(blobAccess BlobAccess, clock clock.Clock, storageType, backendType string) BlobAccess {\n\tblobAccessOperationsPrometheusMetrics.Do(func() {\n\t\tprometheus.MustRegister(blobAccessOperationsBlobSizeBytes)\n\t\tprometheus.MustRegister(blobAccessOperationsFindMissingBatchSize)\n\t\tprometheus.MustRegister(blobAccessOperationsDurationSeconds)\n\t})\n\n\treturn &metricsBlobAccess{\n\t\tblobAccess: blobAccess,\n\t\tclock: clock,\n\n\t\tgetBlobSizeBytes: blobAccessOperationsBlobSizeBytes.WithLabelValues(storageType, backendType, \"Get\"),\n\t\tgetDurationSeconds: blobAccessOperationsDurationSeconds.MustCurryWith(map[string]string{\"storage_type\": storageType, \"backend_type\": backendType, \"operation\": \"Get\"}),\n\t\tgetFromCompositeBlobSizeBytes: blobAccessOperationsBlobSizeBytes.WithLabelValues(storageType, backendType, \"GetFromComposite\"),\n\t\tgetFromCompositeDurationSeconds: blobAccessOperationsDurationSeconds.MustCurryWith(map[string]string{\"storage_type\": storageType, \"backend_type\": backendType, \"operation\": \"GetFromComposite\"}),\n\t\tputBlobSizeBytes: blobAccessOperationsBlobSizeBytes.WithLabelValues(storageType, backendType, \"Put\"),\n\t\tputDurationSeconds: blobAccessOperationsDurationSeconds.MustCurryWith(map[string]string{\"storage_type\": storageType, \"backend_type\": backendType, \"operation\": \"Put\"}),\n\t\tfindMissingBatchSize: blobAccessOperationsFindMissingBatchSize.WithLabelValues(storageType, backendType),\n\t\tfindMissingDurationSeconds: blobAccessOperationsDurationSeconds.MustCurryWith(map[string]string{\"storage_type\": storageType, \"backend_type\": backendType, \"operation\": \"FindMissing\"}),\n\t\tgetCapabilitiesSeconds: blobAccessOperationsDurationSeconds.MustCurryWith(map[string]string{\"storage_type\": storageType, \"backend_type\": backendType, \"operation\": \"GetCapabilities\"}),\n\t}\n}", "func (b *BitsImageManager) GetBlob(name string, digest string) io.ReadCloser {\n\tif digest == b.rootfsDigest {\n\t\tr, e := b.rootFSBlobstore.Get(\"assets/eirinifs.tar\")\n\t\tutil.PanicOnError(errors.WithStack(e))\n\t\treturn r\n\t}\n\n\tr, e := b.digestLookupStore.Get(digest)\n\tif _, notFound := e.(*bitsgo.NotFoundError); notFound {\n\t\treturn nil\n\t}\n\n\tutil.PanicOnError(errors.WithStack(e))\n\treturn r\n}", "func (te *TreeEntry) Blob() *Blob {\n\treturn &Blob{\n\t\tID: te.ID,\n\t\tname: te.Name(),\n\t\tsize: te.size,\n\t\tgotSize: te.sized,\n\t\trepo: te.ptree.repo,\n\t}\n}", "func (is *ObjectStorage) GetBlob(repo string, digest godigest.Digest, mediaType string) (io.ReadCloser, int64, error) {\n\tvar lockLatency time.Time\n\n\tif err := digest.Validate(); err != nil {\n\t\treturn nil, -1, err\n\t}\n\n\tblobPath := is.BlobPath(repo, digest)\n\n\tis.RLock(&lockLatency)\n\tdefer is.RUnlock(&lockLatency)\n\n\tbinfo, err := is.store.Stat(context.Background(), blobPath)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"blob\", blobPath).Msg(\"failed to stat blob\")\n\n\t\treturn nil, -1, zerr.ErrBlobNotFound\n\t}\n\n\tblobReadCloser, err := is.store.Reader(context.Background(), blobPath, 0)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"blob\", blobPath).Msg(\"failed to open blob\")\n\n\t\treturn nil, -1, err\n\t}\n\n\t// is a 'deduped' blob?\n\tif binfo.Size() == 0 {\n\t\t// Check blobs in cache\n\t\tdstRecord, err := is.checkCacheBlob(digest)\n\t\tif err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"digest\", digest.String()).Msg(\"cache: not found\")\n\n\t\t\treturn nil, -1, zerr.ErrBlobNotFound\n\t\t}\n\n\t\tbinfo, err := is.store.Stat(context.Background(), dstRecord)\n\t\tif err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"blob\", dstRecord).Msg(\"failed to stat blob\")\n\n\t\t\treturn nil, -1, zerr.ErrBlobNotFound\n\t\t}\n\n\t\tblobReadCloser, err := is.store.Reader(context.Background(), dstRecord, 0)\n\t\tif err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"blob\", dstRecord).Msg(\"failed to open blob\")\n\n\t\t\treturn nil, -1, err\n\t\t}\n\n\t\treturn blobReadCloser, binfo.Size(), nil\n\t}\n\n\t// The caller function is responsible for calling Close()\n\treturn blobReadCloser, binfo.Size(), nil\n}", "func TestOneEntry(t *testing.T) {\n\tm, err := NewMerkleTree()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar commit [32]byte\n\tvar expect [32]byte\n\n\tkey := \"key\"\n\tval := []byte(\"value\")\n\tindex := staticVRFKey.Compute([]byte(key))\n\tif err := m.Set(index, key, val); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tm.recomputeHash()\n\n\t// Check empty node hash\n\th := sha3.NewShake128()\n\th.Write([]byte{EmptyBranchIdentifier})\n\th.Write(m.nonce)\n\th.Write(utils.ToBytes([]bool{true}))\n\th.Write(utils.UInt32ToBytes(1))\n\th.Read(expect[:])\n\tif !bytes.Equal(m.root.rightHash, expect[:]) {\n\t\tt.Error(\"Wrong righ hash!\",\n\t\t\t\"expected\", expect,\n\t\t\t\"get\", m.root.rightHash)\n\t}\n\n\tr := m.Get(index)\n\tif r.Leaf.Value == nil {\n\t\tt.Error(\"Cannot find value of key:\", key)\n\t\treturn\n\t}\n\tv := r.Leaf.Value\n\tif !bytes.Equal(v, val) {\n\t\tt.Errorf(\"Value mismatch %v / %v\", v, val)\n\t}\n\n\t// Check leaf node hash\n\th.Reset()\n\th.Write(r.Leaf.Commitment.Salt)\n\th.Write([]byte(key))\n\th.Write(val)\n\th.Read(commit[:])\n\n\th.Reset()\n\th.Write([]byte{LeafIdentifier})\n\th.Write(m.nonce)\n\th.Write(index)\n\th.Write(utils.UInt32ToBytes(1))\n\th.Write(commit[:])\n\th.Read(expect[:])\n\n\tif !bytes.Equal(m.root.leftHash, expect[:]) {\n\t\tt.Error(\"Wrong left hash!\",\n\t\t\t\"expected\", expect,\n\t\t\t\"get\", m.root.leftHash)\n\t}\n\n\tr = m.Get([]byte(\"abc\"))\n\tif r.Leaf.Value != nil {\n\t\tt.Error(\"Invalid look-up operation:\", key)\n\t\treturn\n\t}\n}", "func (c *containerdCAS) ReadBlob(blobHash string) (io.Reader, error) {\n\tshaDigest := digest.Digest(blobHash)\n\t_, err := contentStore.Info(ctrdCtx, shaDigest)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ReadBlob: Exception getting info of blob: %s. %s\", blobHash, err.Error())\n\t}\n\treaderAt, err := contentStore.ReaderAt(ctrdCtx, spec.Descriptor{Digest: shaDigest})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ReadBlob: Exception while reading blob: %s. %s\", blobHash, err.Error())\n\t}\n\treturn content.NewReader(readerAt), nil\n}", "func (sr *immutableRef) setBlob(ctx context.Context, desc ocispec.Descriptor) error {\n\tif _, ok := leases.FromContext(ctx); !ok {\n\t\treturn errors.Errorf(\"missing lease requirement for setBlob\")\n\t}\n\n\tdiffID, err := diffIDFromDescriptor(desc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := sr.cm.ContentStore.Info(ctx, desc.Digest); err != nil {\n\t\treturn err\n\t}\n\n\tsr.mu.Lock()\n\tdefer sr.mu.Unlock()\n\n\tif getChainID(sr.md) != \"\" {\n\t\treturn nil\n\t}\n\n\tif err := sr.finalize(ctx, true); err != nil {\n\t\treturn err\n\t}\n\n\tp := sr.parent\n\tvar parentChainID digest.Digest\n\tvar parentBlobChainID digest.Digest\n\tif p != nil {\n\t\tpInfo := p.Info()\n\t\tif pInfo.ChainID == \"\" || pInfo.BlobChainID == \"\" {\n\t\t\treturn errors.Errorf(\"failed to set blob for reference with non-addressable parent\")\n\t\t}\n\t\tparentChainID = pInfo.ChainID\n\t\tparentBlobChainID = pInfo.BlobChainID\n\t}\n\n\tif err := sr.cm.LeaseManager.AddResource(ctx, leases.Lease{ID: sr.ID()}, leases.Resource{\n\t\tID: desc.Digest.String(),\n\t\tType: \"content\",\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tqueueDiffID(sr.md, diffID.String())\n\tqueueBlob(sr.md, desc.Digest.String())\n\tchainID := diffID\n\tblobChainID := imagespecidentity.ChainID([]digest.Digest{desc.Digest, diffID})\n\tif parentChainID != \"\" {\n\t\tchainID = imagespecidentity.ChainID([]digest.Digest{parentChainID, chainID})\n\t\tblobChainID = imagespecidentity.ChainID([]digest.Digest{parentBlobChainID, blobChainID})\n\t}\n\tqueueChainID(sr.md, chainID.String())\n\tqueueBlobChainID(sr.md, blobChainID.String())\n\tqueueMediaType(sr.md, desc.MediaType)\n\tqueueBlobSize(sr.md, desc.Size)\n\tif err := sr.md.Commit(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Repo) AddBlob(root string, rd io.Reader) (string, error) {\n\tblobDir := filepath.Join(r.path, \"repository\", \"blobs\")\n\tos.MkdirAll(blobDir, os.ModePerm)\n\n\tif root != \"\" {\n\t\tdst := filepath.Join(blobDir, root)\n\t\tf, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0666)\n\t\tif err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\treturn root, nil\n\t\t\t}\n\t\t\treturn root, err\n\t\t}\n\t\tdefer f.Close()\n\t\t_, err = io.Copy(f, rd)\n\t\treturn root, err\n\t}\n\n\tvar tree merkle.Tree\n\tf, err := ioutil.TempFile(blobDir, \"blob\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif _, err := tree.ReadFrom(io.TeeReader(rd, f)); err != nil {\n\t\tf.Close()\n\t\treturn \"\", err\n\t}\n\tf.Close()\n\troot = hex.EncodeToString(tree.Root())\n\treturn root, os.Rename(f.Name(), filepath.Join(blobDir, root))\n}", "func NewBlobEntry(dataHint, data []byte) BlobEntry {\n\treturn BlobEntry{\n\t\tDigest: hex.EncodeToString(util.Digest(data)),\n\t\tDataHint: base64.StdEncoding.EncodeToString(dataHint),\n\t\tData: base64.StdEncoding.EncodeToString(data),\n\t}\n}", "func (te *TreeEntry) Blob() *Blob {\n\tencodedObj, err := te.ptree.repo.gogitRepo.Storer.EncodedObject(plumbing.AnyObject, te.gogitTreeEntry.Hash)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &Blob{\n\t\tID: te.gogitTreeEntry.Hash,\n\t\tgogitEncodedObj: encodedObj,\n\t\tname: te.Name(),\n\t}\n}", "func (c *containerdCAS) IngestBlob(ctx context.Context, blobHash string, reader io.Reader) error {\n\tleaseOpts := make([]leases.Opt, 0)\n\tvar leaseID string\n\tif ctx.Value(\"contextID\") == nil {\n\t\treturn fmt.Errorf(\"IngestBlob: context does not have 'contextID'\")\n\t}\n\tif ctx.Value(\"expires\") == nil {\n\t\treturn fmt.Errorf(\"IngestBlob: context does not have 'expires'\")\n\t}\n\tif leaseID = ctx.Value(\"contextID\").(string); leaseID != \"\" {\n\t\tleaseOpts = append(leaseOpts, leases.WithID(leaseID))\n\t}\n\n\tif exp := ctx.Value(\"expires\").(time.Duration); exp > 0 {\n\t\tleaseOpts = append(leaseOpts, leases.WithExpiration(exp))\n\t}\n\n\t_, err := ctrdClient.LeasesService().Create(ctrdCtx, leaseOpts...)\n\tif err != nil && !isAlreadyExistsError(err) {\n\t\treturn fmt.Errorf(\"IngestBlob: Exception while creating lease: %s. %s\", leaseID, err.Error())\n\t}\n\tctrdCtx = leases.WithLease(ctrdCtx, leaseID)\n\tif blobHash == \"\" {\n\t\treturn fmt.Errorf(\"IngestBlob: blobHash cannot be empty\")\n\t}\n\texpectedSha256Digest := digest.Digest(blobHash)\n\tif err = content.WriteBlob(ctrdCtx, contentStore, blobHash, reader, spec.Descriptor{Digest: expectedSha256Digest}); err != nil {\n\t\treturn fmt.Errorf(\"IngestBlob: Exception while writing blob: %s. %s\", blobHash, err.Error())\n\t}\n\treturn nil\n}", "func New(hash hash.Hash, data [][]byte) *MerkleTree {\n\tvar n int\n\n\tif data == nil || len(data) == 0 {\n\t\treturn nil\n\t}\n\tif n = len(data); n == 0 {\n\t\treturn nil\n\t}\n\tr := &MerkleTree{\n\t\thash: hash,\n\t}\n\tr.tree = r.mkMerkleTreeRoot(n, data)\n\treturn r\n}", "func NewHTTPBlobAccess(address, prefix string, readBufferFactory ReadBufferFactory, httpClient *http.Client, capabilitiesProvider capabilities.Provider) BlobAccess {\n\treturn &httpBlobAccess{\n\t\tProvider: capabilitiesProvider,\n\n\t\taddress: address,\n\t\tprefix: prefix,\n\t\treadBufferFactory: readBufferFactory,\n\t\thttpClient: httpClient,\n\t}\n}", "func GetBlobHuge(blobSum string, digest string, index int, length int) *blobs.Blob {\n\tblobManifest := GetBlobsManifest(blobSum)\n\tif blobManifest == nil {\n\t\tlogger.Errorf(\"blob-manifest %s not exist\", blobSum)\n\t\treturn nil\n\t}\n\n\timageFilePath := configuration.RootDirectory() + \"/\" + manifest.ManifestDir + \"/\" + blobSum + \"/\" + \"image\"\n\n\tlogger.Debugf(\"image file path of huge file %s\", imageFilePath)\n\n\tdata, err := utils.GetFileData(imageFilePath, index, length)\n\tif err != nil {\n\t\tlogger.Errorf(\"get data from file %s error, index %d, length %d, %s\",\n\t\timageFilePath, index, length, err)\n\t\treturn nil;\n\t}\n\n\tb := new(blobs.Blob)\n\tb.ID = digest\n\tb.Data = data\n\tb.Size = int64(length)\n\tb.RefCount = 1\n\n\treturn b\t\n}", "func (is *ObjectStorage) CheckBlob(repo string, digest godigest.Digest) (bool, int64, error) {\n\tvar lockLatency time.Time\n\n\tif err := digest.Validate(); err != nil {\n\t\treturn false, -1, err\n\t}\n\n\tblobPath := is.BlobPath(repo, digest)\n\n\tif is.dedupe && fmt.Sprintf(\"%v\", is.cache) != fmt.Sprintf(\"%v\", nil) {\n\t\tis.Lock(&lockLatency)\n\t\tdefer is.Unlock(&lockLatency)\n\t} else {\n\t\tis.RLock(&lockLatency)\n\t\tdefer is.RUnlock(&lockLatency)\n\t}\n\n\tbinfo, err := is.store.Stat(context.Background(), blobPath)\n\tif err == nil && binfo.Size() > 0 {\n\t\tis.log.Debug().Str(\"blob path\", blobPath).Msg(\"blob path found\")\n\n\t\treturn true, binfo.Size(), nil\n\t}\n\t// otherwise is a 'deduped' blob (empty file)\n\n\t// Check blobs in cache\n\tdstRecord, err := is.checkCacheBlob(digest)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"digest\", digest.String()).Msg(\"cache: not found\")\n\n\t\treturn false, -1, zerr.ErrBlobNotFound\n\t}\n\n\tblobSize, err := is.copyBlob(repo, blobPath, dstRecord)\n\tif err != nil {\n\t\treturn false, -1, zerr.ErrBlobNotFound\n\t}\n\n\t// put deduped blob in cache\n\tif err := is.cache.PutBlob(digest, blobPath); err != nil {\n\t\tis.log.Error().Err(err).Str(\"blobPath\", blobPath).Msg(\"dedupe: unable to insert blob record\")\n\n\t\treturn false, -1, err\n\t}\n\n\treturn true, blobSize, nil\n}", "func New(h hash.Hash) *MerkleTree {\n\tif h == nil {\n\t\th = sha256.New()\n\t}\n\treturn &MerkleTree{\n\t\tnil, nil, h, nil,\n\t}\n}", "func (is *ImageStoreLocal) CheckBlob(repo string, digest godigest.Digest) (bool, int64, error) {\n\tvar lockLatency time.Time\n\n\tif err := digest.Validate(); err != nil {\n\t\treturn false, -1, err\n\t}\n\n\tif is.dedupe && fmt.Sprintf(\"%v\", is.cache) != fmt.Sprintf(\"%v\", nil) {\n\t\tis.Lock(&lockLatency)\n\t\tdefer is.Unlock(&lockLatency)\n\t} else {\n\t\tis.RLock(&lockLatency)\n\t\tdefer is.RUnlock(&lockLatency)\n\t}\n\n\tif ok, size, err := is.StatBlob(repo, digest); err == nil || ok {\n\t\treturn true, size, nil\n\t}\n\n\tblobPath := is.BlobPath(repo, digest)\n\n\tis.log.Debug().Str(\"blob\", blobPath).Msg(\"failed to find blob, searching it in cache\")\n\n\t// Check blobs in cache\n\tdstRecord, err := is.checkCacheBlob(digest)\n\tif err != nil {\n\t\treturn false, -1, zerr.ErrBlobNotFound\n\t}\n\n\t// If found copy to location\n\tblobSize, err := is.copyBlob(repo, blobPath, dstRecord)\n\tif err != nil {\n\t\treturn false, -1, zerr.ErrBlobNotFound\n\t}\n\n\tif err := is.cache.PutBlob(digest, blobPath); err != nil {\n\t\tis.log.Error().Err(err).Str(\"blobPath\", blobPath).Msg(\"dedupe: unable to insert blob record\")\n\n\t\treturn false, -1, err\n\t}\n\n\treturn true, blobSize, nil\n}", "func NewBlobRangeFinder(getObjects *[]helperModels.GetObject) BlobRangeFinder {\n rangeMap := toRangeMap(getObjects)\n return &BlobRangeFinderImpl{\n rangeMap: *rangeMap,\n collapser: RangeCollapserImpl{},\n }\n}", "func getBlob(tx *sql.Tx, digest string) (*Blob, error) {\n\tvar b *Blob\n\trows, err := tx.Query(\"SELECT * from blobinfo WHERE digest == $1\", digest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor rows.Next() {\n\t\tb = &Blob{}\n\t\tif err := blobRowScan(rows, b); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// No more than one row for digest must exist.\n\t\tbreak\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, err\n}", "func (c *ContainerClient) NewBlobClient(blobName string) (*BlobClient, error) {\n\tblobURL := appendToURLPath(c.URL(), blobName)\n\n\treturn &BlobClient{\n\t\tclient: newBlobClient(blobURL, c.client.pl),\n\t\tsharedKey: c.sharedKey,\n\t}, nil\n}", "func NewLeaf(data []byte, h hash.Hash) *MerkleTree {\n\tif h == nil {\n\t\th = sha256.New()\n\t}\n\n\tmt := &MerkleTree{\n\t\tnil, nil, h, nil,\n\t}\n\n\tmt.Hash(data)\n\treturn mt\n}", "func NewBlob(id string, length int64, contentType string) *BlobDatum {\n\treturn &BlobDatum{\n\t\tBlobId: id,\n\t\tLength: length,\n\t\tContentType: contentType,\n\t}\n}", "func (l logger) LogBlob(d digest.Digest, level int, err error, isCached bool) {\n\tindent := strings.Repeat(\" \", level)\n\tsuffix := \"\"\n\tif isCached {\n\t\tsuffix = \" (cached result)\"\n\t}\n\tif err == nil {\n\t\tlogg.Info(\"%sblob %s looks good%s\", indent, d, suffix)\n\t} else {\n\t\tlogg.Error(\"%sblob %s validation failed: %s%s\", indent, d, err.Error(), suffix)\n\t}\n}", "func NewBlobClient(cre *properties.Credentials) (blob Blob, err error) {\n\tvar rawUrl string\n\tif strings.HasPrefix(cre.Endpoint, \"blob.\") {\n\t\trawUrl = fmt.Sprintf(\"https://%s.%s/\", cre.AccessKey, cre.Endpoint)\n\t} else {\n\t\trawUrl = fmt.Sprintf(\"https://%s.blob.%s/\", cre.AccessKey, cre.Endpoint)\n\t}\n\tcredential, err := azblob.NewSharedKeyCredential(cre.AccessKey, cre.Secretkey)\n\tif err != nil {\n\t\t//HandleError(err)\n\t\treturn blob, err\n\t}\n\tuRL, _ := url.Parse(rawUrl)\n\tp := azblob.NewPipeline(credential, azblob.PipelineOptions{})\n\tserviceUrl := azblob.NewServiceURL(*uRL, p)\n\tblob.ServiceUrl = &serviceUrl\n\treturn blob, err\n}", "func (is *ObjectStorage) FullBlobUpload(repo string, body io.Reader, dstDigest godigest.Digest) (string, int64, error) {\n\tif err := dstDigest.Validate(); err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tif err := is.InitRepo(repo); err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tu, err := guuid.NewV4()\n\tif err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tuuid := u.String()\n\tsrc := is.BlobUploadPath(repo, uuid)\n\tdigester := sha256.New()\n\tbuf := new(bytes.Buffer)\n\n\t_, err = buf.ReadFrom(body)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Msg(\"failed to read blob\")\n\n\t\treturn \"\", -1, err\n\t}\n\n\tnbytes, err := writeFile(is.store, src, buf.Bytes())\n\tif err != nil {\n\t\tis.log.Error().Err(err).Msg(\"failed to write blob\")\n\n\t\treturn \"\", -1, err\n\t}\n\n\t_, err = digester.Write(buf.Bytes())\n\tif err != nil {\n\t\tis.log.Error().Err(err).Msg(\"digester failed to write\")\n\n\t\treturn \"\", -1, err\n\t}\n\n\tsrcDigest := godigest.NewDigestFromEncoded(godigest.SHA256, fmt.Sprintf(\"%x\", digester.Sum(nil)))\n\tif srcDigest != dstDigest {\n\t\tis.log.Error().Str(\"srcDigest\", srcDigest.String()).\n\t\t\tStr(\"dstDigest\", dstDigest.String()).Msg(\"actual digest not equal to expected digest\")\n\n\t\treturn \"\", -1, zerr.ErrBadBlobDigest\n\t}\n\n\tvar lockLatency time.Time\n\n\tis.Lock(&lockLatency)\n\tdefer is.Unlock(&lockLatency)\n\n\tdst := is.BlobPath(repo, dstDigest)\n\n\tif is.dedupe && fmt.Sprintf(\"%v\", is.cache) != fmt.Sprintf(\"%v\", nil) {\n\t\tif err := is.DedupeBlob(src, dstDigest, dst); err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"src\", src).Str(\"dstDigest\", dstDigest.String()).\n\t\t\t\tStr(\"dst\", dst).Msg(\"unable to dedupe blob\")\n\n\t\t\treturn \"\", -1, err\n\t\t}\n\t} else {\n\t\tif err := is.store.Move(context.Background(), src, dst); err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"src\", src).Str(\"dstDigest\", dstDigest.String()).\n\t\t\t\tStr(\"dst\", dst).Msg(\"unable to finish blob\")\n\n\t\t\treturn \"\", -1, err\n\t\t}\n\t}\n\n\treturn uuid, int64(nbytes), nil\n}", "func newAzureBlobStorage(conf input.AzureBlobStorageConfig, log log.Modular, stats metrics.Type) (*azureBlobStorage, error) {\n\tif conf.StorageAccount == \"\" && conf.StorageConnectionString == \"\" {\n\t\treturn nil, errors.New(\"invalid azure storage account credentials\")\n\t}\n\n\tvar client storage.Client\n\tvar err error\n\tif len(conf.StorageConnectionString) > 0 {\n\t\tif strings.Contains(conf.StorageConnectionString, \"UseDevelopmentStorage=true;\") {\n\t\t\tclient, err = storage.NewEmulatorClient()\n\t\t} else {\n\t\t\tclient, err = storage.NewClientFromConnectionString(conf.StorageConnectionString)\n\t\t}\n\t} else if len(conf.StorageAccessKey) > 0 {\n\t\tclient, err = storage.NewBasicClient(conf.StorageAccount, conf.StorageAccessKey)\n\t} else {\n\t\t// The SAS token in the Azure UI is provided as an URL query string with\n\t\t// the '?' prepended to it which confuses url.ParseQuery\n\t\ttoken, err := url.ParseQuery(strings.TrimPrefix(conf.StorageSASToken, \"?\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid azure storage SAS token: %w\", err)\n\t\t}\n\t\tclient = storage.NewAccountSASClient(conf.StorageAccount, token, azure.PublicCloud)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid azure storage account credentials: %w\", err)\n\t}\n\n\tvar objectScannerCtor codec.ReaderConstructor\n\tif objectScannerCtor, err = codec.GetReader(conf.Codec, codec.NewReaderConfig()); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid azure storage codec: %w\", err)\n\t}\n\n\tblobService := client.GetBlobService()\n\ta := &azureBlobStorage{\n\t\tconf: conf,\n\t\tobjectScannerCtor: objectScannerCtor,\n\t\tlog: log,\n\t\tstats: stats,\n\t\tcontainer: blobService.GetContainerReference(conf.Container),\n\t}\n\n\treturn a, nil\n}", "func (b Base) GetBlob(sum string) (ReadSeekCloser, error) {\n\treturn os.Open(b.blobPath(sum))\n}", "func NewTree(id string, cache storage.Cache, leaves storage.Store, hasher hashing.Hasher) *Tree {\n\n\tcacheLevels := int(math.Max(0.0, math.Floor(math.Log(float64(cache.Size()))/math.Log(2.0))))\n\tdigestLength := len(hasher([]byte(\"a test event\"))) * 8\n\n\ttree := &Tree{\n\t\t[]byte(id),\n\t\tleafHasherF(hasher),\n\t\tinteriorHasherF(hasher),\n\t\tmake([][]byte, digestLength),\n\t\tcache,\n\t\tleaves,\n\t\tnew(stats),\n\t\tnewArea(digestLength-cacheLevels, digestLength),\n\t\tdigestLength,\n\t\tnil,\n\t}\n\n\t// init default hashes cache\n\ttree.defaultHashes[0] = hasher(tree.id, Empty)\n\tfor i := 1; i < int(digestLength); i++ {\n\t\ttree.defaultHashes[i] = hasher(tree.defaultHashes[i-1], tree.defaultHashes[i-1])\n\t}\n\ttree.ops = tree.operations()\n\n\treturn tree\n}", "func (rc *RegClient) BlobMount(ctx context.Context, refSrc ref.Ref, refTgt ref.Ref, d types.Descriptor) error {\n\tschemeAPI, err := rc.schemeGet(refSrc.Scheme)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn schemeAPI.BlobMount(ctx, refSrc, refTgt, d)\n}", "func NewMerkleTree(twc, leafPrefix, interiorPrefix []byte,\n\thash func(data ...[]byte) []byte, data [][]byte) *MerkleTree {\n\tmt := new(MerkleTree)\n\tmt.twc = twc\n\tmt.leafPrefix = leafPrefix\n\tmt.interiorPrefix = interiorPrefix\n\tmt.hash = hash\n\tmt.data = data\n\tmt.cache = new(hashCache)\n\treturn mt\n}", "func readBlob(nd *Node) *Blob {\n\treturn nd.ReadMemo(blobNodeKey{}, func() interface{} {\n\t\tfn := nd.Path()\n\t\tsrc, err := ioutil.ReadFile(fn)\n\t\tif err != nil {\n\t\t\treturn &Blob{err: err}\n\t\t}\n\t\treturn &Blob{src: src}\n\t}).(*Blob)\n}", "func (is *ObjectStorage) GetBlobPartial(repo string, digest godigest.Digest, mediaType string, from, to int64,\n) (io.ReadCloser, int64, int64, error) {\n\tvar lockLatency time.Time\n\n\tif err := digest.Validate(); err != nil {\n\t\treturn nil, -1, -1, err\n\t}\n\n\tblobPath := is.BlobPath(repo, digest)\n\n\tis.RLock(&lockLatency)\n\tdefer is.RUnlock(&lockLatency)\n\n\tbinfo, err := is.store.Stat(context.Background(), blobPath)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"blob\", blobPath).Msg(\"failed to stat blob\")\n\n\t\treturn nil, -1, -1, zerr.ErrBlobNotFound\n\t}\n\n\tend := to\n\n\tif to < 0 || to >= binfo.Size() {\n\t\tend = binfo.Size() - 1\n\t}\n\n\tblobHandle, err := is.store.Reader(context.Background(), blobPath, from)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"blob\", blobPath).Msg(\"failed to open blob\")\n\n\t\treturn nil, -1, -1, err\n\t}\n\n\tblobReadCloser, err := NewBlobStream(blobHandle, from, end)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"blob\", blobPath).Msg(\"failed to open blob stream\")\n\n\t\treturn nil, -1, -1, err\n\t}\n\n\t// is a 'deduped' blob?\n\tif binfo.Size() == 0 {\n\t\tdefer blobReadCloser.Close()\n\n\t\t// Check blobs in cache\n\t\tdstRecord, err := is.checkCacheBlob(digest)\n\t\tif err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"digest\", digest.String()).Msg(\"cache: not found\")\n\n\t\t\treturn nil, -1, -1, zerr.ErrBlobNotFound\n\t\t}\n\n\t\tbinfo, err := is.store.Stat(context.Background(), dstRecord)\n\t\tif err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"blob\", dstRecord).Msg(\"failed to stat blob\")\n\n\t\t\treturn nil, -1, -1, zerr.ErrBlobNotFound\n\t\t}\n\n\t\tend := to\n\n\t\tif to < 0 || to >= binfo.Size() {\n\t\t\tend = binfo.Size() - 1\n\t\t}\n\n\t\tblobHandle, err := is.store.Reader(context.Background(), dstRecord, from)\n\t\tif err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"blob\", dstRecord).Msg(\"failed to open blob\")\n\n\t\t\treturn nil, -1, -1, err\n\t\t}\n\n\t\tblobReadCloser, err := NewBlobStream(blobHandle, from, end)\n\t\tif err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"blob\", blobPath).Msg(\"failed to open blob stream\")\n\n\t\t\treturn nil, -1, -1, err\n\t\t}\n\n\t\treturn blobReadCloser, end - from + 1, binfo.Size(), nil\n\t}\n\n\t// The caller function is responsible for calling Close()\n\treturn blobReadCloser, end - from + 1, binfo.Size(), nil\n}", "func (is *ObjectStorage) NewBlobUpload(repo string) (string, error) {\n\tif err := is.InitRepo(repo); err != nil {\n\t\tis.log.Error().Err(err).Msg(\"error initializing repo\")\n\n\t\treturn \"\", err\n\t}\n\n\tuuid, err := guuid.NewV4()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tuid := uuid.String()\n\n\tblobUploadPath := is.BlobUploadPath(repo, uid)\n\n\t// create multipart upload (append false)\n\t_, err = is.store.Writer(context.Background(), blobUploadPath, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn uid, nil\n}", "func TestMakeBlob(t *testing.T) {\n\tAccount := \"rsTwerzJEGiKh7WjJcC3Q7776D4eGvDXPz\"\n\tAmount := \"30\"\n\tDestination := \"rG5AB117rJ7e2MZGKE4XfaVK5BdyHBxcSm\"\n\tFee := \"12\"\n\tFlags := 2147483648\n\tlast := uint32(13313150)\n\tSequence := 1\n\t//TxnSignature := \"3045022100D59891D15129AFA2297506207AF14A97C2C236C690BA5E167E84BC070CA3774202203F80DFC3D8965AA4705940B9233ED8570812557F1E9DC011DEAF47DC2AE8BD58\"\n\tSigningPubKey := \"028C35EEA94EE7FA9C8485426E164159330BA2453368F399669D5110009F270EE9\"\n\n\tfromAccount, _ := data.NewAccountFromAddress(Account)\n\ttoAccount, _ := data.NewAccountFromAddress(Destination)\n\tamount, _ := data.NewAmount(Amount + \"/XRP\")\n\tfee, _ := data.NewValue(Fee, true)\n\tflags := data.TransactionFlag(Flags)\n\t//tSig, _ := hex.DecodeString(TxnSignature)\n\t//txnSign := data.VariableLength(tSig)\n\tsignPubKey := data.PublicKey{}\n\tpk, _ := hex.DecodeString(SigningPubKey)\n\tcopy(signPubKey[:], pk)\n\n\ttxn := data.TxBase{\n\t\tTransactionType: data.PAYMENT,\n\t\tAccount: *fromAccount,\n\t\tLastLedgerSequence: &last,\n\t\tFlags: &flags,\n\t\tSequence: uint32(Sequence),\n\t\t//TxnSignature: &txnSign,\n\t\tFee: *fee,\n\t\tSigningPubKey: &signPubKey,\n\t}\n\tpayment := data.Payment{\n\t\tTxBase: txn,\n\t\tAmount: *amount,\n\t\tDestination: *toAccount,\n\t}\n\n\t_, res, err := client.makeTxBlob(&payment)\n\tif err != nil {\n\t\tt.Error(\"gen blob err: \", err)\n\t}\n\tt.Log(\"tx blog: \", res)\n}", "func (h *proxyHandler) GetBlob(args []any) (replyBuf, error) {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\n\tvar ret replyBuf\n\n\tif h.sysctx == nil {\n\t\treturn ret, fmt.Errorf(\"client error: must invoke Initialize\")\n\t}\n\tif len(args) != 3 {\n\t\treturn ret, fmt.Errorf(\"found %d args, expecting (imgid, digest, size)\", len(args))\n\t}\n\timgref, err := h.parseImageFromID(args[0])\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tdigestStr, ok := args[1].(string)\n\tif !ok {\n\t\treturn ret, fmt.Errorf(\"expecting string blobid\")\n\t}\n\tsize, err := parseUint64(args[2])\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tctx := context.TODO()\n\td, err := digest.Parse(digestStr)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tblobr, blobSize, err := imgref.src.GetBlob(ctx, types.BlobInfo{Digest: d, Size: int64(size)}, h.cache)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tpiper, f, err := h.allocPipe()\n\tif err != nil {\n\t\tblobr.Close()\n\t\treturn ret, err\n\t}\n\tgo func() {\n\t\t// Signal completion when we return\n\t\tdefer blobr.Close()\n\t\tdefer f.wg.Done()\n\t\tverifier := d.Verifier()\n\t\ttr := io.TeeReader(blobr, verifier)\n\t\tn, err := io.Copy(f.w, tr)\n\t\tif err != nil {\n\t\t\tf.err = err\n\t\t\treturn\n\t\t}\n\t\tif n != int64(size) {\n\t\t\tf.err = fmt.Errorf(\"expected %d bytes in blob, got %d\", size, n)\n\t\t}\n\t\tif !verifier.Verified() {\n\t\t\tf.err = fmt.Errorf(\"corrupted blob, expecting %s\", d.String())\n\t\t}\n\t}()\n\n\tret.value = blobSize\n\tret.fd = piper\n\tret.pipeid = uint32(f.w.Fd())\n\treturn ret, nil\n}", "func (db *merkleDB) NewView(_ context.Context, batchOps []database.BatchOp) (TrieView, error) {\n\t// ensure the db doesn't change while creating the new view\n\tdb.commitLock.RLock()\n\tdefer db.commitLock.RUnlock()\n\n\tnewView, err := db.newUntrackedView(batchOps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ensure access to childViews is protected\n\tdb.lock.Lock()\n\tdefer db.lock.Unlock()\n\n\tdb.childViews = append(db.childViews, newView)\n\treturn newView, nil\n}", "func (fh *FilesystemHandler) ReadBlob(container models.SimpleContainer, blobName string) models.SimpleBlob {\n\tvar blob models.SimpleBlob\n\n\tdirPath := fh.generateFullPath(&container)\n\tfullPath := filepath.Join(dirPath, blobName)\n\n\tblob.DataCachedAtPath = fullPath\n\tblob.BlobInMemory = false\n\tblob.Name = blobName\n\tblob.ParentContainer = &container\n\tblob.Origin = container.Origin\n\tblob.URL = fullPath\n\treturn blob\n}", "func TestLeaf(t *testing.T){\n\tdata := []byte(\"some_utxo\")\n\tvar left Node\n\tvar right Node\n\tvar hash [32]byte\n\tleft = Node{hash:nil,left:nil,right:nil,}\n\tright = Node{hash:nil,left:nil,right:nil,}\n\thash = sha256.Sum256(data)\n\tn_test := Node{\n\t\thash: hash[:],\n\t\tleft: &left,\n\t\tright: &right,\n\t\t\n\t}\t\t\n\tn := makeNode(data,left,right)\n\tn1 := n\n\tn2 := n_test\n\t// first the lenght of bytes\n\tif (len(n1.hash) != len(n2.hash)) {\n\t\tt.Errorf(\"hashes are a different length, %d and %d\", len(n1.hash), len(n2.hash))\n\t}\n\t// the bytes must match\n\tfor i := 0; i < len(n1.hash); i++ {\n\t\tif (n1.hash[i] != n2.hash[i]) {\n\t\t\tt.Errorf(\"hash bytes do not match for byte %d, found %x, expected %x \",i,n1.hash[i],n2.hash[i])\n\t\t}\n\t}\n}", "func (s *Storage) Open(sha256hash string) (ReadSeekCloser, error) {\n\tf, err := s.fs.Open(hashName(sha256hash))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f, nil\n}", "func BlobHash(data []byte) SHA256 {\n\treturn SumSHA256(data)\n}", "func (r *Repository) PullBlob(digest string) (size int64, data io.ReadCloser, err error) {\n\treq, err := http.NewRequest(\"GET\", buildBlobURL(r.Endpoint.String(), r.Name, digest), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresp, err := r.client.Do(req)\n\tif err != nil {\n\t\terr = parseError(err)\n\t\treturn\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\tcontengLength := resp.Header.Get(http.CanonicalHeaderKey(\"Content-Length\"))\n\t\tsize, err = strconv.ParseInt(contengLength, 10, 64)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdata = resp.Body\n\t\treturn\n\t}\n\t// can not close the connect if the status code is 200\n\tdefer resp.Body.Close()\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = &commonhttp.Error{\n\t\tCode: resp.StatusCode,\n\t\tMessage: string(b),\n\t}\n\n\treturn\n}", "func (is *ImageStoreLocal) FullBlobUpload(repo string, body io.Reader, dstDigest godigest.Digest,\n) (string, int64, error) {\n\tif err := dstDigest.Validate(); err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tif err := is.InitRepo(repo); err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tu, err := guuid.NewV4()\n\tif err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tuuid := u.String()\n\n\tsrc := is.BlobUploadPath(repo, uuid)\n\n\tblobFile, err := os.Create(src)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"blob\", src).Msg(\"failed to open blob\")\n\n\t\treturn \"\", -1, zerr.ErrUploadNotFound\n\t}\n\n\tdefer func() {\n\t\tif is.commit {\n\t\t\t_ = blobFile.Sync()\n\t\t}\n\n\t\t_ = blobFile.Close()\n\t}()\n\n\tdigester := sha256.New()\n\tmw := io.MultiWriter(blobFile, digester)\n\n\tnbytes, err := io.Copy(mw, body)\n\tif err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tsrcDigest := godigest.NewDigestFromEncoded(godigest.SHA256, fmt.Sprintf(\"%x\", digester.Sum(nil)))\n\tif srcDigest != dstDigest {\n\t\tis.log.Error().Str(\"srcDigest\", srcDigest.String()).\n\t\t\tStr(\"dstDigest\", dstDigest.String()).Msg(\"actual digest not equal to expected digest\")\n\n\t\treturn \"\", -1, zerr.ErrBadBlobDigest\n\t}\n\n\tdir := path.Join(is.rootDir, repo, \"blobs\", dstDigest.Algorithm().String())\n\n\tvar lockLatency time.Time\n\n\tis.Lock(&lockLatency)\n\tdefer is.Unlock(&lockLatency)\n\n\t_ = ensureDir(dir, is.log)\n\tdst := is.BlobPath(repo, dstDigest)\n\n\tif is.dedupe && fmt.Sprintf(\"%v\", is.cache) != fmt.Sprintf(\"%v\", nil) {\n\t\tif err := is.DedupeBlob(src, dstDigest, dst); err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"src\", src).Str(\"dstDigest\", dstDigest.String()).\n\t\t\t\tStr(\"dst\", dst).Msg(\"unable to dedupe blob\")\n\n\t\t\treturn \"\", -1, err\n\t\t}\n\t} else {\n\t\tif err := os.Rename(src, dst); err != nil {\n\t\t\tis.log.Error().Err(err).Str(\"src\", src).Str(\"dstDigest\", dstDigest.String()).\n\t\t\t\tStr(\"dst\", dst).Msg(\"unable to finish blob\")\n\n\t\t\treturn \"\", -1, err\n\t\t}\n\t}\n\n\treturn uuid, nbytes, nil\n}", "func TestMerkle(t *testing.T) {\n\ttc := SetupTest(t, \"team\", 1)\n\tdefer tc.Cleanup()\n\n\t_, err := kbtest.CreateAndSignupFakeUser(\"team\", tc.G)\n\trequire.NoError(t, err)\n\n\tname := createTeam(tc)\n\n\tteam, err := GetForTestByStringName(context.TODO(), tc.G, name)\n\trequire.NoError(t, err)\n\n\tleaf, err := tc.G.MerkleClient.LookupTeam(libkb.NewMetaContextForTest(tc), team.ID)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, leaf)\n\tt.Logf(\"team merkle leaf: %v\", spew.Sdump(leaf))\n\tif leaf.TeamID.IsNil() {\n\t\tt.Fatalf(\"nil teamID; likely merkle hasn't yet published and polling is busted\")\n\t}\n\trequire.Equal(t, team.ID, leaf.TeamID, \"team id\")\n\trequire.Equal(t, team.chain().GetLatestSeqno(), leaf.Private.Seqno)\n\trequire.Equal(t, team.chain().GetLatestLinkID(), leaf.Private.LinkID.Export())\n\t// leaf.Private.SigID not checked\n\trequire.Nil(t, leaf.Public, \"team public leaf\")\n}", "func (s *Storage) Create(sha256Hash string, r io.Reader) (alreadyExists bool, err error) {\n\tblobRef := hashName(sha256Hash)\n\n\t// First try to increment the file's reference count.\n\terr = s.incRefCount(blobRef)\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif err != mgo.ErrNotFound {\n\t\treturn false, err\n\t}\n\tf, err := s.fs.Create(blobRef)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tf.SetMeta(refCountMeta{RefCount: 1})\n\tf.SetName(blobRef)\n\tif err := copyAndCheckHash(f, r, sha256Hash); err != nil {\n\t\t// Remove any chunks that were written while we were checking the hash.\n\t\tf.Abort()\n\t\tif closeErr := f.Close(); closeErr != nil {\n\t\t\t// TODO add mgo.ErrAborted so that we can avoid a string error check.\n\t\t\tif closeErr.Error() != \"write aborted\" {\n\t\t\t\tlog.Printf(\"cannot clean up after hash-mismatch file write: %v\", closeErr)\n\t\t\t}\n\t\t}\n\t\treturn false, err\n\t}\n\n\terr = f.Close()\n\tif err == nil {\n\t\treturn false, nil\n\t}\n\tif !mgo.IsDup(err) {\n\t\treturn false, err\n\t}\n\t// We cannot close the file because of a clashing index,\n\t// which means someone else has created the blob first,\n\t// so all we need to do is increment the ref count.\n\terr = s.incRefCount(blobRef)\n\tif err == nil {\n\t\t// Although technically, the content already exists,\n\t\t// we have already read the content from the reader,\n\t\t// so report alreadyExists=false.\n\t\treturn false, nil\n\t}\n\tif err != mgo.ErrNotFound {\n\t\treturn false, fmt.Errorf(\"cannot increment blob ref count: %v\", err)\n\t}\n\t// Unfortunately the other party has deleted the blob\n\t// in between Close and incRefCount.\n\t// The chunks we have written have already been\n\t// deleted at this point, so there's nothing we\n\t// can do except return an error. This situation\n\t// should be vanishingly unlikely in practice as\n\t// it relies on\n\t// a) two simultaneous initial uploads of the same blob.\n\t// b) one upload being removed immediately after upload.\n\t// c) the removal happening in the exact window between\n\t// f.Close and s.incRefCount.\n\treturn false, fmt.Errorf(\"duplicate blob removed at an inopportune moment\")\n}", "func NewBlob(fern *Fern, data *geo.Map, loc *geo.Point,\n\tbaseColor float64, accentColor float64) *Blob {\n\treturn &Blob{\n\t\tpriority: 1,\n\t\tdeadline: time.Now().Add(time.Hour * 8000),\n\t\tstart: time.Now(),\n\t\tfern: fern,\n\t\tdata: data,\n\t\tloc: loc,\n\n\t\tbaseColor: baseColor,\n\t\taccentColor: accentColor,\n\t}\n}", "func TmMerkleHash(chunks []Chunk) Digest { panic(\"\") }", "func BuildBlob(b *Blob) []byte {\n\tbu := flatbuffers.NewBuilder(128)\n\n\tputTid := func(tid *core.TractID) flatbuffers.UOffsetT {\n\t\tif tid == nil {\n\t\t\treturn 0 // default value, will make flatbuffers not add field\n\t\t}\n\t\treturn PutTractID(bu, *tid)\n\t}\n\n\tputTract := func(t *Tract) flatbuffers.UOffsetT {\n\t\thosts012, hosts3p := TractFSetupHosts(bu, t.Hosts)\n\t\tTractFStart(bu)\n\t\tTractFAddHosts012(bu, hosts012)\n\t\tTractFAddHosts3p(bu, hosts3p)\n\t\tTractFAddVersion(bu, uint32(t.Version))\n\t\tTractFAddRs63Chunk(bu, putTid(t.Rs63Chunk))\n\t\tTractFAddRs83Chunk(bu, putTid(t.Rs83Chunk))\n\t\tTractFAddRs103Chunk(bu, putTid(t.Rs103Chunk))\n\t\tTractFAddRs125Chunk(bu, putTid(t.Rs125Chunk))\n\t\treturn TractFEnd(bu)\n\t}\n\n\tputTracts := func(tracts []*Tract) flatbuffers.UOffsetT {\n\t\ttLen := len(tracts)\n\t\tif tLen == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\ttOffs := make([]flatbuffers.UOffsetT, tLen)\n\t\tfor i := tLen - 1; i >= 0; i-- {\n\t\t\ttOffs[tLen-i-1] = putTract(tracts[i])\n\t\t}\n\n\t\tBlobFStartTractsVector(bu, tLen)\n\t\tfor _, off := range tOffs {\n\t\t\tbu.PrependUOffsetT(off)\n\t\t}\n\t\treturn bu.EndVector(tLen)\n\t}\n\n\ttVec := putTracts(b.Tracts)\n\n\tBlobFStart(bu)\n\tBlobFAddPackedMeta(bu, PackMeta(b.Storage, b.Hint, int(b.Repl)))\n\tBlobFAddTracts(bu, tVec)\n\tBlobFAddDeleted(bu, b.Deleted)\n\tBlobFAddMtime(bu, b.Mtime)\n\tBlobFAddAtime(bu, b.Atime)\n\tBlobFAddExpires(bu, b.Expires)\n\tbu.Finish(BlobFEnd(bu))\n\treturn bu.FinishedBytes()\n}", "func (r *Repository) Blob(h plumbing.Hash) (*Blob, error) {\n\tblob, err := r.Object(plumbing.BlobObject, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn blob.(*Blob), nil\n}", "func createInternalMerkleNode(left, right *MerkleNode) *MerkleNode {\n\tnode := new(MerkleNode)\n\tnode.left, node.right = left, right\n\tnode.hash = node.calcNodeHash()\n\n\treturn node\n}", "func (is *ImageStoreLocal) GetBlob(repo string, digest godigest.Digest, mediaType string,\n) (io.ReadCloser, int64, error) {\n\tvar lockLatency time.Time\n\n\tif err := digest.Validate(); err != nil {\n\t\treturn nil, -1, err\n\t}\n\n\tblobPath := is.BlobPath(repo, digest)\n\n\tis.RLock(&lockLatency)\n\tdefer is.RUnlock(&lockLatency)\n\n\tbinfo, err := os.Stat(blobPath)\n\tif err != nil {\n\t\tis.log.Debug().Err(err).Str(\"blob\", blobPath).Msg(\"failed to stat blob\")\n\n\t\treturn nil, -1, zerr.ErrBlobNotFound\n\t}\n\n\tblobReadCloser, err := os.Open(blobPath)\n\tif err != nil {\n\t\tis.log.Debug().Err(err).Str(\"blob\", blobPath).Msg(\"failed to open blob\")\n\n\t\treturn nil, -1, err\n\t}\n\n\t// The caller function is responsible for calling Close()\n\treturn blobReadCloser, binfo.Size(), nil\n}", "func (suite *DigestTreeTestSuite) TestDigestTree() {\n\tt := suite.T()\n\n\tfor n := uint(1); n <= MaxTestSize; n++ {\n\t\tleaves := suite.randomDigests(n)\n\n\t\trootDigest, trees, err := NewDigestTree(leaves)\n\t\t_, _, _ = rootDigest, trees, err\n\n\t\tif !assert.Nil(t, err) {\n\t\t\tbreak\n\t\t}\n\n\t\tok := assert.Equal(t, int(n), len(trees))\n\t\tok = ok && assert.Equal(t, sha512.Size384, len(rootDigest))\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i, tree := range trees {\n\t\t\trecomputedRootDigest := tree.RootDigest()\n\t\t\tok = ok && assert.Equal(t, rootDigest, recomputedRootDigest, fmt.Sprintf(\"path %v produced incorrect root digest\", i))\n\t\t}\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (h HTTPHandler) HandleMerklePath(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\t// find the index to operate on\n\tvars := mux.Vars(r)\n\tblockID, err := hex.DecodeString(vars[\"blockId\"])\n\ttxID, err := hex.DecodeString(vars[\"txId\"])\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"invalid block transaction ID\\\"}\", 400)\n\t\treturn\n\t}\n\n\tblockchainPeer, err := getBlockchainById(h.bf, vars[\"blockchainId\"])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\tif blockchainPeer == nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"blockchain doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tvar block *blockchain.Block\n\n\terr = blockchainPeer.Db.View(func(dbtx *bolt.Tx) error {\n\t\tb := dbtx.Bucket([]byte(blockchain.BlocksBucket))\n\n\t\tif b == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleMerklePath\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Warn(\"block bucket doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\n\t\tencodedBlock := b.Get(blockID)\n\n\t\tif encodedBlock == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleMerklePath\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Error(\"block doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\t\tblock = blockchain.DeserializeBlock(encodedBlock)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"block doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tblockchainPeer.Db.View(func(dbtx *bolt.Tx) error {\n\t\t// Assume bucket exists and has keys\n\t\tc := dbtx.Bucket([]byte(blockchain.TransactionsBucket)).Cursor()\n\n\t\tprefix := block.Hash\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tblock.Transactions = append(block.Transactions, blockchain.DeserializeTransaction(v))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tverificationPath := block.GetMerkleTree().GetVerificationPath(txID)\n\tif verificationPath == nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"couldn't create the merkle tree for this transation\\\"}\", 400)\n\t\treturn\n\t}\n\n\tverificationPathString := make(map[int]string)\n\tfor index, hash := range verificationPath {\n\t\tverificationPathString[index] = fmt.Sprintf(\"%x\", hash)\n\t}\n\n\trv := struct {\n\t\tStatus string `json:\"status\"`\n\t\tMerklePath map[int]string `json:\"verificationPath\"`\n\t}{\n\t\tStatus: \"ok\",\n\t\tMerklePath: verificationPathString,\n\t}\n\n\tmustEncode(w, rv)\n}", "func newSHA256() hash.Hash { return sha256.New() }", "func NewFileReader(fetcher blobref.SeekFetcher, fileBlobRef *blobref.BlobRef) (*FileReader, error) {\n\t// TODO(bradfitz): make this take a blobref.FetcherAt instead?\n\t// TODO(bradfitz): rename this into bytes reader? but for now it's still\n\t// named FileReader, but can also read a \"bytes\" schema.\n\tif fileBlobRef == nil {\n\t\treturn nil, errors.New(\"schema/filereader: NewFileReader blobref was nil\")\n\t}\n\trsc, _, err := fetcher.Fetch(fileBlobRef)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"schema/filereader: fetching file schema blob: %v\", err)\n\t}\n\tdefer rsc.Close()\n\tss := new(Superset)\n\tif err = json.NewDecoder(rsc).Decode(ss); err != nil {\n\t\treturn nil, fmt.Errorf(\"schema/filereader: decoding file schema blob: %v\", err)\n\t}\n\tif ss.Type != \"file\" && ss.Type != \"bytes\" {\n\t\treturn nil, fmt.Errorf(\"schema/filereader: expected \\\"file\\\" or \\\"bytes\\\" schema blob, got %q\", ss.Type)\n\t}\n\tfr, err := ss.NewFileReader(fetcher)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"schema/filereader: creating FileReader for %s: %v\", fileBlobRef, err)\n\t}\n\treturn fr, nil\n}", "func verifyBlock(tree io.ReadSeeker, layout Layout, dataBlock []byte, blockIndex int64, expectedRoot []byte) error {\n\tif len(dataBlock) != int(layout.blockSize) {\n\t\treturn fmt.Errorf(\"incorrect block size\")\n\t}\n\n\texpectedDigest := make([]byte, layout.digestSize)\n\ttreeBlock := make([]byte, layout.blockSize)\n\tvar digest []byte\n\tfor level := 0; level < layout.numLevels(); level++ {\n\t\t// Calculate hash.\n\t\tif level == 0 {\n\t\t\tdigestArray := sha256.Sum256(dataBlock)\n\t\t\tdigest = digestArray[:]\n\t\t} else {\n\t\t\t// Read a block in previous level that contains the\n\t\t\t// hash we just generated, and generate a next level\n\t\t\t// hash from it.\n\t\t\tif _, err := tree.Seek(layout.blockOffset(level-1, blockIndex), io.SeekStart); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := tree.Read(treeBlock); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdigestArray := sha256.Sum256(treeBlock)\n\t\t\tdigest = digestArray[:]\n\t\t}\n\n\t\t// Move to stored hash for the current block, read the digest\n\t\t// and store in expectedDigest.\n\t\tif _, err := tree.Seek(layout.digestOffset(level, blockIndex), io.SeekStart); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := tree.Read(expectedDigest); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !bytes.Equal(digest, expectedDigest) {\n\t\t\treturn fmt.Errorf(\"Verification failed\")\n\t\t}\n\n\t\t// If this is the root layer, no need to generate next level\n\t\t// hash.\n\t\tif level == layout.rootLevel() {\n\t\t\tbreak\n\t\t}\n\t\tblockIndex = blockIndex / layout.hashesPerBlock()\n\t}\n\n\t// Verification for the tree succeeded. Now compare the root hash in the\n\t// tree with expectedRoot.\n\tif !bytes.Equal(digest[:], expectedRoot) {\n\t\treturn fmt.Errorf(\"Verification failed\")\n\t}\n\treturn nil\n}", "func NewMerkleNode(left, right *MerkleNode, data []byte) *MerkleNode {\n\tmNode := MerkleNode{}\n\n\tif left == nil && right == nil {\n\t\thash := sha256.Sum256(data)\n\t\tmNode.Data = hash[:]\n\t} else {\n\t\t// get data from left and right node.\n\t\tprevHashes := append(left.Data, right.Data...)\n\t\thash := sha256.Sum256(prevHashes)\n\t\tmNode.Data = hash[:]\n\t}\n\n\tmNode.Left = left\n\tmNode.Right = right\n\n\treturn &mNode\n}", "func (sto *unionStorage) ReceiveBlob(ctx context.Context, br blob.Ref, src io.Reader) (sb blob.SizedRef, err error) {\n\treturn blob.SizedRef{}, blobserver.ErrReadonly\n}", "func (i *DataIndex) getBlob(hash string, fpath string) error {\n\n\t// disallow empty paths\n\tif len(fpath) == 0 {\n\t\treturn fmt.Errorf(\"get blob %.7s - error: no path supplied\", hash)\n\t}\n\n\tfpath = path.Clean(fpath)\n\n\tpErr(\"get blob %.7s %s\\n\", hash, fpath)\n\tw, err := createFile(fpath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\treturn i.copyBlob(hash, w)\n}", "func ReadTree(c *Client, opt ReadTreeOptions, tree Treeish) (*Index, error) {\n\tidx, err := c.GitDir.ReadIndex()\n\tif err != nil {\n\t\tidx = NewIndex()\n\t}\n\torigMap := idx.GetMap()\n\n\tresetremovals, err := checkReadtreePrereqs(c, opt, idx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Convert to a new map before doing anything, so that checkMergeAndUpdate\n\t// can compare the original update after we reset.\n\tif opt.Empty {\n\t\tidx.NumberIndexEntries = 0\n\t\tidx.Objects = make([]*IndexEntry, 0)\n\t\tif err := checkMergeAndUpdate(c, opt, origMap, idx, resetremovals); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn idx, readtreeSaveIndex(c, opt, idx)\n\t}\n\tnewidx := NewIndex()\n\tif err := newidx.ResetIndex(c, tree); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, entry := range newidx.Objects {\n\t\tif opt.Prefix != \"\" {\n\t\t\t// Add it to the original index with the prefix\n\t\t\tentry.PathName = IndexPath(opt.Prefix) + entry.PathName\n\t\t\tif err := idx.AddStage(c, entry.PathName, entry.Mode, entry.Sha1, Stage0, entry.Fsize, entry.Mtime, UpdateIndexOptions{Add: true}); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tif opt.Merge {\n\t\t\tif oldentry, ok := origMap[entry.PathName]; ok {\n\t\t\t\tnewsha, _, err := HashFile(\"blob\", string(entry.PathName))\n\t\t\t\tif err != nil && newsha == entry.Sha1 {\n\t\t\t\t\tentry.Ctime, entry.Ctimenano = oldentry.Ctime, oldentry.Ctimenano\n\t\t\t\t\tentry.Mtime = oldentry.Mtime\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Prefix == \"\" {\n\t\tidx = newidx\n\t}\n\n\tif err := checkMergeAndUpdate(c, opt, origMap, idx, resetremovals); err != nil {\n\t\treturn nil, err\n\t}\n\treturn idx, readtreeSaveIndex(c, opt, idx)\n}", "func NewReader(buffer []byte) *Reader {\n\tvar r = &Reader{}\n\n\tr.buffer = buffer\n\tr.index = 0\n\n\tr.MagicKey = r.ReadUint16()\n\tr.Size = r.ReadUint16()\n\tr.CheckSum = r.ReadUint32()\n\tr.Type = r.ReadUint16()\n\n\treturn r\n}", "func (d *swiftDriver) ReadBlob(account keppel.Account, storageID string) (io.ReadCloser, uint64, error) {\n\tc, _, err := d.getBackendConnection(account)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\to := blobObject(c, storageID)\n\thdr, err := o.Headers()\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treader, err := o.Download(nil).AsReadCloser()\n\treturn reader, hdr.SizeBytes().Get(), err\n}", "func NewMerkleTree(data [][]byte) *MerkleTree {\r\n\tvar node = MerkleNode{nil,nil,data[0]}\r\n\tvar mTree = MerkleTree{&node}\r\n\r\n\treturn &mTree\r\n}", "func NewBlobCache() *BlobCache {\n\treturn &BlobCache{LRU: lru.New[string, []byte](0)}\n}", "func (sr *immutableRef) computeBlobChain(ctx context.Context, createIfNeeded bool, compressionType compression.Type, s session.Group) error {\n\tif _, ok := leases.FromContext(ctx); !ok {\n\t\treturn errors.Errorf(\"missing lease requirement for computeBlobChain\")\n\t}\n\n\tif err := sr.Finalize(ctx, true); err != nil {\n\t\treturn err\n\t}\n\n\tif isTypeWindows(sr) {\n\t\tctx = winlayers.UseWindowsLayerMode(ctx)\n\t}\n\n\treturn computeBlobChain(ctx, sr, createIfNeeded, compressionType, s)\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func RebuildMerkleAgent(plain []byte, secret []byte) *MerkleAgent{\n\tagent := &MerkleAgent{}\n\tseed := make([]byte, config.Size)\n\tagent.keyItr = wots.NewKeyIterator(seed)\n\tagent.keyItr.Init(secret)\n\tagent.H = binary.LittleEndian.Uint32(plain[0:4])\n\thashSize := binary.LittleEndian.Uint32(plain[4:8])\n\troot := plain[8:8 + hashSize]\n\tagent.root = root\n\toffset := 8 + hashSize\n\tagent.auth = make([][]byte, agent.H)\n\tfor i := 0; i < int(agent.H); i++{\n\t\tagent.auth[i] = plain[offset:offset+hashSize]\n\t\toffset += hashSize\n\t}\n\tagent.treeHashStacks = make([]*TreeHashStack, agent.H)\n\tfor i := 0; i < int(agent.H); i++ {\n\t\tstackSize := binary.LittleEndian.Uint32(plain[offset:offset+4])\n\t\telementSize := binary.LittleEndian.Uint32(plain[offset+4:offset+8])\n\t\tstackBytes := plain[offset: offset+20+stackSize*elementSize]\n\t\tagent.treeHashStacks[i] = RebuildTreeHashStack(stackBytes)\n\t\toffset += 20+stackSize*elementSize\n\t}\n\tagent.nodeHouse = make([][]byte, 1 << agent.H)\n\tfor i := 0; i < (1<<agent.H); i++{\n\t\tagent.nodeHouse[i] = plain[offset:offset+hashSize]\n\t\toffset += hashSize\n\t}\n\treturn agent\n}", "func (rc *RegClient) BlobGet(ctx context.Context, r ref.Ref, d types.Descriptor) (blob.Reader, error) {\n\tdata, err := d.GetData()\n\tif err == nil {\n\t\treturn blob.NewReader(blob.WithDesc(d), blob.WithRef(r), blob.WithReader(bytes.NewReader(data))), nil\n\t}\n\tschemeAPI, err := rc.schemeGet(r.Scheme)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn schemeAPI.BlobGet(ctx, r, d)\n}", "func NewBlob(ctx *pulumi.Context,\n\tname string, args *BlobArgs, opts ...pulumi.ResourceOption) (*Blob, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.AccountName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'AccountName'\")\n\t}\n\tif args.ContainerName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ContainerName'\")\n\t}\n\tif args.ResourceGroupName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ResourceGroupName'\")\n\t}\n\tif args.Type == nil {\n\t\targs.Type = BlobType(\"Block\")\n\t}\n\tvar resource Blob\n\terr := ctx.RegisterResource(\"azure-native:storage:Blob\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (is *ImageStoreLocal) NewBlobUpload(repo string) (string, error) {\n\tif err := is.InitRepo(repo); err != nil {\n\t\tis.log.Error().Err(err).Msg(\"error initializing repo\")\n\n\t\treturn \"\", err\n\t}\n\n\tuuid, err := guuid.NewV4()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tuid := uuid.String()\n\n\tblobUploadPath := is.BlobUploadPath(repo, uid)\n\n\tfile, err := os.OpenFile(blobUploadPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, storageConstants.DefaultFilePerms)\n\tif err != nil {\n\t\treturn \"\", zerr.ErrRepoNotFound\n\t}\n\n\tdefer file.Close()\n\n\treturn uid, nil\n}", "func (c *ContainerClient) NewAppendBlobClient(blobName string) (*AppendBlobClient, error) {\n\tblobURL := appendToURLPath(c.URL(), blobName)\n\n\treturn &AppendBlobClient{\n\t\tBlobClient: BlobClient{\n\t\t\tclient: newBlobClient(blobURL, c.client.pl),\n\t\t\tsharedKey: c.sharedKey,\n\t\t},\n\t\tclient: newAppendBlobClient(blobURL, c.client.pl),\n\t}, nil\n}", "func createLeafNode(data fmt.Stringer) *MerkleNode {\n\tnode := new(MerkleNode)\n\tnode.data = data\n\tnode.hash = node.calcNodeHash()\n\n\treturn node\n}", "func TestNew(hash string, size int64) *repb.Digest {\n\treturn mustNew(padHashSHA256(hash), size)\n}", "func (is *ObjectStorage) DeleteBlob(repo string, digest godigest.Digest) error {\n\tvar lockLatency time.Time\n\n\tif err := digest.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tblobPath := is.BlobPath(repo, digest)\n\n\tis.Lock(&lockLatency)\n\tdefer is.Unlock(&lockLatency)\n\n\t_, err := is.store.Stat(context.Background(), blobPath)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"blob\", blobPath).Msg(\"failed to stat blob\")\n\n\t\treturn zerr.ErrBlobNotFound\n\t}\n\n\t// first check if this blob is not currently in use\n\tif ok, _ := common.IsBlobReferenced(is, repo, digest, is.log); ok {\n\t\treturn zerr.ErrBlobReferenced\n\t}\n\n\tif fmt.Sprintf(\"%v\", is.cache) != fmt.Sprintf(\"%v\", nil) {\n\t\tdstRecord, err := is.cache.GetBlob(digest)\n\t\tif err != nil && !errors.Is(err, zerr.ErrCacheMiss) {\n\t\t\tis.log.Error().Err(err).Str(\"blobPath\", dstRecord).Msg(\"dedupe: unable to lookup blob record\")\n\n\t\t\treturn err\n\t\t}\n\n\t\t// remove cache entry and move blob contents to the next candidate if there is any\n\t\tif ok := is.cache.HasBlob(digest, blobPath); ok {\n\t\t\tif err := is.cache.DeleteBlob(digest, blobPath); err != nil {\n\t\t\t\tis.log.Error().Err(err).Str(\"digest\", digest.String()).Str(\"blobPath\", blobPath).\n\t\t\t\t\tMsg(\"unable to remove blob path from cache\")\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// if the deleted blob is one with content\n\t\tif dstRecord == blobPath {\n\t\t\t// get next candidate\n\t\t\tdstRecord, err := is.cache.GetBlob(digest)\n\t\t\tif err != nil && !errors.Is(err, zerr.ErrCacheMiss) {\n\t\t\t\tis.log.Error().Err(err).Str(\"blobPath\", dstRecord).Msg(\"dedupe: unable to lookup blob record\")\n\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// if we have a new candidate move the blob content to it\n\t\t\tif dstRecord != \"\" {\n\t\t\t\tif err := is.store.Move(context.Background(), blobPath, dstRecord); err != nil {\n\t\t\t\t\tis.log.Error().Err(err).Str(\"blobPath\", blobPath).Msg(\"unable to remove blob path\")\n\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := is.store.Delete(context.Background(), blobPath); err != nil {\n\t\tis.log.Error().Err(err).Str(\"blobPath\", blobPath).Msg(\"unable to remove blob path\")\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *TreeStorage) Read(ctx context.Context, ids []compact.NodeID) ([][]byte, error) {\n\tkeys := make([]spanner.KeySet, 0, len(ids))\n\tfor _, id := range ids {\n\t\tkeys = append(keys, spanner.Key{t.id, t.opts.shardID(id), packNodeID(id)})\n\t}\n\tkeySet := spanner.KeySets(keys...)\n\thashes := make([][]byte, 0, len(ids))\n\n\titer := t.c.Single().Read(ctx, \"TreeNodes\", keySet, []string{\"NodeHash\"})\n\tif err := iter.Do(func(r *spanner.Row) error {\n\t\tvar hash []byte\n\t\tif err := r.Column(0, &hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\thashes = append(hashes, hash)\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn hashes, nil\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\tvar defaultHashStrategy = \"sha256\"\n\tt := &MerkleTree{\n\t\tHashStrategy: defaultHashStrategy,\n\t}\n\troot, leafs, err := buildWithContent(cs, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Root = root\n\tt.Leafs = leafs\n\tt.MerkleRoot = root.Hash\n\treturn t, nil\n}", "func NewMerkleTree(data [][]byte) *MerkleTree {\n\treturn &MerkleTree{\n\t\tData: data,\n\t\tSteps: CalculateSteps(data),\n\t}\n}", "func newCache(fs *FS, bs *blobstore.BlobStore, path string) (*cache, error) {\n\tblobsCache, err := bcache.New(path, \"blobs.cache\", (5*1024)<<20) // 5GB on-disk LRU cache TODO(tsileo): make it configurable\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cache{\n\t\tfs: fs,\n\t\tbs: bs,\n\t\tblobsCache: blobsCache,\n\t\tremoteRefs: map[string]string{},\n\t}, nil\n}", "func New(data []byte) []byte {\n\tresult := sha256.Sum256(data)\n\treturn result[:]\n}", "func NewBatchedStoreBlobAccess(blobAccess blobstore.BlobAccess, blobKeyFormat digest.KeyFormat, batchSize int, putSemaphore *semaphore.Weighted) (blobstore.BlobAccess, func(ctx context.Context) error) {\n\tba := &batchedStoreBlobAccess{\n\t\tBlobAccess: blobAccess,\n\t\tblobKeyFormat: blobKeyFormat,\n\t\tbatchSize: batchSize,\n\t\tpendingPutOperations: map[string]pendingPutOperation{},\n\t\tputSemaphore: putSemaphore,\n\t}\n\treturn ba, func(ctx context.Context) error {\n\t\tba.lock.Lock()\n\t\tdefer ba.lock.Unlock()\n\n\t\t// Flush last batch of blobs. Return any errors that occurred.\n\t\tba.flushLocked(ctx)\n\t\terr := ba.flushError\n\t\tba.flushError = nil\n\t\treturn err\n\t}\n}", "func (m *MerkleTree) Get(lookupIndex []byte) *AuthenticationPath {\n\tlookupIndexBits := utils.ToBits(lookupIndex)\n\tdepth := 0\n\tvar nodePointer merkleNode\n\tnodePointer = m.root\n\n\tauthPath := &AuthenticationPath{\n\t\tTreeNonce: m.nonce,\n\t\tLookupIndex: lookupIndex,\n\t}\n\n\tfor {\n\t\tif _, ok := nodePointer.(*userLeafNode); ok {\n\t\t\t// reached to a leaf node\n\t\t\tbreak\n\t\t}\n\t\tif _, ok := nodePointer.(*emptyNode); ok {\n\t\t\t// reached to an empty branch\n\t\t\tbreak\n\t\t}\n\t\tdirection := lookupIndexBits[depth]\n\t\tvar hashArr [crypto.HashSizeByte]byte\n\t\tif direction {\n\t\t\tcopy(hashArr[:], nodePointer.(*interiorNode).leftHash)\n\t\t\tnodePointer = nodePointer.(*interiorNode).rightChild\n\t\t} else {\n\t\t\tcopy(hashArr[:], nodePointer.(*interiorNode).rightHash)\n\t\t\tnodePointer = nodePointer.(*interiorNode).leftChild\n\t\t}\n\t\tauthPath.PrunedTree = append(authPath.PrunedTree, hashArr)\n\t\tdepth++\n\t}\n\n\tif nodePointer == nil {\n\t\tpanic(ErrInvalidTree)\n\t}\n\tswitch nodePointer.(type) {\n\tcase *userLeafNode:\n\t\tpNode := nodePointer.(*userLeafNode)\n\t\tauthPath.Leaf = &ProofNode{\n\t\t\tLevel: pNode.level,\n\t\t\tIndex: pNode.index,\n\t\t\tValue: pNode.value,\n\t\t\tIsEmpty: false,\n\t\t\tCommitment: &crypto.Commit{\n\t\t\t\tSalt: pNode.commitment.Salt,\n\t\t\t\tValue: pNode.commitment.Value,\n\t\t\t},\n\t\t}\n\t\tif bytes.Equal(nodePointer.(*userLeafNode).index, lookupIndex) {\n\t\t\treturn authPath\n\t\t}\n\t\t// reached a different leaf with a matching prefix\n\t\t// return a auth path including the leaf node without salt & value\n\t\tauthPath.Leaf.Value = nil\n\t\tauthPath.Leaf.Commitment.Salt = nil\n\t\treturn authPath\n\tcase *emptyNode:\n\t\tpNode := nodePointer.(*emptyNode)\n\t\tauthPath.Leaf = &ProofNode{\n\t\t\tLevel: pNode.level,\n\t\t\tIndex: pNode.index,\n\t\t\tValue: nil,\n\t\t\tIsEmpty: true,\n\t\t\tCommitment: nil,\n\t\t}\n\t\treturn authPath\n\t}\n\tpanic(ErrInvalidTree)\n}", "func WithBlobDigest(ctx context.Context, digest string) context.Context {\n\tif ctx == nil {\n\t\tctx = context.TODO()\n\t}\n\treturn context.WithValue(ctx, BlobDigestKey, digest)\n}", "func BlobLTE(v []byte) predicate.User {\n\treturn predicate.User(sql.FieldLTE(FieldBlob, v))\n}", "func (es *externalSigner) NewDigest(sig *model.PdfSignature) (model.Hasher, error) {\n\treturn bytes.NewBuffer(nil), nil\n}", "func NewMerkleTreeMemory(evidencepath string, ch string) *MerkleTree {\n\tvar nodes []MerkleNode\n\tvar key []byte = []byte(ch)\n\tvar data [][]byte\n\n\tdata, _ = ReadAllFileIntoMemmory(evidencepath)\n\t//fmt.Println(\"len(data) is \", len(data))\n\t//var nodenum int64 =int64( len(data))\n\n\t//Building leaf nodes\n\tfor _, dataum := range data {\n\t\tnode := NewMerkleNode(nil, nil, key, dataum)\n\t\tnodes = append(nodes, *node)\n\t}\n\n\t//j represents the first element of a layer\n\tvar i int64 = 0\n\tvar j int64 = 0\n\tvar nSize int64\n\n\t//nSize represents the number of a certain layer, and each cycle is halved\n\tfor nSize = int64(len(data)); nSize > 1; nSize = (nSize + 1) / 2 {\n\t\tfor i = 0; i < nSize; i += 2 {\n\t\t\ti2 := min(i+1, nSize-1)\n\t\t\tnode := NewMerkleNode(&nodes[j+i], &nodes[j+i2], key, nil)\n\t\t\tnodes = append(nodes, *node)\n\t\t\t//WriteBlock(evidencecachpath, node.Data)\n\t\t}\n\t\t//j represents the first element of a layer\n\t\tj += nSize\n\t}\n\tmTree := MerkleTree{&(nodes[len(nodes)-1])}\n\tfmt.Println(\"len is \", len(nodes))\n\t//GetNodePath(&mTree,nodenum)\n\treturn &mTree\n}", "func newAppendBlobClient(url url.URL, p pipeline.Pipeline) appendBlobClient {\n\treturn appendBlobClient{newManagementClient(url, p)}\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\troot, leafs, err := buildWithContent(cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &MerkleTree{\n\t\tRoot: root,\n\t\tmerkleRoot: root.Hash,\n\t\tLeafs: leafs,\n\t}\n\treturn t, nil\n}", "func NewMerkleTree() (*MerkleTree, error) {\n\troot := newInteriorNode(nil, 0, []bool{})\n\tnonce, err := crypto.MakeRand()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := &MerkleTree{\n\t\tnonce: nonce,\n\t\troot: root,\n\t}\n\treturn m, nil\n}", "func uploadBlob(registry, name string) (string, error) {\n\tfile, err := makeLayer()\n\tif err != nil {\n\t\tfmt.Printf(\"makeLayer Error\\n\")\n\t\treturn \"\", err\n\t}\n\tdefer os.Remove(file.Name())\n\n\thasher := sha256.New()\n\tif _, err := io.Copy(hasher, file); err != nil {\n\t\treturn \"\", err\n\t}\n\tdigest := fmt.Sprintf(\"%x\", hasher.Sum(nil))\n\tfileLength, err := file.Seek(0, os.SEEK_CUR)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif _, err := file.Seek(0, os.SEEK_SET); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tuploadURL := fmt.Sprintf(\"%s/v2/%s/blobs/uploads/?digest=sha256:%s\", registry, name, digest)\n\treq, err := http.NewRequest(http.MethodPost, uploadURL, file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Close = true\n\treq.Header.Set(\"Content-Length\", fmt.Sprintf(\"%d\", fileLength))\n\treq.Header.Set(\"Content-Type\", \"application/octet-stream\")\n\tresp, err := http.DefaultClient.Do(req)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor resp.StatusCode == http.StatusAccepted {\n\t\tdefer resp.Body.Close()\n\t\t_, err := ioutil.ReadAll(resp.Body)\n\n\t\tfmt.Printf(\"Got `%s` even though we wanted one-stop upload, retrying\\n\", resp.Status)\n\t\t// The last upload closed the file; reopen it\n\t\tfile, err = os.Open(file.Name())\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tnewURL, err := url.Parse(resp.Header.Get(\"Location\"))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tquery := newURL.Query()\n\t\tquery.Add(\"digest\", \"sha256:\"+digest)\n\t\tnewURL.RawQuery = query.Encode()\n\t\tnewreq, err := http.NewRequest(http.MethodPut, newURL.String(), file)\n\t\t// The last argument is the request body to upload.\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tnewreq.Close = true\n\t\tnewreq.Header.Set(\"Content-Length\", fmt.Sprintf(\"%d\", fileLength))\n\t\tnewreq.Header.Set(\"Content-Type\", \"application/octet-stream\")\n\n\t\tnewresp, err := http.DefaultClient.Do(newreq)\n\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tresp = newresp\n\t}\n\n\tswitch resp.StatusCode {\n\tcase http.StatusCreated:\n\t\tbreak\n\tcase http.StatusAccepted:\n\t\tpanic(\"Got status accepted outside loop\")\n\tcase http.StatusBadRequest, http.StatusMethodNotAllowed, http.StatusForbidden, http.StatusNotFound:\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"Error uploading: %s: %s\", resp.Status, string(body))\n\tcase http.StatusUnauthorized:\n\t\treturn \"\", fmt.Errorf(\"Error uploading: unauthorized\")\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Error uploading: unknown status %s\", resp.Status)\n\t}\n\n\treturn digest, nil\n}", "func newLog(storage Storage) *RaftLog {\n\t// Your Code Here (2A).\n\thardState, _, err := storage.InitialState()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfirstIndex, err := storage.FirstIndex()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlastIndex, err := storage.LastIndex()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tentries, err := storage.Entries(firstIndex, lastIndex+1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsnapIndex := firstIndex - 1\n\tsnapTerm, err := storage.Term(snapIndex)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog := &RaftLog{\n\t\tstorage: storage,\n\t\tcommitted: hardState.Commit,\n\t\tapplied: snapIndex,\n\t\tstabled: lastIndex,\n\t\tentries: entries,\n\t\tpendingEntries: make([]pb.Entry, 0),\n\t\tsnapIndex: snapIndex,\n\t\tsnapTerm: snapTerm,\n\t}\n\treturn log\n}", "func NewBlobDatum(body *BlobDatum) *Datum {\n\treturn &Datum{\n\t\tVal: &Datum_Blob{\n\t\t\tBlob: body,\n\t\t},\n\t}\n}", "func CreateMigrationBlob(rw io.ReadWriter, srkAuth Digest, migrationAuth Digest, keyBlob []byte, migrationKeyBlob []byte) ([]byte, error) {\n\t// Run OSAP for the SRK, reading a random OddOSAP for our initial\n\t// command and getting back a secret and a handle.\n\tsharedSecret, osapr, err := newOSAPSession(rw, etSRK, khSRK, srkAuth[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer osapr.Close(rw)\n\tdefer zeroBytes(sharedSecret[:])\n\n\t// The createMigrationBlob command needs an OIAP session in addition to the\n\t// OSAP session.\n\toiapr, err := oiap(rw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer oiapr.Close(rw)\n\n\tencData := tpmutil.U32Bytes(keyBlob)\n\n\t// The digest for auth1 and auth2 for the createMigrationBlob command is\n\t// SHA1(ordCreateMigrationBlob || migrationScheme || migrationKeyBlob || encData)\n\tauthIn := []interface{}{ordCreateMigrationBlob, msRewrap, migrationKeyBlob, encData}\n\n\t// The first commandAuth uses the shared secret as an HMAC key.\n\tca1, err := newCommandAuth(osapr.AuthHandle, osapr.NonceEven, nil, sharedSecret[:], authIn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The second commandAuth is based on OIAP instead of OSAP and uses the\n\t// migration auth as the HMAC key.\n\tca2, err := newCommandAuth(oiapr.AuthHandle, oiapr.NonceEven, nil, migrationAuth[:], authIn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, outData, _, _, _, err := createMigrationBlob(rw, khSRK, msRewrap, migrationKeyBlob, encData, ca1, ca2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// For now, ignore the response authenticatino.\n\treturn outData, nil\n}", "func Verify(sig *Signature, hash []byte) (bool, error) {\n\tif sig.Mode == ModeEdDSA {\n\t\tif len(hash) != crypto.SHA512.Size() {\n\t\t\tmsg := fmt.Sprintf(\"invalid hash length. wanted: %d, got: %d\", crypto.SHA512.Size(), len(hash))\n\t\t\treturn false, errors.New(msg)\n\t\t}\n\n\t\teddsaSig := sig.Signature\n\t\tif len(eddsaSig) != SignatureLength {\n\t\t\tmsg := fmt.Sprintf(\"invalid signature length. wanted: %d, got: %d\", SignatureLength, len(eddsaSig))\n\t\t\treturn false, errors.New(msg)\n\t\t}\n\t\topts := ed25519.Options{\n\t\t\tHash: crypto.SHA512,\n\t\t}\n\t\treturn ed25519.VerifyWithOptions(sig.Address, hash, eddsaSig, &opts), nil\n\t} else if sig.Mode == ModeBLS {\n\t\tif len(hash) != crypto.SHA3_256.Size() {\n\t\t\tmsg := fmt.Sprintf(\"invalid hash length. wanted: %d, got: %d\", crypto.SHA3_256.Size(), len(hash))\n\t\t\treturn false, errors.New(msg)\n\t\t}\n\n\t\tvar blsSig bls.Sign\n\t\tblsSig.Deserialize(sig.Signature)\n\t\tvar blsPub bls.PublicKey\n\t\tblsPub.Deserialize(sig.Address)\n\n\t\treturn blsSig.VerifyHash(&blsPub, hash), nil\n\t} else if sig.Mode == ModeMerkle {\n\t\t// calculate master\n\t\tcurrent := hash\n\t\tfor i := range sig.MerklePath {\n\t\t\th := sha512.New()\n\t\t\thash := sig.MerklePath[i]\n\t\t\tindex := sig.MerkleIndexes[i]\n\t\t\tvar msg []byte\n\t\t\tif index == false {\n\t\t\t\t// hash is left\n\t\t\t\tmsg = append(hash, current...)\n\t\t\t} else {\n\t\t\t\t// hash is right\n\t\t\t\tmsg = append(current, hash...)\n\t\t\t}\n\t\t\tif _, err := h.Write(msg); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tcurrent = h.Sum(nil)\n\t\t}\n\n\t\t// `current` should now be the merkle root.\n\n\t\t// use caching: find out whether we previously already checked that\n\t\t// signature is ok. for this, use hash(addr || merkle root || sig)\n\t\th := crypto.SHA256.New()\n\t\th.Write(sig.Address)\n\t\th.Write(current)\n\t\th.Write(sig.Signature)\n\t\tsigHash := h.Sum(nil)\n\t\tsigHashIndex := [32]byte{}\n\t\tcopy(sigHashIndex[:], sigHash[:])\n\n\t\t// lookup cache and return if cached\n\t\tif UseMerkleSignatureCaching {\n\t\t\tcachedValid, ok := merkleSigCache.Load(sigHashIndex)\n\t\t\tif ok && cachedValid == true {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t\t// there is no cache entry, or entry was false.\n\t\topts := ed25519.Options{\n\t\t\tHash: crypto.SHA512,\n\t\t}\n\t\tvalid := ed25519.VerifyWithOptions(sig.Address, current, sig.Signature, &opts)\n\t\tif valid {\n\t\t\tmerkleSigCache.Store(sigHashIndex, true)\n\t\t}\n\t\treturn valid, nil\n\t} else {\n\t\treturn false, errors.New(\"mode not supported\")\n\t}\n}", "func (s *AzureBlobStorage) Open(ctx context.Context, name string) (ExternalFileReader, error) {\n\tclient := s.containerClient.NewBlockBlobClient(s.withPrefix(name))\n\tresp, err := client.GetProperties(ctx, nil)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"Failed to get properties from the azure blob\")\n\t}\n\n\treturn &azblobObjectReader{\n\t\tblobClient: client,\n\n\t\tpos: 0,\n\t\ttotalSize: *resp.ContentLength,\n\n\t\tctx: ctx,\n\n\t\tcpkInfo: s.cpkInfo,\n\t}, nil\n}", "func CtrGetBlobInfo(blobHash string) (content.Info, error) {\n\tif err := verifyCtr(); err != nil {\n\t\treturn content.Info{}, fmt.Errorf(\"CtrReadBlob: exception while verifying ctrd client: %s\", err.Error())\n\t}\n\treturn contentStore.Info(ctrdCtx, digest.Digest(blobHash))\n}" ]
[ "0.58413476", "0.5624401", "0.5494648", "0.5427737", "0.5140033", "0.50221825", "0.49835172", "0.4974719", "0.49557987", "0.49510318", "0.4940078", "0.4915983", "0.49132773", "0.48539382", "0.48506436", "0.48390308", "0.48285547", "0.4827324", "0.4816197", "0.47794566", "0.47793582", "0.4768111", "0.47316992", "0.47041136", "0.46857607", "0.46732312", "0.46681532", "0.46611884", "0.4659656", "0.46534047", "0.46367702", "0.4615224", "0.4613698", "0.46086648", "0.46042052", "0.45963976", "0.45899022", "0.4586496", "0.4577417", "0.4535327", "0.4525224", "0.44816533", "0.44760898", "0.4471171", "0.44562766", "0.44538727", "0.44368827", "0.44324437", "0.4431547", "0.44275668", "0.44273448", "0.44124043", "0.44123003", "0.44057876", "0.43940634", "0.43912616", "0.43907118", "0.43885133", "0.438707", "0.43869072", "0.4378564", "0.43754607", "0.436635", "0.43658835", "0.43628967", "0.43549013", "0.43526927", "0.43525064", "0.43465215", "0.43461102", "0.4339094", "0.43356973", "0.4332917", "0.43006462", "0.42919943", "0.4291579", "0.42898086", "0.42866692", "0.42818907", "0.42752945", "0.4267692", "0.4254091", "0.4252879", "0.42466223", "0.4236187", "0.42354864", "0.42347214", "0.42238134", "0.42142767", "0.42047513", "0.4197739", "0.41904855", "0.41865906", "0.4183552", "0.41743788", "0.4166505", "0.41658938", "0.41577417", "0.41557097", "0.41506252" ]
0.75446844
0
Restart restarts the application
Перезапуск перезапускает приложение
func Restart() { log.Println("An error has occured, restarting the app") file, _ := osext.Executable() syscall.Exec(file, os.Args, os.Environ()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Restart(args ...string) {\n logger.Log(fmt.Sprintf(\"Restarting %v\\n\", process))\n Stop(args...)\n Start(args...)\n}", "func (r *Runner) Restart(application *config.Application) {\n\tif cmd, ok := r.cmds[application.Name]; ok {\n\t\tpgid, err := syscall.Getpgid(cmd.Process.Pid)\n\t\tif err == nil {\n\t\t\tsyscall.Kill(-pgid, 15)\n\t\t}\n\t}\n\n\tgo r.Run(application)\n}", "func (app *appContext) Restart() error {\n\tif TRAY {\n\t\tTRAYRESTART <- true\n\t} else {\n\t\tRESTART <- true\n\t}\n\treturn nil\n}", "func restart() {\n\tfmt.Println(\"Config change detected, restarting\")\n}", "func (s *Syncthing) Restart(ctx context.Context) error {\n\t_, err := s.APICall(ctx, \"rest/system/restart\", \"POST\", 200, nil, true, nil, false, 3)\n\treturn err\n}", "func (a API) Restart(cmd *None) (e error) {\n\tRPCHandlers[\"restart\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (pomo *Pomo) Restart() {\n\tpomo.SetDuration(DEFAULT_DURATION)\n}", "func (a *App) Restart(w io.Writer) error {\n\ta.Log(\"executing hook to restart\", \"tsuru\")\n\terr := a.preRestart(w)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = write(w, []byte(\"\\n ---> Restarting your app\\n\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = a.run(\"/var/lib/tsuru/hooks/restart\", w)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.posRestart(w)\n}", "func (c *Client) Restart() error {\n\tif _, err := c.httpPost(\"system/restart\", \"\"); err != nil {\n\t\treturn maskAny(err)\n\t}\n\treturn nil\n}", "func Restart() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tinternalPanicHandler.Done()\n\tinternalPanicHandler = NewHandler(internalPanicHandler.handle)\n}", "func (cg *CandlesGroup) restart() {\n\ttime.Sleep(5 * time.Second)\n\tif err := cg.wsClient.Exit(); err != nil {\n\t\tlog.Println(\"[BITFINEX] Error destroying connection: \", err)\n\t}\n\tcg.Start(cg.bus.outChannel)\n}", "func cmdRestart() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tcmdStop()\n\t\ttime.Sleep(1 * time.Second)\n\t\tcmdStart()\n\tdefault:\n\t\tcmdStart()\n\t}\n}", "func (i *Instance) restart(req *route.Request) route.Response {\n\tmsg.Info(\"Instance Restart: %s\", i.Name())\n\tif i.Destroyed() {\n\t\tmsg.Detail(\"Instance does not exist, skipping...\")\n\t\treturn route.OK\n\t}\n\tif resp := i.Derived().PreRestart(req); resp != route.OK {\n\t\treturn resp\n\t}\n\tif resp := i.Derived().Restart(req); resp != route.OK {\n\t\treturn resp\n\t}\n\tif resp := i.Derived().PostRestart(req); resp != route.OK {\n\t\treturn resp\n\t}\n\tmsg.Detail(\"Restarted: %s\", i.Id())\n\taaa.Accounting(\"Instance restarted: %s, %s\", i.Name(), i.Id())\n\treturn route.OK\n}", "func restartCons() {\n\tfor _, inst := range getInstances() {\n\t\tif inst.Running {\n\t\t\tgo startRecordedWebConsole(inst.Instance)\n\t\t}\n\t}\n}", "func (Tests) Restart(ctx context.Context) {\n\tmg.SerialCtxDeps(ctx,\n\t\tTests.Stop,\n\t\tTests.Start,\n\t)\n}", "func (q *CoreClient) Restart() (err error) {\n\t_, err = q.RequestWithoutData(http.MethodPost, \"/safeRestart\", nil, nil, 503)\n\treturn\n}", "func relaunch() (int, error) {\n\tcmd := exec.Command(os.Args[0], os.Args[1:]...)\n\tlogging.Debug(\"Running command: %s\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn 1, locale.WrapError(err, \"err_autoupdate_relaunch_start\",\n\t\t\t\"Could not start updated State Tool after auto-updating, please manually run your command again, if the problem persists please reinstall the State Tool.\")\n\t}\n\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn osutils.CmdExitCode(cmd), locale.WrapError(err, \"err_autoupdate_relaunch_wait\", \"Could not forward your command after auto-updating, please manually run your command again.\")\n\t}\n\n\treturn osutils.CmdExitCode(cmd), nil\n}", "func (m *Machine) Restart() error {\n\tm.State = driver.Running\n\tfmt.Printf(\"Restart %s: %s\\n\", m.Name, m.State)\n\treturn nil\n}", "func (q *CoreClient) Restart() (err error) {\n\tapi := fmt.Sprintf(\"%s/safeRestart\", q.URL)\n\tvar (\n\t\treq *http.Request\n\t\tresponse *http.Response\n\t)\n\n\treq, err = http.NewRequest(\"POST\", api, nil)\n\tif err == nil {\n\t\tq.AuthHandle(req)\n\t} else {\n\t\treturn\n\t}\n\n\tclient := q.GetClient()\n\tif response, err = client.Do(req); err == nil {\n\t\tcode := response.StatusCode\n\t\tvar data []byte\n\t\tdata, err = ioutil.ReadAll(response.Body)\n\t\tif code == 503 { // Jenkins could be behind of a proxy\n\t\t\tfmt.Println(\"Please wait while Jenkins is restarting\")\n\t\t} else if code != 200 || err != nil {\n\t\t\tlog.Fatalf(\"Error code: %d, response: %s, errror: %v\", code, string(data), err)\n\t\t} else {\n\t\t\tfmt.Println(\"restart successfully\")\n\t\t}\n\t} else {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (a *App) preRestart(w io.Writer) error {\n\tif err := a.loadHooks(); err != nil {\n\t\treturn err\n\t}\n\treturn a.runHook(w, a.hooks.PreRestart, \"pre-restart\")\n}", "func (c *KubeTestPlatform) Restart(name string) error {\n\t// To minic the restart behavior, scale to 0 and then scale to the original replicas.\n\tapp := c.AppResources.FindActiveResource(name)\n\tm := app.(*kube.AppManager)\n\toriginalReplicas := m.App().Replicas\n\n\tif err := c.Scale(name, 0); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.Scale(name, originalReplicas); err != nil {\n\t\treturn err\n\t}\n\n\tm.StreamContainerLogs()\n\n\treturn nil\n}", "func (h *Host) Restart() error {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\tcmd := exec.Command(h.cmd.Path, h.cmd.Args...)\n\thttp, https, err := h.setupCmd(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.httpTransfer.Close()\n\th.httpsTransfer.Close()\n\th.cmd = cmd\n\th.httpTransfer = http\n\th.httpsTransfer = https\n\treturn nil\n}", "func (d *daemon) Restart() {\n\td.Lock()\n\tdefer d.Unlock()\n\tif d.ex == nil {\n\t\tex, err := shell.NewExecutor(d.shell, d.conf.Command, d.indir)\n\t\tif err != nil {\n\t\t\td.log.Shout(\"Could not create executor: %s\", err)\n\t\t}\n\t\td.ex = ex\n\t\tgo d.Run()\n\t} else {\n\t\td.log.Notice(\">> sending signal %s\", d.conf.RestartSignal)\n\t\terr := d.ex.Signal(d.conf.RestartSignal)\n\t\tif err != nil {\n\t\t\td.log.Warn(\n\t\t\t\t\"failed to send %s signal to %s: %v\", d.conf.RestartSignal, d.conf.Command, err,\n\t\t\t)\n\t\t}\n\t}\n}", "func (Dev) Restart(ctx context.Context) {\n\tmg.SerialCtxDeps(ctx,\n\t\tDev.Stop,\n\t\tDev.Start,\n\t)\n}", "func RequestRestart() {\n\tRestart = true\n\tDebug(\"requesting restart\")\n\tRequest()\n}", "func Reload(appName string, ctx *Context) {\n\tpresent, process := FindDaemonProcess(ctx)\n\tif present {\n\t\tlog.Printf(\"sending SIGHUP to pid %v\", process.Pid)\n\t\tif err := sigSendHUP(process); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%v is stopped.\\n\", appName)\n\t}\n}", "func (m *Master) Restart(procSign string, out *StartRsp) error {\n\t// I. find & stop instance\n\t// II. stop instance\n\tif _, err := m.StopInstance(procSign, syscall.SIGINT); err != nil {\n\t\t// ignore \"pid not found\" error\n\t\tif err.Error() != \"no active pid found\" {\n\t\t\treturn err\n\t\t}\n\t}\n\t// III. start instance\n\treturn m.Start(procSign, out)\n}", "func (a *App) posRestart(w io.Writer) error {\n\tif err := a.loadHooks(); err != nil {\n\t\treturn err\n\t}\n\treturn a.runHook(w, a.hooks.PosRestart, \"pos-restart\")\n}", "func RestartApp(appName string) (bool, string) {\n\tout, err := exec.Command(\"dokku\", \"ps:restart\", appName).CombinedOutput()\n\tif err != nil {\n\t\tlog.ErrorLogger.Println(\"Can't restart app:\", err.Error(), string(out))\n\t\treturn false, string(out)\n\t}\n\treturn true, \"\"\n}", "func (master *ProcMaster) restart(proc ProcContainer) error {\n\terr := master.stop(proc)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn master.start(proc)\n}", "func (d *Driver) Restart() error {\n\td.Stop()\n\td.Start()\n\treturn nil\n}", "func (tg *TradesGroup) restart() {\n\ttime.Sleep(5 * time.Second)\n\tif err := tg.wsClient.Exit(); err != nil {\n\t\tlog.Println(\"[BITFINEX] Error destroying connection: \", err)\n\t}\n\ttg.Start(tg.bus.outChannel)\n}", "func RestartGame() {\n\t// Removes the current snake and food from the level.\n\tgs.RemoveEntity(gs.SnakeEntity)\n\tgs.RemoveEntity(gs.FoodEntity)\n\n\t// Generate a new snake and food.\n\tgs.SnakeEntity = NewSnake()\n\tgs.FoodEntity = NewFood()\n\n\t// Revert the score and fps to the standard.\n\tSetDiffiultyFPS()\n\tgs.Score = 0\n\n\t// Update the score and fps text.\n\tsp.ScoreText.SetText(fmt.Sprintf(\"Score: %d\", gs.Score))\n\tsp.SpeedText.SetText(fmt.Sprintf(\"Speed: %.0f\", gs.FPS))\n\n\t// Adds the snake and food back and sets them to the standard position.\n\tgs.AddEntity(gs.SnakeEntity)\n\tgs.AddEntity(gs.FoodEntity)\n\tsg.Screen().SetFps(gs.FPS)\n\tsg.Screen().SetLevel(gs)\n}", "func (proc *Proc) Restart() error {\n\tif proc.IsAlive() {\n\t\terr := proc.Stop()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn proc.Start()\n}", "func Restart(s Restartable) error {\n\treturn s.Restart()\n}", "func (proc_status *ProcStatus) IncrRestart() {\n\tproc_status.Restarts++\n}", "func (client *VirtualMachineScaleSetsClient) restart(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsBeginRestartOptions) (*http.Response, error) {\n\treq, err := client.restartCreateRequest(ctx, resourceGroupName, vmScaleSetName, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.pl.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {\n\t\treturn nil, client.restartHandleError(resp)\n\t}\n\treturn resp, nil\n}", "func (m Miner) Restart() error {\n\tclient, err := jsonrpc.Dial(\"tcp\", m.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\targs.psw = m.Password\n\treturn client.Call(methodRestartMiner, args, nil)\n}", "func (dp *DaemonPen) Restart() {\n\tdp.Lock()\n\tdefer dp.Unlock()\n\tif dp.daemons != nil {\n\t\tfor _, d := range dp.daemons {\n\t\t\td.Restart()\n\t\t}\n\t}\n}", "func (mg *Groups) Restart(force bool) error {\n\n\tif mg.group != nil && len(mg.group.ID) > 0 {\n\t\tif appClient := application.New(mg.client); appClient != nil {\n\n\t\t\tcallbackFunc := func(appID string) error {\n\n\t\t\t\tif err := appClient.Get(appID).Restart(force); err != nil {\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\treturn mg.traverseGroupsWithAppID(mg.group, callbackFunc)\n\t\t}\n\t\treturn fmt.Errorf(\"unnable to connect\")\n\t}\n\treturn errors.New(\"group cannot be null nor empty\")\n}", "func (_SweetToken *SweetTokenTransactor) Restart(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"restart\")\n}", "func (el *gameStruct) Restart() {\n\tel.SetLocation(el.start)\n}", "func (nm *NodeMonitor) Restart(arg string) {\n\tnm.mutex.Lock()\n\tdefer nm.mutex.Unlock()\n\tnm.arg = arg\n\n\tif nm.process == nil {\n\t\treturn\n\t}\n\tif err := nm.process.Kill(); err != nil {\n\t\tlog.WithError(err).WithField(\"pid\", nm.process.Pid).Error(\"process.Kill()\")\n\t}\n\tnm.process = nil\n}", "func (d *Driver) Restart() error {\n\terr := d.Stop()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn d.Start()\n}", "func (cr *ConflictResolver) Restart(baseCtx context.Context) {\n\tcr.startProcessing(baseCtx)\n}", "func (s *SystemService) Restart() error {\n\tif err := s.Stop(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.Start(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (inst *Instance) Restart(signal os.Signal) error {\n\tautoRestartHandle := inst.autoRestartHandle\n\t// acquire restart lock to make auto-restart work by force\n\t// it will be automatically released after tick()\n\tautoRestartHandle.forceRestart()\n\treturn inst.stop(signal)\n}", "func (room *RoomRecorder) actionRestart(msg synced.Msg) {\n\tif conn, ok := room.connectionCheck(msg); ok {\n\t\troom.Restart(conn)\n\t}\n}", "func (d *Driver) Restart() error {\n\tcs := d.client()\n\t_, err := cs.AsyncRequest(&egoscale.RebootVirtualMachine{\n\t\tID: d.ID,\n\t}, d.async)\n\n\treturn err\n}", "func (t *Ticker) Restart() {\n\tt.lastRestart = time.Now()\n\tif t.active {\n\t\tt.Stop()\n\t\tt.start()\n\t} else {\n\t\tt.start()\n\t}\n}", "func (inst *IndependentInstance) Restart(id string, manager *support.FlowManager) error {\n\tinst.id = id\n\tvar err error\n\tinst.flowDef, err = manager.GetFlow(inst.flowURI)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tif inst.flowDef == nil {\n\t\treturn errors.New(\"unable to resolve flow: \" + inst.flowURI)\n\t}\n\n\tinst.flowModel = getFlowModel(inst.flowDef)\n\tinst.master = inst\n\tinst.init(inst.Instance)\n\n\treturn nil\n}", "func restartWebServers(ctx context.Context, signal string, newExeFilePath ...string) error {\n\tserverProcessStatus.Set(adminActionRestarting)\n\tif runtime.GOOS == \"windows\" {\n\t\tif len(signal) > 0 {\n\t\t\t// Controlled by signal.\n\t\t\tforceCloseWebServers(ctx)\n\t\t\tif err := forkRestartProcess(ctx, newExeFilePath...); err != nil {\n\t\t\t\tintlog.Errorf(ctx, `%+v`, err)\n\t\t\t}\n\t\t} else {\n\t\t\t// Controlled by web page.\n\t\t\t// It should ensure the response wrote to client and then close all servers gracefully.\n\t\t\tgtimer.SetTimeout(ctx, time.Second, func(ctx context.Context) {\n\t\t\t\tforceCloseWebServers(ctx)\n\t\t\t\tif err := forkRestartProcess(ctx, newExeFilePath...); err != nil {\n\t\t\t\t\tintlog.Errorf(ctx, `%+v`, err)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t} else {\n\t\tif err := forkReloadProcess(ctx, newExeFilePath...); err != nil {\n\t\t\tglog.Printf(ctx, \"%d: server restarts failed\", gproc.Pid())\n\t\t\tserverProcessStatus.Set(adminActionNone)\n\t\t\treturn err\n\t\t} else {\n\t\t\tif len(signal) > 0 {\n\t\t\t\tglog.Printf(ctx, \"%d: server restarting by signal: %s\", gproc.Pid(), signal)\n\t\t\t} else {\n\t\t\t\tglog.Printf(ctx, \"%d: server restarting by web admin\", gproc.Pid())\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (f *Fetcher) Restart() {\n\tf.stop = make(chan struct{})\n\tgo f.Run()\n}", "func Restart(start, pwdn gpio.PinIO) {\n\tif err := pwdn.Out(gpio.Low); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttime.Sleep(500 * time.Millisecond)\n\n\tpwdn.Out(gpio.High)\n\n\tif err := start.Out(gpio.Low); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttime.Sleep(2 * time.Second)\n\n}", "func (s *Supervisor) Restart() (bool, error) {\n\t_, err := execCommand(s.name, []string{\"restart\", s.service})\n\treturn (err == nil), err\n}", "func (s *FluentdService) Restart(ctx context.Context, r *pb.FluentdRestartRequest) (*pb.FluentdRestartResponse, error) {\n\treturn &pb.FluentdRestartResponse{Status: pb.FluentdRestartResponse_RESTART_SUCCESS}, nil\n}", "func (a *adapter) coreRestarted(ctx context.Context, endPoint string) error {\n\tlogger.Errorw(ctx, \"core-restarted\", log.Fields{\"endpoint\": endPoint})\n\treturn nil\n}", "func (q *CoreClient) RestartDirectly() (err error) {\n\t_, err = q.RequestWithoutData(http.MethodPost, \"/restart\", nil, nil, 503)\n\treturn\n}", "func Restart(resource string, namespace string, args ...string) (err error) {\n\trestart := []string{\"rollout\", \"restart\", resource, \"-n\", namespace}\n\t_, err = kubectl(append(restart, args...)...)\n\treturn\n}", "func (srv *jsServer) Restart() {\n\tsrv.restart.Lock()\n\tdefer srv.restart.Unlock()\n\tsrv.Server = natsserver.RunServer(srv.myopts)\n}", "func (f *FakeInstance) Reboot(_ context.Context, _ string) error {\n\tpanic(\"implement me\")\n}", "func restart(listener net.Listener, errLogger *common.ErrorLogger) error {\n\targv0, err := exec.LookPath(os.Args[0])\n\tif nil != err {\n\t\treturn err\n\t}\n\twd, err := os.Getwd()\n\tif nil != err {\n\t\treturn err\n\t}\n\tv := reflect.ValueOf(listener).Elem().FieldByName(\"fd\").Elem()\n\tfd := uintptr(v.FieldByName(\"sysfd\").Int())\n\tallFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr},\n\t\tos.NewFile(fd, string(v.FieldByName(\"sysfile\").String())))\n\n\tp, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{\n\t\tDir: wd,\n\t\tEnv: append(os.Environ(), fmt.Sprintf(\"%s=%d\", FDKey, fd)),\n\t\tFiles: allFiles,\n\t})\n\tif nil != err {\n\t\treturn err\n\t}\n\terrLogger.Printf(\"spawned child %d\\n\", p.Pid)\n\treturn nil\n}", "func (adm *AdminClient) ServiceRestart(ctx context.Context) error {\n\treturn adm.serviceCallAction(ctx, ServiceActionRestart)\n}", "func Reboot(log zerolog.Logger) error {\n\treturn unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)\n}", "func (n *PaxosNode) Restart() bool {\n\tn.QuiesceStarted = false\n\treturn true\n}", "func (m *RdmaDevPlugin) Restart() error {\n\tif err := m.Stop(); err != nil {\n\t\treturn err\n\t}\n\treturn m.Start()\n}", "func (nd *Node) Restart() error {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tswitch nd.outputOption {\n\t\t\tcase ToTerminal:\n\t\t\t\tfmt.Fprintf(nd, \"panic while Restart Node %s (%v)\\n\", nd.Flags.Name, err)\n\t\t\tcase ToHTML:\n\t\t\t\tnd.BufferStream <- fmt.Sprintf(\"panic while Restart Node %s (%v)\\n\", nd.Flags.Name, err)\n\t\t\t\tif f, ok := nd.w.(http.Flusher); ok {\n\t\t\t\t\tif f != nil {\n\t\t\t\t\t\tf.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tif !nd.Terminated {\n\t\treturn fmt.Errorf(\"%s is already running\", nd.Flags.Name)\n\t}\n\n\tnd.Flags.InitialClusterState = \"existing\"\n\n\tcs := []string{\"/bin/bash\", \"-c\", nd.Command + \" \" + nd.Flags.String()}\n\tcmd := exec.Command(cs[0], cs[1:]...)\n\tcmd.Stdin = nil\n\tcmd.Stdout = nd\n\tcmd.Stderr = nd\n\n\tswitch nd.outputOption {\n\tcase ToTerminal:\n\t\tfmt.Fprintln(nd, \"Restart:\", nd.Flags.Name)\n\tcase ToHTML:\n\t\tnd.BufferStream <- fmt.Sprintf(\"Restart: %s\", nd.Flags.Name)\n\t\tif f, ok := nd.w.(http.Flusher); ok {\n\t\t\tif f != nil {\n\t\t\t\tf.Flush()\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"Failed to start %s with %v\\n\", nd.Flags.Name, err)\n\t}\n\tnd.cmd = cmd\n\tnd.PID = cmd.Process.Pid\n\tnd.Terminated = false\n\n\tgo func() {\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tfmt.Fprintf(nd, \"Exiting %s with %v\\n\", nd.Flags.Name, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprintf(nd, \"Exiting %s\\n\", nd.Flags.Name)\n\t}()\n\n\treturn nil\n}", "func restarter() {\n\tfor {\n\t\tfmt.Println(\"Restarter Loop started\")\n\t\t_, ok := <-doneChan\n\t\tif !ok {\n\t\t\tfmt.Println(\"Restarting...\")\n\n\t\t\tstopChan = make(chan bool)\n\t\t\tdoneChan = make(chan bool)\n\n\t\t\terr := mc.StreamListener(\"user\", \"\", events, stopChan, doneChan)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\n\t}\n}", "func (o InstanceGroupManagerActionsSummaryResponseOutput) Restarting() pulumi.IntOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerActionsSummaryResponse) int { return v.Restarting }).(pulumi.IntOutput)\n}", "func (i *Ipmi) ForceRestart(ctx context.Context) (status bool, err error) {\n\toutput, err := i.run(ctx, []string{\"chassis\", \"power\", \"status\"})\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"%v: %v\", err, output)\n\t}\n\n\tcommand := \"on\"\n\treply := \"Up/On\"\n\tif strings.HasPrefix(output, \"Chassis Power is on\") {\n\t\tcommand = \"cycle\"\n\t\treply = \"Cycle\"\n\t} else if !strings.HasPrefix(output, \"Chassis Power is off\") {\n\t\treturn false, fmt.Errorf(\"%v: %v\", err, output)\n\t}\n\n\toutput, err = i.run(ctx, []string{\"chassis\", \"power\", command})\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"%v: %v\", err, output)\n\t}\n\n\tif strings.HasPrefix(output, \"Chassis Power Control: \"+reply) {\n\t\treturn true, err\n\t}\n\treturn false, fmt.Errorf(\"%v: %v\", err, output)\n}", "func (a ClustersAPI) Restart(clusterID string) error {\n\tdata := struct {\n\t\tClusterID string `json:\"cluster_id,omitempty\" url:\"cluster_id,omitempty\"`\n\t}{\n\t\tclusterID,\n\t}\n\t_, err := a.Client.performQuery(http.MethodPost, \"/clusters/restart\", data, nil)\n\treturn err\n}", "func (c *Client) Restart(ctx context.Context, id string) error {\n\targ := &ngrok.Item{ID: id}\n\n\tvar path bytes.Buffer\n\tif err := template.Must(template.New(\"restart_path\").Parse(\"/tunnel_sessions/{{ .ID }}/restart\")).Execute(&path, arg); err != nil {\n\t\tpanic(err)\n\t}\n\targ.ID = \"\"\n\tvar (\n\t\tapiURL = &url.URL{Path: path.String()}\n\t\tbodyArg interface{}\n\t)\n\tapiURL.Path = path.String()\n\tbodyArg = arg\n\n\tif err := c.apiClient.Do(ctx, \"POST\", apiURL, bodyArg, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (proc *Proc) AddRestart() {\n\tproc.Status.IncrRestart()\n}", "func (s *Supervisor) ReStart() {\n\tvar err error\n\ttime.Sleep(s.wait)\n\tif s.daemon.lock == 0 {\n\t\tnp := NewProcess(s.daemon.cfg)\n\t\tif s.process, err = s.daemon.Run(np); err != nil {\n\t\t\tclose(np.quit)\n\t\t\tlog.Print(err)\n\t\t\t// loop again but wait 1 seccond before trying\n\t\t\ts.wait = time.Second\n\t\t\ts.daemon.run <- struct{}{}\n\t\t}\n\t}\n}", "func restartNano(cmd *cobra.Command, args []string) {\n\tctx := context.Background()\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnotExistCheck()\n\tfmt.Println(\"Restarting ceph-nano...\")\n\tif err := cli.ContainerRestart(ctx, ContainerName, nil); err != nil {\n\t\tpanic(err)\n\t}\n\techoInfo()\n}", "func (s *Service) Restart() error {\n\tif s.mgr == nil {\n\t\treturn ErrNoManager\n\t}\n\n\ts.mgr.lock()\n\tdefer s.mgr.unlock()\n\n\tif !s.enabled {\n\t\treturn nil\n\t}\n\n\ts.serial = s.mgr.bumpSerial()\n\ts.logf(\"Restarting service %s\", s.Name())\n\ts.enabled = false\n\ts.stopRecurse(\"Stopping for restart\")\n\n\ts.stamp = time.Now()\n\ts.reason = \"Restarting\"\n\ts.starts = 0\n\ts.failed = false\n\ts.err = nil\n\ts.enabled = true\n\ts.startRecurse(\"Restarting\")\n\treturn nil\n}", "func (m *UserExperienceAnalyticsDeviceStartupHistory) SetRestartCategory(value *UserExperienceAnalyticsOperatingSystemRestartCategory)() {\n err := m.GetBackingStore().Set(\"restartCategory\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *service) Reload() error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\t// Find highest restart epoch of the known running Envoy processes.\n\trestartEpoch := -1\n\tfor _, epoch := range s.cmdMap {\n\t\tif epoch > restartEpoch {\n\t\t\trestartEpoch = epoch\n\t\t}\n\t}\n\trestartEpoch++\n\n\t// Spin up a new Envoy process.\n\tcmd := exec.Command(s.binary,\n\t\t\"-c\", s.config,\n\t\t\"--drain-time-s\", fmt.Sprint(s.drainTime),\n\t\t\"--parent-shutdown-time-s\", fmt.Sprint(s.parentShutdownTime),\n\t\t\"--service-cluster\", \"a8clusters\",\n\t\t\"--service-node\", \"a8nodes\",\n\t\t\"--restart-epoch\", fmt.Sprint(restartEpoch))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\t// Add the new Envoy process to the known set of running Envoy processes.\n\ts.cmdMap[cmd] = restartEpoch\n\n\t// Start tracking the process.\n\tgo s.waitForExit(cmd)\n\n\ttime.Sleep(256 * time.Millisecond)\n\n\treturn nil\n}", "func (d *Deployment) Restart(ctx context.Context, path string) error {\n\to, err := d.GetFactory().Get(\"apps/v1/deployments\", path, true, labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar dp appsv1.Deployment\n\terr = runtime.DefaultUnstructuredConverter.FromUnstructured(o.(*unstructured.Unstructured).Object, &dp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauth, err := d.Client().CanI(dp.Namespace, \"apps/v1/deployments\", []string{client.PatchVerb})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !auth {\n\t\treturn fmt.Errorf(\"user is not authorized to restart a deployment\")\n\t}\n\n\tdial, err := d.Client().Dial()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbefore, err := runtime.Encode(scheme.Codecs.LegacyCodec(appsv1.SchemeGroupVersion), &dp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tafter, err := polymorphichelpers.ObjectRestarterFn(&dp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdiff, err := strategicpatch.CreateTwoWayMergePatch(before, after, dp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = dial.AppsV1().Deployments(dp.Namespace).Patch(\n\t\tctx,\n\t\tdp.Name,\n\t\ttypes.StrategicMergePatchType,\n\t\tdiff,\n\t\tmetav1.PatchOptions{},\n\t)\n\n\treturn err\n}", "func Rerun(seconds int) {\n\trerun = seconds\n}", "func (_SweetToken *SweetTokenSession) Restart() (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Restart(&_SweetToken.TransactOpts)\n}", "func HotReload(appName string, ctx *Context) {\n\tpresent, process := FindDaemonProcess(ctx)\n\tif present {\n\t\tlog.Printf(\"sending SIGUSR2 to pid %v\", process.Pid)\n\t\tif err := sigSendUSR2(process); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn\n\t\t}\n\t\tStop(appName, ctx)\n\t} else {\n\t\tfmt.Printf(\"%v is stopped.\\n\", appName)\n\t}\n}", "func Restart(client *cliHttp.SimpleClient, gameID int, size int64, checksum string) (*RestartResult, error) {\n\tgetParams := url.Values(map[string][]string{\n\t\t\"game_id\": {strconv.Itoa(gameID)},\n\t\t\"size\": {strconv.FormatInt(size, 10)},\n\t\t\"checksum\": {checksum},\n\t})\n\n\t_, res, err := client.Post(\"files/restart\", getParams, nil)\n\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to restart file upload: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to restart file upload: \" + err.Error())\n\t}\n\n\tresult := &RestartResult{}\n\tif err = json.Unmarshal(body, result); err != nil {\n\t\treturn nil, errors.New(\"Failed to restart file upload, the server returned a weird looking response: \" + string(body))\n\t}\n\n\tif result.Error != nil {\n\t\treturn nil, apiErrors.New(result.Error)\n\t}\n\treturn result, nil\n}", "func (w *Worker) Reload() {\n\tw.cmd.Process.Signal(syscall.SIGHUP)\n}", "func (r *ResumeStrategy) restartService() error {\n\terr := service.Start(r.ServiceName)\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif systemservice.IsUnknownServiceError(err) {\n\t\treturn trace.NotFound(\"service %v not found\", r.ServiceName)\n\t}\n\treturn trace.Wrap(err)\n}", "func primaryCrashElectRestart(t *testing.T) {\n\tproxyURL := tutils.RandomProxyURL(t)\n\tkillRestorePrimary(t, proxyURL, false, nil)\n}", "func (_SweetToken *SweetTokenTransactorSession) Restart() (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Restart(&_SweetToken.TransactOpts)\n}", "func (actor Actor) RestartApplication(appGUID string) (Warnings, error) {\n\tvar allWarnings Warnings\n\t_, warnings, err := actor.CloudControllerClient.UpdateApplicationRestart(appGUID)\n\tallWarnings = append(allWarnings, warnings...)\n\tif err != nil {\n\t\treturn allWarnings, err\n\t}\n\n\tpollingWarnings, err := actor.PollStart(appGUID)\n\tallWarnings = append(allWarnings, pollingWarnings...)\n\treturn allWarnings, err\n}", "func (h *Hero) Restart() {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\tpos := h.world.RandomizePos(h.ID, heroW, heroH)\n\th.setDefaults(pos.X, pos.Y, pos.W, pos.H, h.world)\n}", "func restartInterface(ctx context.Context) error {\n\terr := testexec.CommandContext(ctx, \"modprobe\", \"-r\", \"iwlmvm\", \"iwlwifi\").Run(testexec.DumpLogOnError)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"could not remove module iwlmvm and iwlwifi\")\n\t}\n\tif err2 := testexec.CommandContext(ctx, \"modprobe\", \"iwlwifi\").Run(testexec.DumpLogOnError); err2 != nil {\n\t\treturn errors.Wrapf(err, \"could not load iwlwifi module: %s\", err2.Error())\n\t}\n\treturn err\n}", "func (m Miner) Reboot() error {\n\tclient, err := jsonrpc.Dial(\"tcp\", m.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\targs.psw = m.Password\n\treturn client.Call(methodReboot, args, nil)\n}", "func restartInstallOrJoin(env *localenv.LocalEnvironment) error {\n\tenv.PrintStep(\"Resuming installer\")\n\n\tbaseDir := utils.Exe.WorkingDir\n\tstrategy, err := newResumeStrategy(baseDir)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\terr = InstallerClient(env, installerclient.Config{\n\t\tConnectStrategy: strategy,\n\t\tLifecycle: &installerclient.AutomaticLifecycle{\n\t\t\tAborter: installerAbortOperation(strategy.ServiceName),\n\t\t\tCompleter: InstallerCompleteOperation(strategy.ServiceName, env),\n\t\t\tDebugReportPath: DebugReportPath(),\n\t\t\tLocalDebugReporter: InstallerGenerateLocalReport(env),\n\t\t},\n\t})\n\tif utils.IsContextCancelledError(err) {\n\t\t// We only end up here if the initialization has not been successful - clean up the state\n\t\tif err := InstallerCleanup(strategy.ServiceName); err != nil {\n\t\t\tlog.Warnf(\"Failed to clean up installer: %v.\", err)\n\t\t}\n\t\treturn trace.Wrap(err, \"installer interrupted\")\n\t}\n\treturn trace.Wrap(err)\n}", "func (i *Instance) Restarted(restarts InsRestarts) (*Instance, error) {\n\t//\n\t// instances/\n\t// 6868/\n\t// object = <app> <rev> <proc>\n\t// start = 10.0.0.1 24690 localhost\n\t// - restarts = 1 4\n\t// + restarts = 2 4\n\t//\n\t// instances/\n\t// 6869/\n\t// object = <app> <rev> <proc>\n\t// start = 10.0.0.1 24691 localhost\n\t// + restarts = 1 0\n\t//\n\tif i.Status != InsStatusRunning {\n\t\treturn i, nil\n\t}\n\n\tsp, err := i.GetSnapshot().FastForward()\n\tif err != nil {\n\t\treturn i, err\n\t}\n\n\tf := cp.NewFile(i.dir.Prefix(restartsPath), nil, new(cp.ListIntCodec), sp)\n\n\tf, err = f.Set(restarts.Fields())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.Restarts = restarts\n\ti.dir = i.dir.Join(f)\n\n\treturn i, nil\n}", "func (o ApplicationUpgradePolicyOutput) ForceRestart() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v ApplicationUpgradePolicy) *bool { return v.ForceRestart }).(pulumi.BoolPtrOutput)\n}", "func (c *Controller) tunedRestart(timeoutInitiated bool) (err error) {\n\tif _, err = c.tunedStop(); err != nil {\n\t\treturn err\n\t}\n\tc.tunedCmd = nil // Cmd.Start() cannot be used more than once\n\tc.tunedExit = make(chan bool, 1) // Once tunedStop() terminates, the tunedExit channel is closed!\n\n\tif err = c.tunedReload(timeoutInitiated); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *RemoteCluster) Restart(i int) error {\n\t_ = r.Kill(i)\n\t// supervisorctl is horrible with exit codes (cockroachdb/cockroach-prod#59).\n\treturn r.execSupervisor(i, \"start cockroach\")\n}", "func (strm *Stream) Restart() *sync.WaitGroup {\n\tif strm == nil {\n\t\treturn nil\n\t}\n\tstrm.Mux.Lock()\n\tif strm.CMD != nil && strm.CMD.ProcessState != nil {\n\t\tstrm.CMD.Process.Kill()\n\t}\n\tstrm.CMD = strm.Process.Spawn(strm.StorePath, strm.OriginalURI)\n\tif strm.LoggingOpts.Enabled {\n\t\tstrm.CMD.Stderr = strm.Logger\n\t\tstrm.CMD.Stdout = strm.Logger\n\t}\n\tstrm.Streak.Activate().Hit()\n\tstrm.Mux.Unlock()\n\treturn strm.Start()\n}", "func (adm *AdminClient) ServiceRestart() error {\n\t//\n\treqData := requestData{}\n\treqData.queryValues = make(url.Values)\n\treqData.queryValues.Set(\"service\", \"\")\n\treqData.customHeaders = make(http.Header)\n\treqData.customHeaders.Set(minioAdminOpHeader, \"restart\")\n\n\t// Execute GET on bucket to list objects.\n\tresp, err := adm.executeMethod(\"POST\", reqData)\n\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn httpRespToErrorResponse(resp)\n\t}\n\treturn nil\n}", "func (s *Service) Restart(ctx context.Context, timeout int) error {\n\ttimeout = s.stopTimeout(timeout)\n\treturn s.collectContainersAndDo(ctx, func(c *container.Container) error {\n\t\treturn c.Restart(ctx, timeout)\n\t})\n}", "func newRestartCommand(client *client.Client) *Command {\n\trestartStrings := docstrings.Get(\"restart\")\n\trestartCmd := BuildCommandKS(nil, runRestart, restartStrings, client, requireSession, requireAppNameAsArg)\n\trestartCmd.Args = cobra.RangeArgs(0, 1)\n\n\treturn restartCmd\n}" ]
[ "0.74956864", "0.7276446", "0.724625", "0.7144054", "0.70957565", "0.7012717", "0.7004468", "0.69704926", "0.6808136", "0.67299974", "0.6707739", "0.6671288", "0.66431946", "0.66143584", "0.65433764", "0.6533106", "0.6501655", "0.64996433", "0.6497295", "0.6495759", "0.64949965", "0.649093", "0.6468322", "0.6448265", "0.6431029", "0.64289784", "0.6425251", "0.63979524", "0.63940257", "0.6360013", "0.6349392", "0.6348009", "0.63320744", "0.63218385", "0.63023686", "0.6215234", "0.6211932", "0.6190709", "0.61656797", "0.6134736", "0.61313534", "0.6129843", "0.6125453", "0.60995746", "0.60947543", "0.60349", "0.59945536", "0.59856206", "0.5981359", "0.5968635", "0.5965973", "0.59602374", "0.59551924", "0.59532076", "0.5905737", "0.5894867", "0.5869275", "0.58569074", "0.58313876", "0.58267707", "0.582356", "0.5818626", "0.579211", "0.5788229", "0.5778724", "0.57720405", "0.5767864", "0.57476246", "0.5733005", "0.57133883", "0.56982964", "0.5696346", "0.5693598", "0.56914306", "0.56746435", "0.5665343", "0.5655895", "0.56538534", "0.5640875", "0.5633028", "0.5631398", "0.5617062", "0.56125635", "0.56114155", "0.5605873", "0.55978394", "0.5582854", "0.5582821", "0.55753005", "0.55749136", "0.5560732", "0.55513406", "0.55497247", "0.5542397", "0.554102", "0.5537548", "0.55315", "0.55297244", "0.55274737", "0.55123276" ]
0.77647364
0
IsInputNode returns whether Node is InputNode
IsInputNode возвращает true, если Node является InputNode
func (inNode *InputNode) IsInputNode() bool { return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func isInput(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"input\"\n}", "func (neuron *Neuron) IsInput() bool {\n\tif neuron.Net == nil {\n\t\treturn false\n\t}\n\treturn neuron.Net.IsInput(neuron.neuronIndex)\n}", "func (w *Wire) IsInput() bool {\n\treturn w.input == nil\n}", "func (neuron *Neuron) HasInput(e NeuronIndex) bool {\n\tfor _, ni := range neuron.InputNodes {\n\t\tif ni == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (Step) IsNode() {}", "func (Node) Is(typ string) bool { return boolResult }", "func (Workspace) IsNode() {}", "func (Task) IsNode() {}", "func (address Address) IsNode() {}", "func (Project) IsNode() {}", "func inputSelector(n *Node) bool {\n\treturn n.Type() == ElementNode && (n.Name() == \"input\" || n.Name() == \"select\" || n.Name() == \"textarea\" || n.Name() == \"button\")\n}", "func NewInputNode(inStream msgstream.MsgStream, nodeName string, maxQueueLength int32, maxParallelism int32, role string, nodeID int64, collectionID int64, dataType string) *InputNode {\n\tbaseNode := BaseNode{}\n\tbaseNode.SetMaxQueueLength(maxQueueLength)\n\tbaseNode.SetMaxParallelism(maxParallelism)\n\n\treturn &InputNode{\n\t\tBaseNode: baseNode,\n\t\tinStream: inStream,\n\t\tname: nodeName,\n\t\trole: role,\n\t\tnodeID: nodeID,\n\t\tcollectionID: collectionID,\n\t\tdataType: dataType,\n\t}\n}", "func (g *GPIOControllerPCF8574T) IsInput(index int) bool {\n\tif index < 0 || index > pinCount {\n\t\tfmt.Printf(\"Input out of range for gpio: %d\", index)\n\t\treturn false\n\t}\n\n\treturn false\n}", "func IsOperationInputAPropertyDefinition(ctx context.Context, deploymentID, nodeTemplateImpl, typeNameImpl, operationName, inputName string) (bool, error) {\n\tvar typeOrNodeTemplate string\n\tif nodeTemplateImpl == \"\" {\n\t\ttypeOrNodeTemplate = typeNameImpl\n\t} else {\n\t\ttypeOrNodeTemplate = nodeTemplateImpl\n\t}\n\toperationDef, interfaceDef, err := getOperationAndInterfaceDefinitions(ctx, deploymentID, nodeTemplateImpl, typeNameImpl, operationName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif operationDef != nil {\n\t\tinput, is := operationDef.Inputs[inputName]\n\t\tif is && &input != nil {\n\t\t\treturn input.PropDef != nil, nil\n\t\t}\n\t}\n\n\tif interfaceDef != nil {\n\t\tinput, is := interfaceDef.Inputs[inputName]\n\t\tif is && &input != nil {\n\t\t\treturn input.PropDef != nil, nil\n\t\t}\n\t}\n\treturn false, errors.Errorf(\"failed to find input with name:%q for operation:%q and node template/type:%q\", inputName, operationName, typeOrNodeTemplate)\n}", "func IsNodeIn(fi *v1alpha1.FileIntegrity, nodeName string, annotation string) bool {\n\tif fi.Annotations == nil {\n\t\treturn false\n\t}\n\tif nodeList, has := fi.Annotations[annotation]; has {\n\t\t// If the annotation is empty, we assume all nodes are in reinit\n\t\tif nodeList == \"\" {\n\t\t\treturn true\n\t\t}\n\t\tfor _, node := range strings.Split(nodeList, \",\") {\n\t\t\tif node == nodeName {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func isAcceptingInput(oldFn reflect.Value) bool {\n\treturn oldFn.Type().NumIn() == 1\n}", "func (MatchedNode) Is(typ string) bool { return boolResult }", "func (t *BinaryTree) IsNode(e interface{}) (bool, error) {\n\tif t.count == 0 {\n\t\treturn false, errors.New(\"Tree is empty\")\n\t}\n\tn := t.root\n\tok, err := n.isbnode(e)\n\treturn ok, err\n}", "func (this *Node) IsMe(nodeName string) bool {\n\treturn this.NodeInfo.Name == nodeName\n}", "func (n *Network) AddInputNode(node *NNode) {\n\tn.Inputs = append(n.Inputs, node)\n}", "func (this *DefaultNode) IsMe(nodeName string) bool {\n\treturn this.NodeInfo.Name == nodeName\n}", "func (neuron *Neuron) InputNeuronsAreGood() bool {\n\tfor _, inputNeuronIndex := range neuron.InputNodes {\n\t\tif !neuron.Net.Exists(inputNeuronIndex) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c GlobalConfig) IsNode() bool {\n\treturn RunMode(c.OBSMode).IsNode()\n}", "func IsInputFromPipe() bool {\n\tfileInfo, _ := os.Stdin.Stat()\n\treturn fileInfo.Mode()&os.ModeCharDevice == 0\n}", "func (o *WorkflowServiceItemActionInstance) HasInput() bool {\n\tif o != nil && o.Input != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *baseNode) IsNodeType(nodeType NodeType) bool {\n\treturn s.nodeType == nodeType\n}", "func CfnInput_IsCfnElement(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_iotevents.CfnInput\",\n\t\t\"isCfnElement\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (neuron *Neuron) IsOutput() bool {\n\tif neuron.Net == nil {\n\t\treturn false\n\t}\n\treturn neuron.Net.OutputNode == neuron.neuronIndex\n}", "func (in *TransferableInput) Input() Transferable { return in.In }", "func IsClonedInput(ctx context.Context) bool {\n\tv, _ := ctx.Value(clonedInputKey{}).(bool)\n\treturn v\n}", "func IsHtmlNode(n *html.Node, name string) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\treturn n.Type == html.ElementNode && n.Data == name\n}", "func (r *MessageExecuteCommand) HasInput() bool {\n\treturn r.hasInput\n}", "func (neuron *Neuron) AddInput(ni NeuronIndex) error {\n\tif neuron.Is(ni) {\n\t\treturn errors.New(\"adding a neuron as input to itself\")\n\t}\n\tif neuron.HasInput(ni) {\n\t\treturn errors.New(\"neuron already exists\")\n\t}\n\tneuron.InputNodes = append(neuron.InputNodes, ni)\n\n\treturn nil\n}", "func IsPipedInput() bool {\n\tfi, _ := os.Stdin.Stat()\n\n\treturn fi.Mode()&os.ModeNamedPipe != 0\n}", "func (in *TransferableInput) Input() TransferableIn {\n\treturn in.In\n}", "func IsStdin(r io.Reader) bool {\n\tif f, ok := r.(*os.File); ok {\n\t\treturn f.Fd() == uintptr(syscall.Stdin)\n\t}\n\treturn false\n}", "func (inNode *InputNode) Name() string {\n\treturn inNode.name\n}", "func IsInline(t NodeType) bool {\n\treturn t&(NodeText|NodeURL|NodeImage|NodeButton) != 0\n}", "func (neuron *Neuron) FindInput(e NeuronIndex) (int, bool) {\n\tfor i, n := range neuron.InputNodes {\n\t\tif n == e {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func IsInputNotFound(err error) bool {\n\terr = errors.Cause(err)\n\t_, ok := err.(inputNotFound)\n\treturn ok\n}", "func (o *WorkflowSolutionActionDefinition) HasInputDefinition() bool {\n\tif o != nil && o.InputDefinition != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (inNode *InputNode) InStream() msgstream.MsgStream {\n\treturn inNode.inStream\n}", "func (inp inputT) IsLayout() bool {\n\tif inp.Type == \"textblock\" {\n\t\treturn true\n\t}\n\tif inp.Type == \"button\" { // we dont care\n\t\treturn true\n\t}\n\tif inp.Type == \"label-as-input\" {\n\t\treturn true\n\t}\n\tif inp.Type == \"dyn-textblock\" {\n\t\treturn true\n\t}\n\tif inp.Type == \"dyn-composite\" { // inputs are in \"dyn-composite-scalar\"\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (neuron *Neuron) InputStatement() (*jen.Statement, error) {\n\t// If this node is a network input node, return a statement representing this input,\n\t// like \"inputData[0]\"\n\tif !neuron.IsInput() {\n\t\treturn jen.Empty(), errors.New(\" not an input node\")\n\t}\n\tfor i, ni := range neuron.Net.InputNodes {\n\t\tif ni == neuron.neuronIndex {\n\t\t\t// This index in the neuron.NetInputNodes is i\n\t\t\treturn jen.Id(\"inputData\").Index(jen.Lit(i)), nil\n\t\t}\n\t}\n\t// Not found!\n\treturn jen.Empty(), errors.New(\"not an input node for the associated network\")\n}", "func IsRootNode(node []byte) bool {\n\tvar IsRootNodeField uint8 = *(*uint8)(unsafe.Pointer(&node[IsRootNodeOffset]))\n\tif IsRootNodeField == 1 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (n *Node) Bool() bool", "func isNode(line string) bool {\n\treturn nodeRegex.MatchString(line) && len(line) > 2\n}", "func IsNodeTemplateImplementingOperation(ctx context.Context, deploymentID, nodeName, operationName string) (bool, error) {\n\toperationDef, _, err := getOperationAndInterfaceDefinitions(ctx, deploymentID, nodeName, \"\", operationName)\n\tif err != nil {\n\t\treturn false, errors.Wrapf(err, \"Can't define if operation with name:%q exists for node %q\", operationName, nodeName)\n\t}\n\treturn isOperationImplemented(operationDef), nil\n}", "func IsInputErr(err error) bool {\n\treturn errors.HasErrorCode(err, invalidInput)\n}", "func (obj *transformOperation) Input() Identifier {\n\treturn obj.input\n}", "func (inNode *InputNode) Start() {\n}", "func UpdateNodeUserInput(userInput []policy.UserInput,\n\terrorhandler DeviceErrorHandler,\n\tgetDevice exchange.DeviceHandler,\n\tpatchDevice exchange.PatchDeviceHandler,\n\tdb *bolt.DB) (bool, []policy.UserInput, []*events.NodeUserInputMessage) {\n\n\t// Check for the device in the local database. If there are errors, they will be written\n\t// to the HTTP response.\n\tpDevice, err := persistence.FindExchangeDevice(db)\n\tif err != nil {\n\t\treturn errorhandler(nil, NewSystemError(fmt.Sprintf(\"Unable to read node object, error %v\", err))), nil, nil\n\t} else if pDevice == nil {\n\t\treturn errorhandler(nil, NewNotFoundError(\"Exchange registration not recorded. Complete account and node registration with an exchange and then record node registration using this API's /node path.\", \"node\")), nil, nil\n\t}\n\n\tif changedSvcs, err := exchangesync.UpdateNodeUserInput(pDevice, db, userInput, getDevice, patchDevice); err != nil {\n\t\treturn errorhandler(pDevice, NewSystemError(fmt.Sprintf(\"Unable to update the node user input. %v\", err))), nil, nil\n\t} else {\n\t\tLogDeviceEvent(db, persistence.SEVERITY_INFO, fmt.Sprintf(\"New node user input: %v\", userInput), persistence.EC_NODE_USERINPUT_UPDATED, pDevice)\n\n\t\tnodeUserInputUpdated := events.NewNodeUserInputMessage(events.UPDATE_NODE_USERINPUT, changedSvcs)\n\t\treturn false, userInput, []*events.NodeUserInputMessage{nodeUserInputUpdated}\n\t}\n}", "func (o *WorkflowServiceItemInputDefinitionType) HasInputDefinition() bool {\n\tif o != nil && o.InputDefinition != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *WorkflowCatalogServiceRequest) HasInput() bool {\n\tif o != nil && o.Input != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (ns Nodes) Is(selector string) bool {\n\tsel := parseSelector(selector)\n\tif len(sel) == 1 {\n\t\tfor _, v := range ns {\n\t\t\tif satisfiesSel(v, sel[0]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (n *Network) IsControlNode(nid int) bool {\n\tfor _, cn := range n.controlNodes {\n\t\tif cn.Id == nid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *WorkflowWorkflowDefinitionAllOf) HasInputDefinition() bool {\n\tif o != nil && o.InputDefinition != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SdwanRouterNode) HasTemplateInputs() bool {\n\tif o != nil && o.TemplateInputs != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TxsdFeCompositeTypeOperator) IsOut() bool { return me.String() == \"out\" }", "func (obj *testInstruction) IsInstruction() bool {\n\treturn obj.ins != nil\n}", "func (d *hoverWalker) EnterNode(n ir.Node) bool {\n\tstate.EnterNode(&d.st, n)\n\treturn true\n}", "func (me TxsdFeCompositeTypeOperator) IsIn() bool { return me.String() == \"in\" }", "func (neuron *Neuron) Is(e NeuronIndex) bool {\n\treturn neuron.neuronIndex == e\n}", "func (rndr *Renderer) isThisNodeOrHostIP(ip net.IP) bool {\n\tnodeIP, _ := rndr.IPNet.GetNodeIP()\n\tif ip.Equal(nodeIP) {\n\t\treturn true\n\t}\n\tfor _, hostIP := range rndr.IPNet.GetHostIPs() {\n\t\tif hostIP.Equal(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *WorkflowServiceItemInputDefinitionType) HasInputParameters() bool {\n\tif o != nil && o.InputParameters != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *CheckIfEmailExistResult) HasInput() bool {\n\tif o != nil && o.Input != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsValidNodeIP(ip *net.IP) bool {\n\treturn ip.IsGlobalUnicast()\n}", "func IsClusterNode(name string) bool {\n\treturn false\n}", "func (t *DataProcessorTask) HasInputTables() bool {\n\treturn t.Has(InputTables)\n}", "func (s STExpressionOperator) IsInstruction() bool {\n\treturn true\n}", "func (g *Gateway) IsDqliteNode() bool {\n\tg.lock.RLock()\n\tdefer g.lock.RUnlock()\n\n\tif g.info != nil {\n\t\tif g.server == nil {\n\t\t\tpanic(\"gateway has node identity but no dqlite server\")\n\t\t}\n\n\t\treturn true\n\t}\n\n\tif g.server != nil {\n\t\tpanic(\"gateway dqlite server but no node identity\")\n\t}\n\n\treturn true\n}", "func (t *DataProcessorTask) HasInputDirs() bool {\n\treturn t.Has(InputDirs)\n}", "func (inp inputT) IsHidden() bool {\n\tif inp.Type == \"hidden\" {\n\t\treturn true\n\t}\n\tif inp.Type == \"javascript-block\" {\n\t\treturn true\n\t}\n\tif inp.Type == \"dyn-composite-scalar\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func (n *Node) IsControlPlane() bool {\n\treturn n.Role() == constants.ControlPlaneNodeRoleValue\n}", "func (obj *transform) Input() string {\n\treturn obj.input\n}", "func NodeIsKnown(addr string) bool {\n\tfor _, node := range KnownNodes {\n\t\tif node == addr {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (n *Node) IsControlPlane() bool {\n\treturn n.Role == ControlPlaneRole\n}", "func Input() *Event {\n\treturn NewEvent(\"input\")\n\n}", "func IsUnary(node sql.Node) bool {\n\treturn len(node.Children()) == 1\n}", "func IsTextNode(n *html.Node) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\treturn n.Type == html.TextNode\n}", "func (socket *MockSocket) Input() *socket.InputProtocol {\n\treturn socket.input\n}", "func (node *Node) IsTag(name string) bool {\n\treturn node.Type == ElementNode && node.Data == name\n}", "func (n *Network) PrintInput() string {\n\tout := bytes.NewBufferString(fmt.Sprintf(\"Network %s with id %d inputs: (\", n.Name, n.Id))\n\tfor i, node := range n.Inputs {\n\t\tfmt.Fprintf(out, \"[Input #%d: %s] \", i, node)\n\t}\n\tfmt.Fprint(out, \")\")\n\treturn out.String()\n}", "func (w *Wire) Input() *Gate {\n\treturn w.input\n}", "func DebugIdentityV3IsInput(value bool) DebugIdentityV3Attr {\n\treturn func(m optionalAttr) {\n\t\tm[\"is_input\"] = value\n\t}\n}", "func isObject(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"object\"\n}", "func CfnInput_IsCfnResource(construct constructs.IConstruct) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_iotevents.CfnInput\",\n\t\t\"isCfnResource\",\n\t\t[]interface{}{construct},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (n *Network) PrintInput() string {\n\tout := bytes.NewBufferString(fmt.Sprintf(\"Network %s with id %d inputs: (\", n.Name, n.Id))\n\tfor i, node := range n.inputs {\n\t\t_, _ = fmt.Fprintf(out, \"[Input #%d: %s] \", i, node)\n\t}\n\t_, _ = fmt.Fprint(out, \")\")\n\treturn out.String()\n}", "func (neuron *Neuron) AddInputNeuron(n *Neuron) error {\n\t// If n.neuronIndex is known to this network, just add the NeuronIndex to neuron.InputNeurons\n\tif neuron.Net.Exists(n.neuronIndex) {\n\t\treturn neuron.AddInput(n.neuronIndex)\n\t}\n\t// If not, add this neuron to the network first\n\tnode := *n\n\tnode.neuronIndex = NeuronIndex(len(neuron.Net.AllNodes))\n\tneuron.Net.AllNodes = append(neuron.Net.AllNodes, node)\n\treturn neuron.AddInput(n.neuronIndex)\n}", "func (n *PipeNode) IsEqual(other Node) bool {\n\tif !n.equal(n, other) {\n\t\treturn false\n\t}\n\n\to, ok := other.(*PipeNode)\n\n\tif !ok {\n\t\tdebug(\"Failed to convert to PipeNode\")\n\t\treturn false\n\t}\n\n\tif len(n.cmds) != len(o.cmds) {\n\t\tdebug(\"Number of pipe commands differ: %d != %d\",\n\t\t\tlen(n.cmds), len(o.cmds))\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(n.cmds); i++ {\n\t\tif !n.cmds[i].IsEqual(o.cmds[i]) {\n\t\t\tdebug(\"Command differs. '%s' != '%s'\", n.cmds[i],\n\t\t\t\to.cmds[i])\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (context Context) IsUsingKeyboard() bool {\n\treturn imgui.CurrentIO().WantTextInput()\n}", "func (w *W3CNode) IsRoot() bool {\n\treturn w.ParentNode() == nil\n}", "func (n *Node) LoadInput(invalue FloatXX) {\n\tn.inputValue = invalue\n}", "func DeleteNodeUserInput(errorhandler DeviceErrorHandler, db *bolt.DB,\n\tgetDevice exchange.DeviceHandler,\n\tpatchDevice exchange.PatchDeviceHandler) (bool, []*events.NodeUserInputMessage) {\n\n\t// Check for the device in the local database. If there are errors, they will be written\n\t// to the HTTP response.\n\tpDevice, err := persistence.FindExchangeDevice(db)\n\tif err != nil {\n\t\treturn errorhandler(nil, NewSystemError(fmt.Sprintf(\"Unable to read node object, error %v\", err))), nil\n\t} else if pDevice == nil {\n\t\treturn errorhandler(nil, NewNotFoundError(\"Exchange registration not recorded. Complete account and node registration with an exchange and then record node registration using this API's /node path.\", \"node\")), nil\n\t}\n\n\tuserInput, err := persistence.FindNodeUserInput(db)\n\tif err != nil {\n\t\treturn errorhandler(pDevice, NewSystemError(fmt.Sprintf(\"unable to read node user input object, error %v\", err))), nil\n\t}\n\tif userInput == nil || len(userInput) == 0 {\n\t\tLogDeviceEvent(db, persistence.SEVERITY_INFO, fmt.Sprintf(\"No node user input to detele\"), persistence.EC_NODE_USERINPUT_UPDATED, pDevice)\n\t\treturn false, []*events.NodeUserInputMessage{}\n\t}\n\n\t// delete the node policy from both exchange the local db\n\tif err := exchangesync.DeleteNodeUserInput(pDevice, db, getDevice, patchDevice); err != nil {\n\t\treturn errorhandler(pDevice, NewSystemError(fmt.Sprintf(\"Node user input could not be deleted. %v\", err))), nil\n\t}\n\n\tLogDeviceEvent(db, persistence.SEVERITY_INFO, fmt.Sprintf(\"Deleted all node user input\"), persistence.EC_NODE_USERINPUT_UPDATED, pDevice)\n\n\tchnagedSvcSpecs := new(persistence.ServiceSpecs)\n\tfor _, ui := range userInput {\n\t\tchnagedSvcSpecs.AppendServiceSpec(persistence.ServiceSpec{Url: ui.ServiceUrl, Org: ui.ServiceOrgid})\n\t}\n\tnodeUserInputUpdated := events.NewNodeUserInputMessage(events.UPDATE_NODE_USERINPUT, *chnagedSvcSpecs)\n\treturn false, []*events.NodeUserInputMessage{nodeUserInputUpdated}\n}", "func PatchNodeUserInput(patchObject []policy.UserInput,\n\terrorhandler DeviceErrorHandler,\n\tgetDevice exchange.DeviceHandler,\n\tpatchDevice exchange.PatchDeviceHandler,\n\tdb *bolt.DB) (bool, []policy.UserInput, []*events.NodeUserInputMessage) {\n\n\tpDevice, err := persistence.FindExchangeDevice(db)\n\tif err != nil {\n\t\treturn errorhandler(nil, NewSystemError(fmt.Sprintf(\"Unable to read node object, error %v\", err))), nil, nil\n\t} else if pDevice == nil {\n\t\treturn errorhandler(nil, NewNotFoundError(\"Exchange registration not recorded. Complete account and node registration with an exchange and then record node registration using this API's /node path.\", \"node\")), nil, nil\n\t}\n\n\tif err := exchangesync.PatchNodeUserInput(pDevice, db, patchObject, getDevice, patchDevice); err != nil {\n\t\treturn errorhandler(pDevice, NewSystemError(fmt.Sprintf(\"Unable patch the user input. %v\", err))), nil, nil\n\t} else {\n\t\tLogDeviceEvent(db, persistence.SEVERITY_INFO, fmt.Sprintf(\"New node user input: %v\", patchObject), persistence.EC_NODE_USERINPUT_UPDATED, pDevice)\n\n\t\tchnagedSvcSpecs := new(persistence.ServiceSpecs)\n\t\tfor _, ui := range patchObject {\n\t\t\tchnagedSvcSpecs.AppendServiceSpec(persistence.ServiceSpec{Url: ui.ServiceUrl, Org: ui.ServiceOrgid})\n\n\t\t}\n\t\tnodeUserInputUpdated := events.NewNodeUserInputMessage(events.UPDATE_NODE_USERINPUT, *chnagedSvcSpecs)\n\t\treturn false, patchObject, []*events.NodeUserInputMessage{nodeUserInputUpdated}\n\t}\n}", "func (t *DataProcessorTask) HasInputFiles() bool {\n\treturn t.Has(InputFiles)\n}", "func isLoopHead(n *Node) bool {\n\tif n.LoopHead == nil {\n\t\treturn false\n\t}\n\treturn n.LoopHead.ID() == n.ID()\n}", "func isSameNode(a, b *NodeInfo) bool {\n\n\tif a.Addr == b.Addr { //do not check ID now\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (nue NodeUpEvent) AsNodeEvent() (*NodeEvent, bool) {\n\treturn nil, false\n}", "func (this *Tidy) InputXml(val bool) (bool, error) {\n\treturn this.optSetBool(C.TidyXmlTags, cBool(val))\n}" ]
[ "0.77378595", "0.7563745", "0.7193405", "0.6881346", "0.6374417", "0.6312678", "0.6054738", "0.5895529", "0.5886826", "0.5841217", "0.58025974", "0.5732391", "0.56517136", "0.562411", "0.56054157", "0.5595582", "0.5592241", "0.5553411", "0.5546443", "0.5511153", "0.54900104", "0.5482221", "0.5408648", "0.5393594", "0.53390646", "0.5333446", "0.5323601", "0.5312799", "0.5305786", "0.5279525", "0.5242083", "0.52134377", "0.5212066", "0.520929", "0.5192215", "0.5187956", "0.5172169", "0.5157659", "0.5101167", "0.506657", "0.5059025", "0.5054485", "0.5036206", "0.5032264", "0.50320244", "0.5000152", "0.4998978", "0.49768183", "0.49651062", "0.49634498", "0.49634308", "0.4945864", "0.49382272", "0.49298707", "0.49159977", "0.49128145", "0.4896858", "0.48801154", "0.486493", "0.48588097", "0.48558578", "0.4854787", "0.48206455", "0.4819746", "0.4802041", "0.478786", "0.47515574", "0.47472492", "0.4743657", "0.47380638", "0.47370914", "0.47344843", "0.47078487", "0.4701962", "0.4697919", "0.4694275", "0.46917346", "0.4689967", "0.46856937", "0.46741766", "0.46662027", "0.46626207", "0.46622074", "0.4662107", "0.4661505", "0.4654468", "0.464783", "0.46476173", "0.46324772", "0.46289554", "0.46268183", "0.46266112", "0.4612238", "0.46089977", "0.4596838", "0.45893022", "0.45876837", "0.45837545", "0.4583303", "0.45756897" ]
0.87470484
0
InStream returns the internal MsgStream
InStream возвращает внутренний MsgStream
func (inNode *InputNode) InStream() msgstream.MsgStream { return inNode.inStream }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *eventSourceMessageReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *signedExchangeReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (s *Chan) In() chan []byte {\n\treturn s.inMsgChan\n}", "func In(stream pb.Chat_StreamClient, ch chan pb.Message) {\n\tfor {\n\t\tmsg, _ := stream.Recv()\n\t\tch <- *msg\n\t}\n}", "func (c *dataReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (cli *ExecCli) In() *streams.In {\n\treturn cli.in\n}", "func (c *webSocketWillSendHandshakeRequestClient) GetStream() rpcc.Stream { return c.Stream }", "func (s *Samil) read() (message, error) {\n\tmsg, ok := <-s.in\n\tif !ok {\n\t\treturn message{}, s.closed\n\t}\n\treturn msg, nil\n}", "func (c *requestWillBeSentClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *responseReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *requestWillBeSentExtraInfoClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *requestInterceptedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *subresourceWebBundleMetadataReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *webSocketHandshakeResponseReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *webSocketClosedClient) GetStream() rpcc.Stream { return c.Stream }", "func (p *Player) inStream() {\n\tdefer func() {\n\t\tp.ghub.destroyPlayer(p)\n\t\tp.conn.Close()\n\t}()\n\n\t//p.conn.SetPongHandler(func(string) error { p.conn.SetReadDeadline(time.Now().Add(pongWaitTime)); return nil })\n\n\tfor {\n\t\tvar data map[string]interface{}\n\t\terr := p.conn.ReadJSON(&data)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"err reading msg\")\n\t\t\tbreak\n\t\t}\n\n\t\t//update player position in central\n\t\tp.xPos = data[\"positionX\"].(float64)\n\t\tp.yPos = data[\"positionY\"].(float64)\n\n\t\tp.ghub.publish <- data\n\t}\n}", "func (c *webSocketFrameSentClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *responseReceivedExtraInfoClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *webSocketCreatedClient) GetStream() rpcc.Stream { return c.Stream }", "func (stdout *StdoutSink) In() chan<- interface{} {\n\treturn stdout.in\n}", "func (stdout *StdoutSink) In() chan<- interface{} {\n\treturn stdout.in\n}", "func (ws *WrappedStream) Stream() net.Stream {\n\treturn ws.stream\n}", "func (gi *Invoker) StreamRecv(param *common.Params) error {\n\t//gloryPkg := newGloryRequestPackage(\"\", param.MethodName, uint64(common.StreamSendPkg), param.Seq)\n\t//gloryPkg.Params = append(gloryPkg.Params, param.Value)\n\t//gloryPkg.Header.ChanOffset = param.ChanOffset\n\t//gloryPkg.Header.Seq = param.Seq\n\t//if err := gloryPkg.sendToConn(gi.gloryConnClient, gi.handler); err != nil {\n\t//\tlog.Error(\"StreamRecv: gloryPkg.sendToConn(gi.conn, gi.handler) err =\", err)\n\t//\treturn GloryErrorConnErr\n\t//}\n\treturn nil\n}", "func (c *webTransportClosedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *webTransportConnectionEstablishedClient) GetStream() rpcc.Stream { return c.Stream }", "func (s *MessengerDiffServerCallStub) RecvStream() interface {\n\tAdvance() bool\n\tValue() []string\n\tErr() error\n} {\n\treturn implMessengerDiffServerCallRecv{s}\n}", "func (c *webSocketFrameReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *webTransportCreatedClient) GetStream() rpcc.Stream { return c.Stream }", "func (ch *RingChannel) In() chan<- interface{} {\n\treturn ch.input\n}", "func (s *MessengerPushServerCallStub) RecvStream() interface {\n\tAdvance() bool\n\tValue() []byte\n\tErr() error\n} {\n\treturn implMessengerPushServerCallRecv{s}\n}", "func (hs *Handshake) OpenedStream(s p2p.Stream) {\n\n}", "func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) {\n\tp := ipath.New(path)\n\tunixfs := fs.coreAPI.Unixfs()\n\tnode, err := unixfs.Get(context.Background(), p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// node should be files.File\n\tfile, ok := node.(files.File)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"path is not a file: '%s'\", path)\n\t}\n\n\treturn file, nil\n}", "func (notifee *Notifee) OpenedStream(network.Network, network.Stream) {}", "func (c *subresourceWebBundleInnerResponseParsedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *Client) GetInMessage(from string, idx uint64) ([][]byte, error) {\n\tvar blockNum *big.Int\n\tif err := retry.Retry(func(attempt uint) error {\n\t\tvar err error\n\t\tblockNum, err = c.session.GetInMessage(from, idx)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"get in message\", \"err\", err.Error())\n\t\t}\n\t\treturn err\n\t}); err != nil {\n\t\tlogger.Error(\"retry error in GetInMessage\", \"err\", err.Error())\n\t}\n\n\treturn [][]byte{blockNum.Bytes()}, nil\n}", "func (c *loadingFailedClient) GetStream() rpcc.Stream { return c.Stream }", "func (h *hijackedIOStreamer) stream(ctx context.Context) error {\n\trestoreInput, err := h.setupInput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to setup input stream: %s\", err)\n\t}\n\n\tdefer restoreInput()\n\n\toutputDone := h.beginOutputStream(restoreInput)\n\tinputDone, detached := h.beginInputStream(restoreInput)\n\n\tselect {\n\tcase err := <-outputDone:\n\t\treturn err\n\tcase <-inputDone:\n\t\t// Input stream has closed.\n\t\tif h.outputStream != nil || h.errorStream != nil {\n\t\t\t// Wait for output to complete streaming.\n\t\t\tselect {\n\t\t\tcase err := <-outputDone:\n\t\t\t\treturn err\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase err := <-detached:\n\t\t// Got a detach key sequence.\n\t\treturn err\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func InMessage(messengerID, msg, stringBuffer string) (outServerMsg string, err error) {\n\tif msg == \"info\" {\n\t\toutServerMsg, err = controlsystemhome.GetInfoControlSystemHomeInterfaces()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tstr, errr := controlled.GetInfoControlledsString()\n\t\tif errr != nil {\n\t\t\terr = errr\n\t\t\treturn\n\t\t}\n\t\toutServerMsg += \"\\n\" + str\n\t\treturn\n\t}\n\n\toutServerMsg, err = commandrecord.UsedTextCommand(msg, stringBuffer)\n\treturn\n}", "func (t *Transport) stream(msg Message, stream *Stream, out []byte) (n int) {\n\tatomic.AddUint64(&t.nTxstream, 1)\n\tn = tag2cbor(tagCborPrefix, out) // prefix\n\tout[n] = 0xc7 // 0xc7 (stream msg, 0b110_00111 <tag,7>)\n\tn++ //\n\tn += t.framepkt(msg, stream, out[n:]) // packet\n\treturn n\n}", "func (c *webSocketFrameErrorClient) GetStream() rpcc.Stream { return c.Stream }", "func (pstFile *File) GetAttachmentInputStream(attachment Attachment, formatType string, encryptionType string) (HeapOnNodeInputStream, error) {\n\tattachmentInputStreamPropertyContextItem, err := FindPropertyContextItem(attachment.PropertyContext, 14081)\n\n\tif err != nil {\n\t\treturn HeapOnNodeInputStream{}, err\n\t}\n\n\tif attachmentInputStreamPropertyContextItem.IsExternalValueReference {\n\t\tattachmentInputStreamLocalDescriptor, err := FindLocalDescriptor(attachment.LocalDescriptors, attachmentInputStreamPropertyContextItem.ReferenceHNID, formatType)\n\n\t\tif err != nil {\n\t\t\treturn HeapOnNodeInputStream{}, err\n\t\t}\n\n\t\tattachmentInputStreamHeapOnNode, err := pstFile.NewHeapOnNodeFromLocalDescriptor(attachmentInputStreamLocalDescriptor, formatType, encryptionType)\n\n\t\tif err != nil {\n\t\t\treturn HeapOnNodeInputStream{}, err\n\t\t}\n\n\t\treturn attachmentInputStreamHeapOnNode.InputStream, nil\n\t} else {\n\t\t// TODO - Internal data is not encrypted.\n\t\t// TODO - We need to be able to have a Heap-on-Node input stream without a file offset but only deal with the data directly.\n\t\treturn HeapOnNodeInputStream{}, errors.New(\"internal attachment data is not implemented yet, please open an issue on GitHub\")\n\t}\n}", "func (p *Port) Stream() *Port {\n\treturn p.sub\n}", "func ReadStream(data types.Message, stream core.Stream) error {\n\treturn ReadStreamTimeout(data, stream, time.Second*30)\n}", "func (ctx *Context) in() unsafe.Pointer {\n\treturn unsafe.Pointer(&ctx.buf[headerInSize])\n}", "func (m Message) GetStreamAsgnReqID(f *field.StreamAsgnReqIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (n *ForNode) handleStreamMsg(msg StreamMsg) {\n\tif n.inChan == nil {\n\t\tn.inChan = make(chan Msg, msg.Len.Len())\n\t}\n\tif n.nodeType == nil {\n\t\tn.nodeType = &streamNodeType{-1, msg.Len, make(map[string]bool), false}\n\t}\n\n\ti := msg.Idx.String()\n\tn.subnodes[i] = n.body.Clone(n.globals)\n\tn.subnodes[i].ParentChans()[n.id] = n.inChan\n\tn.nodeToIdx[n.subnodes[i].ID()] = msg.Idx\n\tSetVarNodes(n.subnodes[i], n.name, msg.Data)\n\n\t// Start node if the body is not a loop,\n\t// or if there are less running nodes than the fanout.\n\tif nodeType, ok := n.nodeType.(*streamNodeType); ok {\n\t\tif !n.isLoop || nodeType.numCurrIdxs < n.fanout {\n\t\t\tnodeType.visitedNodes[i] = true\n\t\t\tstartNode(n.globals, n.subnodes[i])\n\t\t\tnodeType.numCurrIdxs++\n\t\t}\n\t}\n}", "func (c *trustTokenOperationDoneClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *loadingFinishedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *resourceChangedPriorityClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *reportingAPIEndpointsChangedForOriginClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *subresourceWebBundleMetadataErrorClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *subresourceWebBundleInnerResponseErrorClient) GetStream() rpcc.Stream { return c.Stream }", "func (m Message) StreamAsgnReqID() (*field.StreamAsgnReqIDField, quickfix.MessageRejectError) {\n\tf := &field.StreamAsgnReqIDField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (c *requestServedFromCacheClient) GetStream() rpcc.Stream { return c.Stream }", "func (me *Server) GetStream(appName string, instName string, name string) *Stream {\n\tme.mtx.RLock()\n\tdefer me.mtx.RUnlock()\n\n\tapp, ok := me.applications[appName]\n\tif !ok {\n\t\tapp = new(Application).Init(appName, me.logger, me.factory)\n\t\tme.applications[appName] = app\n\t}\n\n\treturn app.GetStream(instName, name)\n}", "func (s GrpcServer) MessageStream(streamServer pb.StreamService_MessageStreamServer) error {\n\tip := extractRemoteAddr(streamServer)\n\n\t_, cancel := context.WithCancel(context.Background())\n\tstreamWrapper := NewServerStreamWrapper(streamServer, cancel)\n\n\tconn, err := NewConnection(Address{Ip: ip}, uuid.New().String(), streamWrapper)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif s.connHandler != nil {\n\t\ts.connHandler(conn)\n\t}\n\treturn nil\n}", "func (r *IntCode) In() io.Reader { return r.in }", "func (c *reportingAPIReportUpdatedClient) GetStream() rpcc.Stream { return c.Stream }", "func (bn *BasicNotifiee) OpenedStream(n net.Network, s net.Stream) {\n\tglog.V(4).Infof(\"Notifiee - OpenedStream: %v - %v\", peer.IDHexEncode(s.Conn().LocalPeer()), peer.IDHexEncode(s.Conn().RemotePeer()))\n}", "func (ignore *IgnoreSink) In() chan<- interface{} {\n\treturn ignore.in\n}", "func (ignore *IgnoreSink) In() chan<- interface{} {\n\treturn ignore.in\n}", "func (f FFmpeg) Stream() (io.ReadCloser, error) {\n\t// Verify ffmpeg is running\n\tif !f.started {\n\t\treturn nil, ErrFFmpegNotStarted\n\t}\n\n\t// Return stream\n\treturn f.stream, nil\n}", "func (w *RecvWindow) Input(msg *protobuf.Message) error {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\toffset := int(msg.MessageNonce - w.messageNonce)\n\n\tif offset < 0 || offset >= w.size {\n\t\treturn errors.Errorf(\"Local message nonce is %d while received %d\", w.messageNonce, msg.MessageNonce)\n\t}\n\n\t*w.buffer.Index(offset) = msg\n\treturn nil\n}", "func (c *Conn) ReceiveStream(wireTimeout, idleTimeout time.Duration) (opcode uint, r io.Reader, err error) {\n\t_, opcode, final, err := c.readWithRetry(nil, idleTimeout)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\tif opcode == Continuation {\n\t\treturn 0, nil, c.SendClose(ProtocolError, \"anonymous continuation\")\n\t}\n\n\tswitch {\n\tcase final:\n\t\tr = readEOF{}\n\tcase opcode == Text:\n\t\tr = &textReader{\n\t\t\tconn: c,\n\t\t\twireTimeout: wireTimeout,\n\t\t}\n\tdefault:\n\t\tr = &messageReader{\n\t\t\tconn: c,\n\t\t\twireTimeout: wireTimeout,\n\t\t}\n\t}\n\treturn opcode, r, nil\n}", "func (c *reportingAPIReportAddedClient) GetStream() rpcc.Stream { return c.Stream }", "func (r *OperationReader) ReadStream(\n\ton templater.OnDataStream,\n\tstopCh <-chan struct{},\n) error {\n\treturn nil\n}", "func NewMockStreamInbound(ctrl *gomock.Controller) *MockStreamInbound {\n\tmock := &MockStreamInbound{ctrl: ctrl}\n\tmock.recorder = &MockStreamInboundMockRecorder{mock}\n\treturn mock\n}", "func (s *Yamux) OpenStream() (net.Conn, error) {\n\treturn s.session.OpenStream()\n}", "func (m *Mbox) Message() (io.ReadCloser, error) {\n\tif m.eof {\n\t\treturn nil, nil\n\t}\n\n\tpr, pw := io.Pipe()\n\n\tgo func() {\n\t\tfor {\n\t\t\teof := !m.scanner.Scan()\n\t\t\tif eof {\n\t\t\t\tm.eof = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tline := m.scanner.Text()\n\t\t\tif isFromLine(line) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif isEscapedFromLine(line) {\n\t\t\t\tline = line[1:] // unescape\n\t\t\t}\n\t\t\tio.WriteString(pw, line)\n\t\t\tio.WriteString(pw, \"\\r\\n\")\n\t\t}\n\t\tpw.Close()\n\t}()\n\treturn &readCloser{\n\t\tr: pr,\n\t\tm: m,\n\t}, nil\n}", "func (stream *VTGateStream) MessageStream(ks, shard string, keyRange *topodata.KeyRange, name string) (*sqltypes.Result, error) {\n\t// start message stream which send received message to the respChan\n\tgo stream.VTGateConn.MessageStream(stream.ctx, ks, shard, keyRange, name, func(s *sqltypes.Result) error {\n\t\tstream.respChan <- s\n\t\treturn nil\n\t})\n\t// wait for field details\n\treturn stream.Next()\n}", "func (msh *MockStreamHandler) GetStream(string, bool) (network.Stream, error) {\n\treturn nil, nil\n}", "func GetStream(aggregateType, aggregateID string) string {\n\treturn fmt.Sprintf(\"%s!%s\", aggregateType, aggregateID)\n}", "func (sp *SyncProtocol) createInboundReader(ws *WrappedStream) error {\n\n\t// create stan connection with random client id\n\tsc, err := NSSConnection(nuid.Next())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// launch the read loop, append received blocks to the local feed\n\tgo func() {\n\t\tdefer sc.Close()\n\t\tdefer ws.stream.Close()\n\t\tlog.Println(\"reader open for: \", string(ws.remotePeerID()))\n\t\ti := 0\n\t\tfor {\n\t\t\tb, err := receiveBlock(ws)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"read-block error, closing reader: \", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// log.Println(\"...got a message from: \", string(ws.remotePeerID()))\n\n\t\t\t// verify - check content against signature\n\t\t\tif !b.Verify() {\n\t\t\t\tlog.Printf(\"\\n\\nrecieved block failed verification %v\\n\\n\", b)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// log.Println(\"...received block is verified\")\n\n\t\t\t// validate by attempting to add to blockchain\n\t\t\tbc := GetBlockchain(b.Data.Context, b.Author)\n\t\t\tvalidBlock, err := bc.AddBlock(b)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"\\t\\t=== received invalid block ===\")\n\t\t\t\tb.Print()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// log.Println(\"\\t...received block is valid\")\n\n\t\t\t// if all ok publish to the feed\n\t\t\tmutex.Lock()\n\t\t\tfilterfeed_records++\n\t\t\tmutex.Unlock()\n\t\t\terr = sc.Publish(\"feed\", validBlock.Serialize())\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"unable to publish message to nss: \", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// log.Println(\"...inbound message committed to nss:feed\")\n\t\t\ti++\n\t\t\tlog.Printf(\"messages received from:\\t%s: %d\\n\", ws.remotePeerID(), i)\n\t\t\t// b.Print()\n\t\t}\n\t\t// on any errors return & close nats and stream connections\n\t\treturn\n\t}()\n\n\treturn nil\n}", "func (p *Port) ParentStream() *Port {\n\treturn p.parStr\n}", "func (c *subContext) openStream(ctx context.Context, epID epapi.ID, indCh chan<- indication.Indication) error {\n\tresponse, err := c.epClient.Get(ctx, epID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := c.conns.Connect(fmt.Sprintf(\"%s:%d\", response.IP, response.Port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := termination.NewClient(conn)\n\tresponseCh := make(chan e2tapi.StreamResponse)\n\trequestCh, err := client.Stream(ctx, responseCh)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequestCh <- e2tapi.StreamRequest{\n\t\tAppID: e2tapi.AppID(c.config.AppID),\n\t\tInstanceID: e2tapi.InstanceID(c.config.InstanceID),\n\t\tSubscriptionID: e2tapi.SubscriptionID(c.sub.ID),\n\t}\n\n\tfor response := range responseCh {\n\t\tindCh <- indication.Indication{\n\t\t\tEncodingType: encoding.Type(response.Header.EncodingType),\n\t\t\tPayload: indication.Payload{\n\t\t\t\tHeader: response.IndicationHeader,\n\t\t\t\tMessage: response.IndicationMessage,\n\t\t\t},\n\t\t}\n\t}\n\treturn nil\n}", "func (config *MessageConfiguration) AsIncoming() *IncomingMessageConfiguration {\n\treturn config.endpoint.createOrGetIncomingMessageConfig(config)\n}", "func (s *server) Stream(in *tt.Empty, stream tt.TamTam_StreamServer) error {\n\tch := make(chan []byte)\n\tctx := stream.Context()\n\tutil.AddBroadcastChannel(ctx, ch)\n\tdefer util.RemoveBroadcastChannel(ctx)\n\tdefer log.Info().Msg(\"Broadcast listener went away\")\n\tfor {\n\t\tselect {\n\t\tcase v := <-ch:\n\t\t\tlog.Debug().Msgf(\"Streaming %d bytes to subscriber\", len(v))\n\t\t\tif err := stream.Send(&tt.Message{Bytes: v}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (n *NotifyMail) In() chan<- M.Mail {\n\treturn n.sendChan\n}", "func (m Message) GetStreamAsgnReqType(f *field.StreamAsgnReqTypeField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (s *JudgePlayServerCallStub) RecvStream() interface {\n\tAdvance() bool\n\tValue() PlayerAction\n\tErr() error\n} {\n\treturn implJudgePlayServerCallRecv{s}\n}", "func (th *Throttler) In() chan<- interface{} {\n\treturn th.in\n}", "func (t testConn) NewStream(ctx context.Context) (network.Stream, error) { return nil, nil }", "func (inNode *InputNode) Operate(in []Msg) []Msg {\n\tmsgPack, ok := <-inNode.inStream.Chan()\n\tif !ok {\n\t\tlog.Warn(\"MsgStream closed\", zap.Any(\"input node\", inNode.Name()))\n\t\treturn []Msg{&MsgStreamMsg{\n\t\t\tisCloseMsg: true,\n\t\t}}\n\t}\n\n\t// TODO: add status\n\tif msgPack == nil {\n\t\treturn []Msg{}\n\t}\n\n\tsub := tsoutil.SubByNow(msgPack.EndTs)\n\tif inNode.role == typeutil.QueryNodeRole {\n\t\tmetrics.QueryNodeConsumerMsgCount.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tInc()\n\n\t\tmetrics.QueryNodeConsumeTimeTickLag.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tSet(float64(sub))\n\t}\n\n\tif inNode.role == typeutil.DataNodeRole {\n\t\tmetrics.DataNodeConsumeMsgCount.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tInc()\n\n\t\tmetrics.DataNodeConsumeTimeTickLag.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tSet(float64(sub))\n\t}\n\n\tvar spans []opentracing.Span\n\tfor _, msg := range msgPack.Msgs {\n\t\tsp, ctx := trace.StartSpanFromContext(msg.TraceCtx())\n\t\tsp.LogFields(oplog.String(\"input_node name\", inNode.Name()))\n\t\tspans = append(spans, sp)\n\t\tmsg.SetTraceCtx(ctx)\n\t}\n\n\tvar msgStreamMsg Msg = &MsgStreamMsg{\n\t\ttsMessages: msgPack.Msgs,\n\t\ttimestampMin: msgPack.BeginTs,\n\t\ttimestampMax: msgPack.EndTs,\n\t\tstartPositions: msgPack.StartPositions,\n\t\tendPositions: msgPack.EndPositions,\n\t}\n\n\tfor _, span := range spans {\n\t\tspan.Finish()\n\t}\n\n\t// TODO batch operate msg\n\treturn []Msg{msgStreamMsg}\n}", "func (i *InputInlineQueryResultSticker) GetInputMessageContent() (value InputMessageContentClass) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.InputMessageContent\n}", "func ReadFrom(io.Reader) (WireMessage, error) { return nil, nil }", "func (ctx *HijackResponse) BodyStream() (io.Reader, error) {\n\tres, err := ctx.req.Response()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res.Body, nil\n}", "func (c *Client) streamReader() {\n\tdefer func() {\n\t\tc.conn.Close()\n\t}()\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(readTimeout))\n\t// SetPongHandler sets the handler for pong messages received from the peer.\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(readTimeout)); return nil })\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t// feed message to command channel\n\t\tc.read <- message\n\t}\n}", "func (s *SRTInbound) Read(p []byte) (n int, err error) {\n\treturn s.reader.Read(p)\n}", "func ReadExtendedSquitterIn(data []byte) ExtendedSquitterIn {\n\tbits := (data[1] & 0x10) >> 4\n\treturn ExtendedSquitterIn(bits)\n}", "func (m *Manager) InputChannel() chan []byte {\n\treturn m.byteStream\n}", "func (c *DiskCache) GetStream(ctx context.Context, repo *gitalypb.Repository, req proto.Message) (_ io.ReadCloser, err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tc.missTotals.Inc()\n\t\t}\n\t}()\n\n\tc.requestTotals.Inc()\n\n\trespPath, err := c.KeyPath(ctx, repo, req)\n\tswitch {\n\tcase os.IsNotExist(err):\n\t\treturn nil, ErrReqNotFound\n\tcase err == nil:\n\t\tbreak\n\tdefault:\n\t\treturn nil, err\n\t}\n\n\tctxlogrus.Extract(ctx).\n\t\tWithField(\"stream_path\", respPath).\n\t\tInfo(\"getting stream\")\n\n\trespF, err := os.Open(respPath)\n\tswitch {\n\tcase os.IsNotExist(err):\n\t\treturn nil, ErrReqNotFound\n\tcase err == nil:\n\t\tbreak\n\tdefault:\n\t\treturn nil, err\n\t}\n\n\treturn instrumentedReadCloser{\n\t\tReadCloser: respF,\n\t\tcounter: c.bytesFetchedtotals,\n\t}, nil\n}", "func (o *out) Underlying() interface{} {\n\treturn o.stream\n}", "func (s *Session) Stream() error {\n\t// In parallel read from client, send to broker\n\t// and read from broker, send to client.\n\terrs := make(chan error, 2)\n\n\tgo s.stream(up, s.inbound, s.outbound, errs)\n\tgo s.stream(down, s.outbound, s.inbound, errs)\n\n\t// Handle whichever error happens first.\n\t// The other routine won't be blocked when writing\n\t// to the errors channel because it is buffered.\n\terr := <-errs\n\n\ts.handler.Disconnect(&s.Client)\n\treturn err\n}", "func (ssec *SSEClient) GetStream(uri string) error {\n\tssec.Lock()\n\tdefer ssec.Unlock()\n\tvar err error\n\tif ssec.url, err = url.Parse(uri); err != nil {\n\t\treturn errors.Wrap(err, \"error parsing URL\")\n\t}\n\tssec.wg.Add(1)\n\tgo ssec.process()\n\treturn err\n}", "func (p *Concatenator) In() *scipipe.InPort { return p.InPort(\"in\") }", "func NewStream(in io.Reader, out io.Writer) Stream {\r\n\treturn &plainStream{\r\n\t\tin: json.NewDecoder(in),\r\n\t\tout: out,\r\n\t}\r\n}", "func (s *Stream) Read(b []byte) (int, error) {\n\tlogf(logTypeConnection, \"Reading from stream %v\", s.Id())\n\tif len(s.in) == 0 {\n\t\treturn 0, ErrorWouldBlock\n\t}\n\tif s.in[0].offset > s.readOffset {\n\t\treturn 0, ErrorWouldBlock\n\t}\n\tn := copy(b, s.in[0].data)\n\tif n == len(s.in[0].data) {\n\t\ts.in = s.in[1:]\n\t}\n\ts.readOffset += uint64(n)\n\treturn n, nil\n}", "func (e *streamExecutor) Stream(stdin io.Reader, stdout, stderr io.Writer, tty bool) error {\n\tsupportedProtocols := []string{StreamProtocolV2Name, StreamProtocolV1Name}\n\tconn, protocol, err := e.Dial(supportedProtocols...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tvar streamer streamProtocolHandler\n\n\tswitch protocol {\n\tcase StreamProtocolV2Name:\n\t\tstreamer = &streamProtocolV2{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\tcase \"\":\n\t\tglog.V(4).Infof(\"The server did not negotiate a streaming protocol version. Falling back to %s\", StreamProtocolV1Name)\n\t\tfallthrough\n\tcase StreamProtocolV1Name:\n\t\tstreamer = &streamProtocolV1{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\t}\n\n\treturn streamer.stream(conn)\n}", "func (xmlmc *XmlmcInstStruct) GetServerStream() string {\n\treturn xmlmc.stream\n}", "func GetStreamInputIotHub(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *StreamInputIotHubState, opts ...pulumi.ResourceOption) (*StreamInputIotHub, error) {\n\tvar resource StreamInputIotHub\n\terr := ctx.ReadResource(\"azure:streamanalytics/streamInputIotHub:StreamInputIotHub\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}" ]
[ "0.6105474", "0.6063308", "0.58948004", "0.5838755", "0.58044165", "0.57779425", "0.57277787", "0.5700929", "0.5552331", "0.55458105", "0.5520131", "0.5516159", "0.54422444", "0.54403114", "0.54284227", "0.54207987", "0.5408762", "0.53644747", "0.5340302", "0.5325053", "0.5325053", "0.53247464", "0.5321217", "0.52575386", "0.52354014", "0.52224106", "0.52126163", "0.5172212", "0.5163436", "0.5150923", "0.5148562", "0.5114078", "0.5112218", "0.5092126", "0.50884616", "0.50753444", "0.50606996", "0.5058763", "0.505733", "0.50490916", "0.5018641", "0.50129336", "0.5009929", "0.49883994", "0.4986531", "0.49825215", "0.49734184", "0.49705797", "0.49658662", "0.4960334", "0.49450386", "0.49437663", "0.49423122", "0.4928599", "0.49259475", "0.49242207", "0.4893913", "0.4868547", "0.4862932", "0.48621282", "0.48621282", "0.48443067", "0.48439687", "0.4842013", "0.48394483", "0.4807161", "0.47923875", "0.4785159", "0.4746866", "0.47243607", "0.47226247", "0.47225076", "0.47016025", "0.46871614", "0.46806788", "0.46789685", "0.46692988", "0.46598193", "0.46379462", "0.46331838", "0.46320754", "0.4628068", "0.46272913", "0.46239993", "0.46224776", "0.4615471", "0.46138796", "0.4609737", "0.46095672", "0.46048075", "0.46031764", "0.4601651", "0.45989472", "0.45916656", "0.45866844", "0.45682937", "0.45562744", "0.4549144", "0.4543821", "0.45325306" ]
0.7173401
0
NewInputNode composes an InputNode with provided MsgStream, name and parameters
NewInputNode составляет InputNode с предоставленным MsgStream, именем и параметрами
func NewInputNode(inStream msgstream.MsgStream, nodeName string, maxQueueLength int32, maxParallelism int32, role string, nodeID int64, collectionID int64, dataType string) *InputNode { baseNode := BaseNode{} baseNode.SetMaxQueueLength(maxQueueLength) baseNode.SetMaxParallelism(maxParallelism) return &InputNode{ BaseNode: baseNode, inStream: inStream, name: nodeName, role: role, nodeID: nodeID, collectionID: collectionID, dataType: dataType, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewInput(Name string, Type string, Repr msgs.Representation, Chan string, Default msgs.Message) Input {\n\n\t// Validates if the message-type is registered\n\tif !msgs.IsMessageTypeRegistered(Type) {\n\t\terrorString := fmt.Sprintf(\"The '%s' message type has not been registered!\", Type)\n\t\tpanic(errorString)\n\t}\n\n\t// Validates if the representation format is supported\n\tif !msgs.DoesMessageTypeImplementsRepresentation(Type, Repr) {\n\t\terrorString := fmt.Sprintf(\"'%s' message-type does not implement codec for '%s' representation format\", Type, Repr)\n\t\tpanic(errorString)\n\t}\n\n\treturn Input{IO: IO{Name: Name, Type: Type, Representation: Repr, Channel: Chan, Message: Default}, DefaultMessage: Default}\n}", "func NewInput(\n\tcfg *common.Config,\n\toutlet channel.Connector,\n\tcontext input.Context,\n) (input.Input, error) {\n\n\tout, err := outlet(cfg, context.DynamicFields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tforwarder := harvester.NewForwarder(out)\n\n\tconfig := defaultConfig\n\terr = cfg.Unpack(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcb := func(data []byte, metadata inputsource.NetworkMetadata) {\n\t\tevent := createEvent(data, metadata)\n\t\tforwarder.Send(event)\n\t}\n\n\tsplitFunc := tcp.SplitFunc([]byte(config.LineDelimiter))\n\tif splitFunc == nil {\n\t\treturn nil, fmt.Errorf(\"unable to create splitFunc for delimiter %s\", config.LineDelimiter)\n\t}\n\n\tserver, err := tcp.New(&config.Config, splitFunc, cb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Input{\n\t\tserver: server,\n\t\tstarted: false,\n\t\toutlet: out,\n\t\tconfig: &config,\n\t\tlog: logp.NewLogger(\"tcp input\").With(\"address\", config.Config.Host),\n\t}, nil\n}", "func NewInput(input *Synapse) *Neuron {\n\treturn &Neuron{\n\t\tInputs: []*Synapse{input},\n\t\tOutputs: []*Synapse{},\n\t\tFunction: func(inputs, outputs []*Synapse) {\n\t\t\tfor _, s := range outputs {\n\t\t\t\ts.Value = inputs[0].Value\n\t\t\t}\n\t\t},\n\t}\n}", "func (r *ReactorGraph) CreateInput(value int) InputCell {\n\treturn &Node{value: value, dependencies: make([]*Node, 0)}\n}", "func (m *Master) NewInput(a *NewInputArgs, r *int) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\ts := m.slaves[a.ID]\n\tif s == nil {\n\t\treturn errors.New(\"unknown slave\")\n\t}\n\n\tart := Artifact{a.Data, a.Prio, false}\n\tif !m.corpus.add(art) {\n\t\treturn nil\n\t}\n\tm.lastInput = time.Now()\n\t// Queue the input for sending to every slave.\n\tfor _, s1 := range m.slaves {\n\t\ts1.pending = append(s1.pending, MasterInput{a.Data, a.Prio, execCorpus, true, s1 != s})\n\t}\n\n\treturn nil\n}", "func (w *Watcher) NewInput(p ProducerFunc) *Input {\n\tret := &Input{\n\t\tProducer: p,\n\t\tLogFunc: w.LogFunc,\n\t}\n\tw.Inputs = append(w.Inputs, ret)\n\treturn ret\n}", "func NewInput() inputT {\n\tcntr := ctr.Increment()\n\tt := inputT{\n\t\tName: fmt.Sprintf(\"input_%v\", cntr),\n\t\tType: \"text\",\n\t\tLabel: trl.S{\"en\": fmt.Sprintf(\"Label %v\", cntr), \"de\": fmt.Sprintf(\"Titel %v\", cntr)},\n\t\tDesc: trl.S{\"en\": \"Description\", \"de\": \"Beschreibung\"},\n\t}\n\treturn t\n}", "func (pub *Publisher) CreateInput(nodeHWID string, inputType types.InputType, instance string,\n\tsetCommandHandler func(input *types.InputDiscoveryMessage, sender string, value string)) *types.InputDiscoveryMessage {\n\tinput := pub.inputFromSetCommands.CreateInput(nodeHWID, inputType, instance, setCommandHandler)\n\treturn input\n}", "func (m *Manager) NewInput(conf linput.Config, pipelines ...processor.PipelineConstructorFunc) (input.Streamed, error) {\n\treturn bundle.AllInputs.Init(conf, m, pipelines...)\n}", "func (inv *ActionLocationNetworkCreateInvocation) NewInput() *ActionLocationNetworkCreateInput {\n\tinv.Input = &ActionLocationNetworkCreateInput{}\n\treturn inv.Input\n}", "func NewInputComponent(parent *Entity) *InputComponent {\n\tinputComponent := &InputComponent{\n\t\tID: \"input\",\n\t\tParent: parent,\n\t}\n\treturn inputComponent\n}", "func NewInput(uri string) (*Input, error) {\n\tdialer := websocket.Dialer{\n\t\tHandshakeTimeout: 10 * time.Second,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t\tNetDial: (&net.Dialer{\n\t\t\tTimeout: time.Second * 5,\n\t\t}).Dial,\n\t}\n\tws, resp, err := dialer.Dial(uri, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = resp.Body.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Input{ws: ws}, nil\n}", "func (inv *ActionExportCreateInvocation) NewInput() *ActionExportCreateInput {\n\tinv.Input = &ActionExportCreateInput{}\n\treturn inv.Input\n}", "func (inv *ActionVpsConfigCreateInvocation) NewInput() *ActionVpsConfigCreateInput {\n\tinv.Input = &ActionVpsConfigCreateInput{}\n\treturn inv.Input\n}", "func (tv *TV) createInput() (*Input, error) {\n\tmsg := Message{\n\t\tType: RequestMessageType,\n\t\tID: requestID(),\n\t\tURI: GetPointerInputSocketCommand,\n\t}\n\tres, err := tv.request(&msg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not make request: %v\", err)\n\t}\n\tvar socketPath string\n\tsocketPath = fmt.Sprintf(\"%s\", res.Payload[\"socketPath\"])\n\n\tinput, err := NewInput(socketPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not dial: %v\", err)\n\t}\n\treturn input, nil\n}", "func readInput(r io.Reader) Node {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdata = bytes.Trim(data, \"^$ \\n\") // remove extraneous symbols\n\tnode, i := parseSequence(data, 0)\n\tif i < len(data) {\n\t\tpanic(fmt.Sprintf(\"parse error at offset %d\", i))\n\t}\n\treturn node\n}", "func (x *fastReflection_Input) New() protoreflect.Message {\n\treturn new(fastReflection_Input)\n}", "func NewInput() *Input {\n\tq, _ := fetch.Parse(\".\")\n\treturn &Input{\n\t\tPath: q,\n\t\tConnection: make(Connection),\n\t\tquitChan: make(chan bool),\n\t}\n}", "func (inv *ActionUserSessionIndexInvocation) NewInput() *ActionUserSessionIndexInput {\n\tinv.Input = &ActionUserSessionIndexInput{}\n\treturn inv.Input\n}", "func (c *InputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewInput() *BeegoInput {\n\treturn &BeegoInput{\n\t\tpnames: make([]string, 0, maxParam),\n\t\tpvalues: make([]string, 0, maxParam),\n\t\tdata: make(map[interface{}]interface{}),\n\t}\n}", "func (a *Agent) CreateInput(name string) (telegraf.Input, error) {\n\tp, exists := inputs.Inputs[name]\n\tif exists {\n\t\treturn p(), nil\n\t}\n\treturn nil, fmt.Errorf(\"could not find input plugin with name: %s\", name)\n}", "func NewInput() *Input {\n\treturn &Input{NewLine(), 0}\n}", "func NewCfnInput(scope awscdk.Construct, id *string, props *CfnInputProps) CfnInput {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnInput{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_iotevents.CfnInput\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func NewInput(addr sdk.CUAddress, coins sdk.Coins) Input {\n\treturn Input{\n\t\tAddress: addr,\n\t\tCoins: coins,\n\t}\n}", "func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (r *reactor) CreateInput(v int) InputCell {\n\treturn &cell{reactor: r, value: v}\n}", "func (inv *ActionUserRequestRegistrationCreateInvocation) NewInput() *ActionUserRequestRegistrationCreateInput {\n\tinv.Input = &ActionUserRequestRegistrationCreateInput{}\n\treturn inv.Input\n}", "func NewInput(chartPath, releaseName, namespace string, values map[string]interface{}) renderer.Input {\n\treturn helmInput{\n\t\tchartPath: chartPath,\n\t\treleaseName: releaseName,\n\t\tnamespace: namespace,\n\t\tvalues: values,\n\t}\n}", "func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (pub *Publisher) CreateInputFromOutput(\n\tnodeHWID string, inputType types.InputType, instance string, outputAddress string,\n\thandler func(input *types.InputDiscoveryMessage, sender string, value string)) {\n\n\tinput := pub.inputFromOutputs.CreateInput(nodeHWID, inputType, instance, outputAddress, handler)\n\n\t_ = input\n}", "func NewInput() *Input {\n\treturn &Input{\n\t\tSamples: []*Sample{},\n\t}\n}", "func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (inv *ActionClusterSearchInvocation) NewInput() *ActionClusterSearchInput {\n\tinv.Input = &ActionClusterSearchInput{}\n\treturn inv.Input\n}", "func (t *OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Inputs) NewInput(Id string) (*OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Inputs_Input, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Input == nil {\n\t\tt.Input = make(map[string]*OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Inputs_Input)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Input[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Input\", key)\n\t}\n\n\tt.Input[key] = &OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Inputs_Input{\n\t\tId: &Id,\n\t}\n\n\treturn t.Input[key], nil\n}", "func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *schema) NewTransform(name string, input io.Reader, ctx *transformctx.Ctx) (Transform, error) {\n\tbr, err := ios.StripBOM(s.header.ParserSettings.WrapEncoding(input))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif ctx.InputName != name {\n\t\tctx.InputName = name\n\t}\n\tingester, err := s.handler.NewIngester(ctx, br)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// If caller already specified a way to do context aware error formatting, use it;\n\t// otherwise (vast majority cases), use the Ingester (which implements CtxAwareErr\n\t// interface) created by the schema handler.\n\tif ctx.CtxAwareErr == nil {\n\t\tctx.CtxAwareErr = ingester\n\t}\n\treturn &transform{ingester: ingester}, nil\n}", "func (inv *ActionUserTotpDeviceConfirmInvocation) NewInput() *ActionUserTotpDeviceConfirmInput {\n\tinv.Input = &ActionUserTotpDeviceConfirmInput{}\n\treturn inv.Input\n}", "func NewInputs(inputsCfg config.Inputs) *Inputs {\n\tinputs := Inputs{\n\t\tRW: *new(sync.RWMutex),\n\t\tMap: make(map[string]Input),\n\t}\n\n\tinputs.RW.Lock()\n\tdefer inputs.RW.Unlock()\n\n\tfor _, in := range inputsCfg {\n\t\tinputs.Map[in.Name] = NewInput(in.IO.Name, in.IO.Type, msgs.Representation(in.IO.Representation), in.IO.Channel, NewDefaultMessage(in.Type, in.Default))\n\t}\n\treturn &inputs\n}", "func (c *InputService10ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService22ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (n *Network) AddInputNode(node *NNode) {\n\tn.Inputs = append(n.Inputs, node)\n}", "func (c *InputService15ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewInput() *Input {\n\tinput := &Input{\n\t\tBlock: *NewBlock(),\n\t}\n\tinput.sizePolicyY = Minimum\n\tinput.SetFocused(true)\n\treturn input\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewInput(\n\tcfg *common.Config,\n\toutletFactory channel.Connector,\n\tcontext input.Context,\n) (input.Input, error) {\n\tlogger := logp.NewLogger(\"docker\")\n\n\tcfgwarn.Deprecate(\"8.0.0\", \"'docker' input deprecated. Use 'container' input instead.\")\n\n\t// Wrap log input with custom docker settings\n\tconfig := defaultConfig\n\tif err := cfg.Unpack(&config); err != nil {\n\t\treturn nil, errors.Wrap(err, \"reading docker input config\")\n\t}\n\n\t// Docker input should make sure that no callers should ever pass empty strings as container IDs\n\t// Hence we explicitly make sure that we catch such things and print stack traces in the event of\n\t// an invocation so that it can be fixed.\n\tvar ids []string\n\tfor _, containerID := range config.Containers.IDs {\n\t\tif containerID != \"\" {\n\t\t\tids = append(ids, containerID)\n\t\t} else {\n\t\t\tlogger.Error(\"Docker container ID can't be empty for Docker input config\")\n\t\t\tlogger.Debugw(\"Empty docker container ID was received\", logp.Stack(\"stacktrace\"))\n\t\t}\n\t}\n\n\tif len(ids) == 0 {\n\t\treturn nil, errors.New(\"Docker input requires at least one entry under 'containers.ids''\")\n\t}\n\n\tfor idx, containerID := range ids {\n\t\tcfg.SetString(\"paths\", idx, path.Join(config.Containers.Path, containerID, \"*.log\"))\n\t}\n\n\tif err := checkStream(config.Containers.Stream); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := cfg.SetString(\"docker-json.stream\", -1, config.Containers.Stream); err != nil {\n\t\treturn nil, errors.Wrap(err, \"update input config\")\n\t}\n\n\tif err := cfg.SetBool(\"docker-json.partial\", -1, config.Partial); err != nil {\n\t\treturn nil, errors.Wrap(err, \"update input config\")\n\t}\n\n\tif err := cfg.SetBool(\"docker-json.cri_flags\", -1, config.CRIFlags); err != nil {\n\t\treturn nil, errors.Wrap(err, \"update input config\")\n\t}\n\n\tif config.CRIForce {\n\t\tif err := cfg.SetString(\"docker-json.format\", -1, \"cri\"); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"update input config\")\n\t\t}\n\t}\n\n\t// Add stream to meta to ensure different state per stream\n\tif config.Containers.Stream != \"all\" {\n\t\tif context.Meta == nil {\n\t\t\tcontext.Meta = map[string]string{}\n\t\t}\n\t\tcontext.Meta[\"stream\"] = config.Containers.Stream\n\t}\n\n\treturn log.NewInput(cfg, outletFactory, context)\n}", "func (inv *ActionUserClusterResourceIndexInvocation) NewInput() *ActionUserClusterResourceIndexInput {\n\tinv.Input = &ActionUserClusterResourceIndexInput{}\n\treturn inv.Input\n}", "func NewInput(name string, frame, center bool, x, y int, w, h int, onChange func(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool) *Input {\n\tw--\n\th--\n\n\tif center {\n\t\tx = x - w/2\n\t\ty = y - h/2\n\t}\n\n\tif onChange == nil {\n\t\tonChange = func(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool { return true }\n\t}\n\n\treturn &Input{nil, TypeInput, name, \"\", frame, center, x, y, w, h, onChange}\n}", "func NewInput(path string) (*Path, error) {\n\tfi, err := fs.Stat(path)\n\tif err != nil {\n\t\t// log.Fatalln(err)\n\t\treturn nil, err\n\t}\n\n\tq := []string{}\n\tswitch mode := fi.Mode(); {\n\tcase mode.IsDir():\n\t\tfiles, err := afero.ReadDir(fs, path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t\t//\tlog.Fatalf(\"Couldn't get directory or file: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Found %d file(s) in %s\", len(files), path)\n\t\tfor _, f := range files {\n\t\t\tq = append(q, filepath.Join(path, f.Name()))\n\t\t}\n\tcase mode.IsRegular():\n\t\tq = append(q, path)\n\t}\n\n\treturn &Path{queue: q}, nil\n}", "func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService16ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService21ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (pub *Publisher) CreateInputFromHTTP(\n\tnodeHWID string, inputType types.InputType, instance string, url string, login string, password string, intervalSec int,\n\thandler func(input *types.InputDiscoveryMessage, sender string, value string)) {\n\n\tinput := pub.inputFromHTTP.CreateHTTPInput(\n\t\tnodeHWID, inputType, instance, url, login, password, intervalSec, handler)\n\t_ = input\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService17ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewFileInput(p string) File {\n\treturn &FileInput{Path: p}\n}", "func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (inv *ActionUserRequestChangeResolveInvocation) NewInput() *ActionUserRequestChangeResolveInput {\n\tinv.Input = &ActionUserRequestChangeResolveInput{}\n\treturn inv.Input\n}", "func (c *OutputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService15ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (inNode *InputNode) Operate(in []Msg) []Msg {\n\tmsgPack, ok := <-inNode.inStream.Chan()\n\tif !ok {\n\t\tlog.Warn(\"MsgStream closed\", zap.Any(\"input node\", inNode.Name()))\n\t\treturn []Msg{&MsgStreamMsg{\n\t\t\tisCloseMsg: true,\n\t\t}}\n\t}\n\n\t// TODO: add status\n\tif msgPack == nil {\n\t\treturn []Msg{}\n\t}\n\n\tsub := tsoutil.SubByNow(msgPack.EndTs)\n\tif inNode.role == typeutil.QueryNodeRole {\n\t\tmetrics.QueryNodeConsumerMsgCount.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tInc()\n\n\t\tmetrics.QueryNodeConsumeTimeTickLag.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tSet(float64(sub))\n\t}\n\n\tif inNode.role == typeutil.DataNodeRole {\n\t\tmetrics.DataNodeConsumeMsgCount.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tInc()\n\n\t\tmetrics.DataNodeConsumeTimeTickLag.\n\t\t\tWithLabelValues(fmt.Sprint(inNode.nodeID), inNode.dataType, fmt.Sprint(inNode.collectionID)).\n\t\t\tSet(float64(sub))\n\t}\n\n\tvar spans []opentracing.Span\n\tfor _, msg := range msgPack.Msgs {\n\t\tsp, ctx := trace.StartSpanFromContext(msg.TraceCtx())\n\t\tsp.LogFields(oplog.String(\"input_node name\", inNode.Name()))\n\t\tspans = append(spans, sp)\n\t\tmsg.SetTraceCtx(ctx)\n\t}\n\n\tvar msgStreamMsg Msg = &MsgStreamMsg{\n\t\ttsMessages: msgPack.Msgs,\n\t\ttimestampMin: msgPack.BeginTs,\n\t\ttimestampMax: msgPack.EndTs,\n\t\tstartPositions: msgPack.StartPositions,\n\t\tendPositions: msgPack.EndPositions,\n\t}\n\n\tfor _, span := range spans {\n\t\tspan.Finish()\n\t}\n\n\t// TODO batch operate msg\n\treturn []Msg{msgStreamMsg}\n}", "func newInputLoop(log zerolog.Logger, spec *koalja.TaskSpec, pod *corev1.Pod, executor Executor, snapshotService SnapshotService, statistics *tracking.TaskStatistics) (*inputLoop, error) {\n\tinputAddressMap := make(map[string]string)\n\tfor _, tis := range spec.Inputs {\n\t\tannKey := constants.CreateInputLinkAddressAnnotationName(tis.Name)\n\t\taddress := pod.GetAnnotations()[annKey]\n\t\tif address == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"No input address annotation found for input '%s'\", tis.Name)\n\t\t}\n\t\tinputAddressMap[tis.Name] = address\n\t}\n\treturn &inputLoop{\n\t\tlog: log,\n\t\tspec: spec,\n\t\tinputAddressMap: inputAddressMap,\n\t\tclientID: uniuri.New(),\n\t\texecQueue: make(chan *InputSnapshot),\n\t\texecutor: executor,\n\t\tsnapshotService: snapshotService,\n\t\tstatistics: statistics,\n\t}, nil\n}", "func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewInputFromBytes(bytes []byte) (*Input, int, error) {\r\n\tif len(bytes) < 36 {\r\n\t\treturn nil, 0, fmt.Errorf(\"input length too short < 36\")\r\n\t}\r\n\r\n\toffset := 36\r\n\tl, size := DecodeVarInt(bytes[offset:])\r\n\toffset += size\r\n\r\n\ttotalLength := offset + int(l) + 4 // 4 bytes for nSeq\r\n\r\n\tif len(bytes) < totalLength {\r\n\t\treturn nil, 0, fmt.Errorf(\"input length too short < 36 + script + 4\")\r\n\t}\r\n\r\n\treturn &Input{\r\n\t\tpreviousTxID: ReverseBytes(bytes[0:32]),\r\n\t\tPreviousTxOutIndex: binary.LittleEndian.Uint32(bytes[32:36]),\r\n\t\tSequenceNumber: binary.LittleEndian.Uint32(bytes[offset+int(l):]),\r\n\t\tUnlockingScript: bscript.NewFromBytes(bytes[offset : offset+int(l)]),\r\n\t}, totalLength, nil\r\n}", "func (inv *ActionIpAddressIndexInvocation) NewInput() *ActionIpAddressIndexInput {\n\tinv.Input = &ActionIpAddressIndexInput{}\n\treturn inv.Input\n}", "func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (inv *ActionMigrationPlanIndexInvocation) NewInput() *ActionMigrationPlanIndexInput {\n\tinv.Input = &ActionMigrationPlanIndexInput{}\n\treturn inv.Input\n}", "func (c *InputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (w *RecvWindow) Input(msg *protobuf.Message) error {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\toffset := int(msg.MessageNonce - w.messageNonce)\n\n\tif offset < 0 || offset >= w.size {\n\t\treturn errors.Errorf(\"Local message nonce is %d while received %d\", w.messageNonce, msg.MessageNonce)\n\t}\n\n\t*w.buffer.Index(offset) = msg\n\treturn nil\n}", "func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (inv *ActionMailTemplateTranslationUpdateInvocation) NewInput() *ActionMailTemplateTranslationUpdateInput {\n\tinv.Input = &ActionMailTemplateTranslationUpdateInput{}\n\treturn inv.Input\n}", "func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func newMessageNode(msg schema.Message, next *messageNode) *messageNode {\n\treturn &messageNode{\n\t\tmessage: msg,\n\t\tnext: next,\n\t}\n}", "func (c *OutputService14ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}" ]
[ "0.6755735", "0.6387063", "0.6107659", "0.6013483", "0.60084355", "0.5982119", "0.59718966", "0.5887658", "0.57997257", "0.57652515", "0.5739579", "0.56995016", "0.5677465", "0.55904806", "0.5589528", "0.5555853", "0.5499458", "0.5491909", "0.54152054", "0.540663", "0.5405652", "0.53939885", "0.53612036", "0.5337119", "0.53345764", "0.5334494", "0.53204215", "0.52846", "0.5283716", "0.52656794", "0.5261368", "0.525254", "0.525105", "0.52469724", "0.5226995", "0.5222072", "0.5222051", "0.5221401", "0.5216378", "0.52083623", "0.52005684", "0.51968914", "0.5193034", "0.51860005", "0.518284", "0.51813257", "0.5155211", "0.5149538", "0.5143879", "0.5136459", "0.5136459", "0.5134036", "0.5132896", "0.5122367", "0.51214755", "0.5116744", "0.5114746", "0.5113296", "0.5111071", "0.5111071", "0.50962114", "0.50962114", "0.50944364", "0.5076235", "0.5076235", "0.50655115", "0.50597274", "0.5059043", "0.5059043", "0.50473547", "0.5047235", "0.5042767", "0.5042767", "0.5034466", "0.50296783", "0.50296783", "0.50249267", "0.5012059", "0.49903706", "0.49895152", "0.4987488", "0.4987488", "0.49825394", "0.4978471", "0.49780816", "0.49780816", "0.4977321", "0.4977321", "0.4977148", "0.49759614", "0.4971477", "0.4971477", "0.49703795", "0.49591294", "0.49591294", "0.49569497", "0.4950586", "0.4950586", "0.4946964", "0.49375752" ]
0.7976249
0
ODataCount returns the number of rows from a table
ODataCount возвращает количество строк из таблицы
func ODataCount(db *sql.DB, table string) (int, error) { var count int selectStmt := fmt.Sprintf("SELECT count(*) FROM %s", pq.QuoteIdentifier(table)) row := db.QueryRow(selectStmt) err := row.Scan(&count) if err != nil { return 0, err } return count, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *RepositoryService) Count(rs app.RequestScope) (int64, error) {\n\treturn s.dao.Count(rs.DB())\n}", "func (eq *EntityQuery) Count(ctx context.Context) (int, error) {\n\tif err := eq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn eq.sqlCount(ctx)\n}", "func (s *NewsService) Count(rs app.RequestScope) (int, error) {\n\treturn s.dao.Count(rs)\n}", "func (mm *Model) Count(query interface{}) (int, error) {\n\treturn mm.executeInt(func(c CachedCollection) (int, error) {\n\t\treturn c.Count(query)\n\t})\n}", "func (ouq *OrgUnitQuery) Count(ctx context.Context) (int, error) {\n\tif err := ouq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn ouq.sqlCount(ctx)\n}", "func (q automodRuleDatumQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count automod_rule_data rows\")\n\t}\n\n\treturn count, nil\n}", "func (t *Table) Count(c string) (string, error) {\n\tp := \"https://%s/api/getCount.sjs?json&object=%s&countColumn=%s_KEY\"\n\tx := fmt.Sprintf(p, t.Host, t.Name, t.Name)\n\tif len(c) != 0 {\n\t\tx = x + \"&condition=\" + FixCrit(c)\n\t}\n\t_, body, err := t.Get(x)\n\t//The API does not return valid JSON for getCount.sjs.\n\t//The body is the count as a string.\n\treturn string(body), err\n}", "func (q oauthClientQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count oauth_clients rows\")\n\t}\n\n\treturn count, nil\n}", "func Count(db *sql.DB, table string) int {\n\tvar count int\n\tq := fmt.Sprintf(`SELECT COUNT(*) FROM %s`, pq.QuoteIdentifier(table))\n\terr := db.QueryRow(q).Scan(&count)\n\tbhlindex.Check(err)\n\treturn count\n}", "func (q kvstoreQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count kvstore rows\")\n\t}\n\n\treturn count, nil\n}", "func Count(collection string, query interface{}) (int, error) {\n\n\tsession, db, err := GetGlobalSessionFactory().GetSession()\n\tif err != nil {\n\t\tgrip.Errorf(\"error establishing db connection: %+v\", err)\n\n\t\treturn 0, err\n\t}\n\tdefer session.Close()\n\n\treturn db.C(collection).Find(query).Count()\n}", "func (q shelfQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count shelf rows\")\n\t}\n\n\treturn count, nil\n}", "func (q utxoQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count utxo rows\")\n\t}\n\n\treturn count, nil\n}", "func (c *Core) Count(ctx context.Context, filter QueryFilter) (int, error) {\n\treturn c.storer.Count(ctx, filter)\n}", "func (s *TransactionRows) Count() int {\n\t// return s.iter.\n\treturn 0\n}", "func (instance *DSInstance) Count(ctx context.Context, query *datastore.Query) (int, error) {\n\treturn instance.client.Count(ctx, query)\n}", "func (qs SysDBQuerySet) Count() (int, error) {\n\tvar count int\n\terr := qs.db.Count(&count).Error\n\treturn count, err\n}", "func (s *Store) Count(key storage.Key) (int, error) {\n\tkeys := util.BytesPrefix([]byte(key.Namespace() + separator))\n\titer := s.db.NewIterator(keys, nil)\n\n\tvar c int\n\tfor iter.Next() {\n\t\tc++\n\t}\n\n\titer.Release()\n\n\treturn c, iter.Error()\n}", "func (table *Table) Count(db DB, selector sqlbuilder.Selector, args ...interface{}) (int64, error) {\n\tif err := table.Open(); err != nil {\n\t\treturn 0, err\n\t}\n\tquery := selector.Columns(\"COUNT(*)\").From(table.Name).SQL()\n\trow := db.QueryRow(query, args...)\n\tvar count int64\n\tif err := row.Scan(&count); err != nil {\n\t\treturn 0, err\n\t}\n\treturn count, nil\n}", "func (dao *ArticleDAO) Count(rs app.RequestScope, filter string) (int, error) {\n\tvar count int\n\tq := rs.Tx().Select(\"COUNT(*)\").From(\"article\")\n\tif filter != \"\" {\n\t\tq.Where(dbx.Like(\"title\", filter))\n\t}\n\terr := q.Row(&count)\n\treturn count, err\n}", "func (s *Schema) Count(tableName string) IQuery {\n\treturn s.newQuery(tableName, \"count\")\n}", "func (q sourceQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"mdbmodels: failed to count sources rows\")\n\t}\n\n\treturn count, nil\n}", "func (c *Client) Count(entityName string, filters []stgml.Filter) (int64, error) {\n\tcollection := c.getCollection(entityName)\n\tfilterOption := filter(filters)\n\treturn collection.CountDocuments(ctx, filterOption)\n}", "func (kv *KV) Count() (i int) {\n\trows, err := kv.db.Query(\n\t\tfmt.Sprintf(\"SELECT COUNT(*) FROM %s LIMIT 1\", string(kv.table)),\n\t)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tif rows.Next() {\n\t\terr = rows.Scan(&i)\n\t}\n\treturn\n}", "func (q paymentObjectQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count payment_objects rows\")\n\t}\n\n\treturn count, nil\n}", "func (t *DbService) Count(request *CountRequest) (*CountResponse, error) {\n\trsp := &CountResponse{}\n\treturn rsp, t.client.Call(\"db\", \"Count\", request, rsp)\n}", "func (s *CategoryService) Count(rs app.RequestScope) (int, error) {\n\treturn s.dao.Count(rs)\n}", "func (us *UserService) Count(a AdminCriteria) (int, error) {\n\treturn us.Datasource.Count(a)\n}", "func (q repositoryQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count repositories rows\")\n\t}\n\n\treturn count, nil\n}", "func (tbl AssociationTable) Count(wh where.Expression) (count int64, err error) {\n\twhs, args := where.Where(wh, tbl.Dialect().Quoter())\n\treturn tbl.CountWhere(whs, args...)\n}", "func (q storeQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count stores rows\")\n\t}\n\n\treturn count, nil\n}", "func (c *Chef) Count() (int, error) {\n\trows, err := c.db.Query(fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE \"deleted\"=FALSE`, c.table))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer rows.Close()\n\n\tif !rows.Next() {\n\t\treturn 0, nil\n\t}\n\tvar n int\n\terr = rows.Scan(&n)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn n, nil\n}", "func (s *PersonStore) Count(q *PersonQuery) (int64, error) {\n\treturn s.Store.Count(q)\n}", "func (sd *SelectDataset) Count() (int64, error) {\n\treturn sd.CountContext(context.Background())\n}", "func (osq *OfflineSessionQuery) Count(ctx context.Context) (int, error) {\n\tif err := osq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn osq.sqlCount(ctx)\n}", "func (dataset *Dataset) Count() int {\r\n\treturn len(dataset.data)\r\n}", "func (kv *KV) Count() (i int) {\n\tkv.db.View(func(tx *buntdb.Tx) error {\n\t\terr := tx.Ascend(\"\", func(key, value string) bool {\n\t\t\ti++\n\t\t\treturn true\n\t\t})\n\t\treturn err\n\t})\n\treturn\n}", "func (q cmfTurntableQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count cmf_turntable rows\")\n\t}\n\n\treturn count, nil\n}", "func Count(mock sqlmock.Sqlmock, table string, err error, count uint32) {\n\tSelect(mock, table, []string{\"count(*)\"}, err, []driver.Value{count})\n}", "func (m *UserExtModel) Count(ctx context.Context, builders ...query.SQLBuilder) (int64, error) {\n\tsqlStr, params := m.query.\n\t\tMerge(builders...).\n\t\tTable(m.tableName).\n\t\tAppendCondition(m.applyScope()).\n\t\tResolveCount()\n\n\trows, err := m.db.QueryContext(ctx, sqlStr, params...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer rows.Close()\n\n\trows.Next()\n\tvar res int64\n\tif err := rows.Scan(&res); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn res, nil\n}", "func (q *DeferredQuery) Count() (int, error) {\n\topt := mopt.Count()\n\tfilter := q.Filter\n\tif filter == nil {\n\t\tfilter = bson.D{}\n\t}\n\tc, err := q.Coll.CountDocuments(nil, filter, opt)\n\treturn int(c), err\n}", "func (q illnessQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count illness rows\")\n\t}\n\n\treturn count, nil\n}", "func (s *EntityStorage) Count() int {\n\treturn s.count\n}", "func (store *EntryStore) Count() int64 {\n\tprop := store.db.GetProperty(\"rocksdb.estimate-num-keys\")\n\tc, _ := strconv.ParseInt(prop, 10, 64)\n\treturn c\n}", "func (q featureRelationshipQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"chado: failed to count feature_relationship rows\")\n\t}\n\n\treturn count, nil\n}", "func (p *MongodbProvider) Count() (total int) {\n\tvar err error\n\ttotal, err = p.c.Count()\n\tif err != nil {\n\t\tpanic(\"session/mgoSession: error counting records: \" + err.Error())\n\t}\n\treturn total\n}", "func (b *QueryBuilder) Count(_ bool, _ ...NodeI) uint {\n\treturn 0\n}", "func (h *handler) Count(ctx context.Context, params db.Params) int {\n\tbsonFilter := bson.M{}\n\tfor key, val := range params.Filter {\n\t\tbsonFilter[key] = val\n\t}\n\tcount, _ := h.getDatabase(params.Database).C(params.Collection).Find(bsonFilter).Count()\n\treturn count\n}", "func (s *SessionStore) Count(q *SessionQuery) (int64, error) {\n\treturn s.Store.Count(q)\n}", "func (q docQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count doc rows\")\n\t}\n\n\treturn count, nil\n}", "func GetCount(c *gin.Context) {\n\tstore := c.MustGet(\"store\").(*Store)\n\n\tc.JSON(http.StatusOK, store.Count())\n}", "func (rdq *ResultsDefinitionQuery) Count(ctx context.Context) (int, error) {\n\tif err := rdq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn rdq.sqlCount(ctx)\n}", "func (irq *InstanceRuntimeQuery) Count(ctx context.Context) (int, error) {\n\tif err := irq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn irq.sqlCount(ctx)\n}", "func Count(s Session, dbname string, collection string, query map[string]interface{}) (int, error) {\n\treturn s.DB(dbname).C(collection).Find(query).Count()\n}", "func (sch *schema) Count(filter []byte) int {\n\tvar filterQuery interface{}\n\tbson.UnmarshalJSON(filter, &filterQuery)\n\tquery := sch.Collection.Find(filterQuery).Sort(\"_id\")\n\n\tcount, _ := query.Count()\n\treturn count\n}", "func (q employeeQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count employee rows\")\n\t}\n\n\treturn count, nil\n}", "func (q currentChartDataMinutelyQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count current_chart_data_minutely rows\")\n\t}\n\n\treturn count, nil\n}", "func (c *Contract) Count() (count int64, err error) {\n\terr = DBConn.Table(c.TableName()).Count(&count).Error\n\treturn\n}", "func (q storestateQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"stellarcore: failed to count storestate rows\")\n\t}\n\n\treturn count, nil\n}", "func (q sourceQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"mdbmdbmodels: failed to count sources rows\")\n\t}\n\n\treturn count, nil\n}", "func (nimq *NetInterfaceModeQuery) Count(ctx context.Context) (int, error) {\n\tif err := nimq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn nimq.sqlCount(ctx)\n}", "func (q descriptionQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count descriptions rows\")\n\t}\n\n\treturn count, nil\n}", "func (p *Store) Len(ctx context.Context) (int, error) {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn 0, ctx.Err()\n\tdefault:\n\t}\n\n\tconst query = `\n\tSELECT\n\t\tCOUNT(*)\n\tFROM\n\t\tbeacon_details\n\tWHERE\n\t\tbeacon_id = :beacon_id`\n\n\tdata := struct {\n\t\tBeaconID int `db:\"beacon_id\"`\n\t}{\n\t\tBeaconID: p.beaconID,\n\t}\n\n\tvar ret struct {\n\t\tCount int `db:\"count\"`\n\t}\n\trows, err := p.db.NamedQueryContext(ctx, query, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer rows.Close()\n\n\tif !rows.Next() {\n\t\treturn 0, chainerrors.ErrNoBeaconStored\n\t}\n\n\terr = rows.StructScan(&ret)\n\treturn ret.Count, err\n}", "func (dao *VillageDAO) Count(rs app.RequestScope, districtID int) (int, error) {\n\tvar count int\n\terr := rs.Tx().Select(\"COUNT(*)\").Where(dbx.HashExp{\"district_id\": districtID}).From(\"village\").Row(&count)\n\treturn count, err\n}", "func (r repository) Count(ctx context.Context) (int, error) {\n\tvar count int\n\terr := r.db.With(ctx).Select(\"COUNT(*)\").From(\"urls\").Row(&count)\n\treturn count, err\n}", "func (gq *GoodsQuery) Count(ctx context.Context) (int, error) {\n\tif err := gq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn gq.gremlinCount(ctx)\n}", "func (m *UserModel) Count(ctx context.Context, builders ...query.SQLBuilder) (int64, error) {\n\tsqlStr, params := m.query.\n\t\tMerge(builders...).\n\t\tTable(m.tableName).\n\t\tAppendCondition(m.applyScope()).\n\t\tResolveCount()\n\n\trows, err := m.db.QueryContext(ctx, sqlStr, params...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer rows.Close()\n\n\trows.Next()\n\tvar res int64\n\tif err := rows.Scan(&res); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn res, nil\n}", "func Count(sql string, args ...interface{}) int64 {\n\tvar total int64\n\terr := QueryRow(sql, args...).Scan(&total)\n\tif err != nil {\n\t\tfmt.Errorf(\"%v\", err)\n\t\treturn 0\n\t}\n\treturn total\n}", "func (r *SmscSessionRepository) Count() (int, error) {\n\tcnt := 0\n\terr := app.BuntDBInMemory.View(func(tx *buntdb.Tx) error {\n\t\treturn tx.Ascend(SMSC_SESSION_PREFIX, func(key, value string) bool {\n\t\t\tcnt++\n\t\t\treturn true\n\t\t})\n\t})\n\treturn cnt, err\n}", "func (q Query) Count(ctx Context) (r int, err error) {\n\tnext := q.Iterate()\n\tfor {\n\t\t_, e := next(ctx)\n\t\tif e != nil {\n\t\t\tif IsNoRows(e) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn 0, e\n\t\t}\n\n\t\tr++\n\t}\n\n\treturn\n}", "func (o *PlatformsByPlatformNameAllOfData) GetCount() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Count\n}", "func (osq *OfflineSessionQuery) Count(ctx context.Context) (int, error) {\n\tctx = setContextOp(ctx, osq.ctx, \"Count\")\n\tif err := osq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn withInterceptors[int](ctx, osq, querierCount[*OfflineSessionQuery](), osq.inters)\n}", "func (dao *DistrictDAO) Count(rs app.RequestScope, regencyID int) (int, error) {\n\tvar count int\n\terr := rs.Tx().Select(\"COUNT(*)\").Where(dbx.HashExp{\"regency_id\": regencyID}).From(\"district\").Row(&count)\n\treturn count, err\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 (q apiKeyQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count api_keys rows\")\n\t}\n\n\treturn count, nil\n}", "func (fdq *FurnitureDetailQuery) Count(ctx context.Context) (int, error) {\n\tif err := fdq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn fdq.sqlCount(ctx)\n}", "func (q skinQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count skin rows\")\n\t}\n\n\treturn count, nil\n}", "func NumOfDataEntries(db *sql.DB, name string) (int, error) {\n\tscript := fmt.Sprintf(\"SELECT count(*) FROM %v;\", name)\n\tvar num int\n\terr := db.QueryRow(script).Scan(&num)\n\treturn num, err\n}", "func (qs ConstraintQuerySet) Count() (int, error) {\n\tvar count int\n\terr := qs.db.Count(&count).Error\n\treturn count, err\n}", "func (s *InMemoryDocumentSessionOperations) GetNumberOfEntitiesInUnitOfWork() int {\n\treturn len(s.documentsByEntity)\n}", "func (q customerQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count customers rows\")\n\t}\n\n\treturn count, nil\n}", "func (q holdenAtQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count HoldenAt rows\")\n\t}\n\n\treturn count, nil\n}", "func (ac *ArticleController) Count(w http.ResponseWriter, r *http.Request) {\n\tcount := models.ArticleCount()\n\tsendJSON(count, http.StatusOK, w)\n}", "func (session *Session) Count(bean ...interface{}) (int64, error) {\n\tdefer session.resetStatement()\n\tif session.IsAutoClose {\n\t\tdefer session.Close()\n\t}\n\n\tvar sqlStr string\n\tvar args []interface{}\n\tvar err error\n\tif session.Statement.RawSQL == \"\" {\n\t\tsqlStr, args, err = session.Statement.genCountSQL(bean...)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t} else {\n\t\tsqlStr = session.Statement.RawSQL\n\t\targs = session.Statement.RawParams\n\t}\n\n\tsession.queryPreprocess(&sqlStr, args...)\n\n\tvar total int64\n\tif session.IsAutoCommit {\n\t\terr = session.DB().QueryRow(sqlStr, args...).Scan(&total)\n\t} else {\n\t\terr = session.Tx.QueryRow(sqlStr, args...).Scan(&total)\n\t}\n\n\tif err == sql.ErrNoRows || err == nil {\n\t\treturn total, nil\n\t}\n\n\treturn 0, err\n}", "func (self PostgresDatabase) ArticleCount() (count int64) {\n\n err := self.conn.QueryRow(\"SELECT COUNT(message_id) FROM ArticlePosts\").Scan(&count)\n if err != nil {\n log.Println(\"failed to count articles\", err)\n }\n return \n}", "func (s PgPromotionStore) Count() int {\n\tvar n int\n\ts.db.Get(&n, \"SELECT COUNT(*) FROM public.promotion\")\n\treturn n\n}", "func (q tenantQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"dbmodel: failed to count tenants rows\")\n\t}\n\n\treturn count, nil\n}", "func (q notificationQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count notification rows\")\n\t}\n\n\treturn count, nil\n}", "func (liq *LineItemQuery) Count(ctx context.Context) (int, error) {\n\tif err := liq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn liq.sqlCount(ctx)\n}", "func (db *DB) Count() uint32 {\n\tdb.mu.RLock()\n\tdefer db.mu.RUnlock()\n\treturn db.index.count()\n}", "func (ob *Objects) TCount(_t orm.Trans) (num int, err error) {\n\tif _t == nil {\n\t\treturn 0, orm.ErrTransEmpty\n\t}\n\tt := _t.(*Trans)\n\tif t == nil {\n\t\treturn 0, orm.ErrTransInvalid\n\t}\n\treturn ob.countDo(t)\n}", "func (q phenotypepropQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"chado: failed to count phenotypeprop rows\")\n\t}\n\n\treturn count, nil\n}", "func (p *OrderRepo) Count(params param.Param) (count uint64, err error) {\n\tvar whereStr string\n\tif whereStr, err = params.ParseWhere(p.Cols); err != nil {\n\t\terr = limberr.Take(err, \"E1532288\").Custom(corerr.ValidationFailedErr).Build()\n\t\treturn\n\t}\n\n\terr = p.Engine.DB.Table(cafmodel.OrderTable).\n\t\tWhere(whereStr).\n\t\tCount(&count).Error\n\n\terr = p.dbError(err, \"E1539820\", cafmodel.Order{}, corterm.List)\n\treturn\n}", "func (q contentUnitDerivationQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"mdbmodels: failed to count content_unit_derivations rows\")\n\t}\n\n\treturn count, nil\n}", "func (q assetQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count asset rows\")\n\t}\n\n\treturn count, nil\n}", "func (q smallblogQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count smallblog rows\")\n\t}\n\n\treturn count, nil\n}", "func Count(db *Database, engine string, dbName string, tableName string) (int, error) {\n\tvar cnt int\n\tvar queryErr error\n\tquery := func(s *Session) {\n\t\tif engine != \"\" {\n\t\t\tif queryErr = s.SetEngine(context.Background(), engine); queryErr != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tcnt, queryErr = s.Count(context.Background(), dbName, tableName)\n\t}\n\n\terr := db.QueryInSession(query)\n\tif err != nil {\n\t\treturn cnt, err\n\t}\n\n\tif queryErr != nil {\n\t\treturn cnt, fmt.Errorf(\"failed to query table %s/%s: %v\", dbName, tableName, queryErr)\n\t}\n\n\treturn cnt, nil\n}", "func (q itemQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count items rows\")\n\t}\n\n\treturn count, nil\n}", "func (q nodeQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count node rows\")\n\t}\n\n\treturn count, nil\n}", "func (s *PetStore) Count(q *PetQuery) (int64, error) {\n\treturn s.Store.Count(q)\n}" ]
[ "0.65731376", "0.6423667", "0.6399858", "0.6366155", "0.6364464", "0.6363455", "0.63600063", "0.63275915", "0.6326546", "0.62999713", "0.6288543", "0.6251071", "0.6241342", "0.62159956", "0.6206949", "0.62037224", "0.6189948", "0.6167601", "0.61594486", "0.61513174", "0.6145387", "0.61421555", "0.61302495", "0.6125287", "0.61181146", "0.6116384", "0.6111478", "0.61114645", "0.60922176", "0.6092099", "0.60882896", "0.608553", "0.6085197", "0.6080378", "0.6078839", "0.6073212", "0.60582536", "0.60401195", "0.60321534", "0.60274", "0.60142577", "0.6012846", "0.6009238", "0.60080266", "0.60062337", "0.6004515", "0.60043234", "0.5991036", "0.59827846", "0.59818006", "0.5973273", "0.5970868", "0.5969371", "0.5963901", "0.59508556", "0.5942128", "0.5934807", "0.59324825", "0.59149957", "0.5913526", "0.5911103", "0.590835", "0.5905544", "0.5904632", "0.58963984", "0.5893553", "0.5887692", "0.5876999", "0.58749807", "0.5870834", "0.5863779", "0.58634615", "0.585287", "0.5845809", "0.58447987", "0.5839316", "0.5839304", "0.58344233", "0.58321154", "0.58268774", "0.5824897", "0.58227557", "0.5819977", "0.58183396", "0.5818015", "0.5805757", "0.5799755", "0.57972026", "0.57902586", "0.578889", "0.5787787", "0.5787692", "0.5786959", "0.57812643", "0.57808524", "0.57779115", "0.57755107", "0.5769499", "0.5769415", "0.57683414" ]
0.8465603
0
post handleDBGettokenizedcards receive and handle the request from client, access DB, and web
post handleDBGettokenizedcards получает и обрабатывает запрос от клиента, обращается к базе данных и вебу
func handleDBPostGettokenizedcards(w http.ResponseWriter, r *http.Request) { defer func() { db.Connection.Close(nil) }() var errorGeneral string var errorGeneralNbr string var requestData modelito.RequestTokenizedCards errorGeneral="" requestData, errorGeneral=obtainPostParmsGettokenizedcards(r,errorGeneral) //logicrequest_post.go ////////////////////////////////////////////////process business rules /// START if errorGeneral=="" { errorGeneral,errorGeneralNbr= ProcessGettokenizedcards(w , requestData) } /// END if errorGeneral!=""{ //send error response if any //prepare an error JSON Response, if any log.Print("CZ STEP Get the ERROR response JSON ready") /// START fieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr) ////////// write the response (ERROR) w.Header().Set("Content-Type", "application/json") w.Write(fieldDataBytesJson) if(err!=nil){ } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func handleDBGeneratetokenized(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var requestData modelito.RequestTokenized\n var errorGeneral string\n var errorGeneralNbr string\n \n errorGeneral=\"\"\n requestData,errorGeneral =obtainParmsGeneratetokenized(r,errorGeneral)\n\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGeneratetokenized(w , requestData)\n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleDBPostGeneratetokenized(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var requestData modelito.RequestTokenized\n var errorGeneral string\n var errorGeneralNbr string\n \n errorGeneral=\"\"\n\n\n requestData,errorGeneral =obtainPostParmsGeneratetokenized(r,errorGeneral) //logicrequest_post.go\n\n\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGeneratetokenized(w , requestData)\n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleRequests(dbgorm *gorm.DB) {\n\n\t//\n\t// lets instantiate some simple things here\n\t//\n\text := echo.New() // This is the externally supported login API. It only exposes SignIn and Sign out\n\tinternal := echo.New() // This is the externally supported login API. It only exposes SignIn and Sign out\n\n\tdb := DAO{DB: dbgorm}\n\n\text.Use(middleware.Recover())\n\text.Use(middleware.Logger())\n\n\tinternal.Use(middleware.Recover())\n\tinternal.Use(middleware.Logger())\n\n\t// This is the only path that can be taken for the external\n\t// There is sign in.\n\t// TODO: Signout\n\text.POST(\"/signin\", signin(db)) // This validates the user, generates a jwt token, and shoves it in a cookie\n\t// This is the only path that can be taken for the external\n\t// There is sign in.\n\t// TODO: Signout\n\text.POST(\"/signout\", signout()) // Lets invalidate the cookie\n\n\t//\n\t// Restricted group\n\t// This is an internal call made by all other microservices\n\t//\n\tv := internal.Group(\"/validate\")\n\t// Configure middleware with the custom claims type\n\tconfig := middleware.JWTConfig{\n\t\tClaims: &m.Claims{},\n\t\tSigningKey: []byte(\"my_secret_key\"),\n\t\tTokenLookup: \"cookie:jwt\",\n\t}\n\tv.Use(validatetoken(db)) // Lets validate the Token to make sure its valid and user is still valid\n\tv.Use(middleware.JWTWithConfig(config)) // If we are good, lets unpack it\n\tv.GET(\"\", GeneratePayload) // lets place the payload\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(2)\n\n\t// Lets fire up the internal first\n\tgo func() {\n\t\tif Properties.InternalMS.IsHTTPS {\n\t\t\tinternal.Logger.Fatal(internal.StartTLS(fmt.Sprintf(\":%d\", Properties.InternalMS.Port), \"./keys/server.crt\",\"./keys/server.key\"))\n\t\t} else {\n\t\t\tinternal.Logger.Fatal(internal.Start(fmt.Sprintf(\":%d\", Properties.InternalMS.Port)))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\t// Lets fire up the external now\n\tgo func() {\n\t\tif Properties.ExternalMS.IsHTTPS {\n\t\t\text.Logger.Fatal(ext.StartTLS(fmt.Sprintf(\":%d\", Properties.ExternalMS.Port), \"./keys/server.crt\",\"./keys/server.key\"))\n\t\t} else {\n\t\t\text.Logger.Fatal(ext.Start(fmt.Sprintf(\":%d\", Properties.ExternalMS.Port)))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n}", "func v4handleDBPostProcesspayment(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var errorGeneral string\n var errorGeneralNbr string\n var requestData modelito.RequestPayment\n \n errorGeneral=\"\"\nrequestData,errorGeneral =obtainPostParmsProcessPayment(r,errorGeneral) //logicrequest_post.go\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= v4ProcessProcessPayment(w , requestData) //logicbusiness.go \n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func HandleGetDatabaseConnectionState(adminMan *admin.Manager, modules *modules.Modules) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Create a context of execution\n\t\tctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)\n\t\tdefer cancel()\n\n\t\tvars := mux.Vars(r)\n\t\tdbAlias := vars[\"dbAlias\"]\n\n\t\tcrud := modules.DB()\n\t\tconnState := crud.GetConnectionState(ctx, dbAlias)\n\n\t\t_ = utils.SendResponse(w, http.StatusOK, model.Response{Result: connState})\n\t}\n}", "func v4handleDBProcesspayment(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n\n var errorGeneral string\n var\terrorGeneralNbr string\n var requestData modelito.RequestPayment\n errorGeneral=\"\"\nrequestData,errorGeneral =obtainParmsProcessPayment(r,errorGeneral)\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= v4ProcessProcessPayment(w , requestData) //logicbusiness.go \n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func logicDBMysqlProcessDash01Grafica01(requestData modelito.RequestDash01Grafica01, errorGeneral string) ([]modelito.Card,string) {\n\t////////////////////////////////////////////////obtain parms in JSON\n //START \nvar resultCards []modelito.Card\nvar errCards error\n\n\t\t\t\t// START fetchFromDB\n\t\t\t\t var errdb error\n\t\t\t\t var db *sql.DB\n\t\t\t\t // Create connection string\n\t\t\t\t\tconnString := fmt.Sprintf(\"host=%s dbname=%s user=%s password=%s port=%d sslmode=disable\",\n\t\t\t\t\t\tConfig_DB_server,Config_DB_name, Config_DB_user, Config_DB_pass, Config_DB_port)\n\t\t\t\t\n\t\t\t\t if (connString !=\"si\"){\n\n }\n//\"mysql\", \"root:password1@tcp(127.0.0.1:3306)/test\"\n\n\t\t\t\t\t // Create connection pool\n//\t\t\t\t\tdb, errdb = sql.Open(\"postgres\", connString)\n//this use the values set up in the configuration.go\n log.Print(\"Usando para conectar : \" + Config_dbStringType)\n\t\t\t\t\tdb, errdb = sql.Open(Config_dbStringType, Config_connString)\n \n\n\t\t\t\t\tif errdb != nil {\n\t\t\t\t\t\tlog.Print(\"Error creating connection pool: \" + errdb.Error())\n\t\t\t\t\t\terrorGeneral=errdb.Error()\n\t\t\t\t\t}\n\t\t\t\t\t// Close the database connection pool after program executes\n\t\t\t\t\t defer db.Close()\n\t\t\t\t\tif errdb == nil {\n\t\t\t\t\t\tlog.Print(\"Connected!\\n\")\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\terrPing := db.Ping()\n\t\t\t\t\t\tif errPing != nil {\n\t\t\t\t\t\t log.Print(\"Error: Could not establish a connection with the database:\"+ errPing.Error())\n\t\t\t\t\t\t\t errorGeneral=errPing.Error()\n\t\t\t\t\t\t}else{\n\t\t\t\t\t log.Print(\"Ping ok!\\n\")\n//\t\t\t\t\t var misCards modelito.Card\n\t\t\t\t\t \n\t\t\t\t\t resultCards,errCards =modelito.GetCardsByCustomer(db,requestData.Dash0101reference)\n\t\t\t\t\t \t\t\t\t\t log.Print(\"regresa func getCardsByCustomer ok!\\n\")\n\t\t\t\t\t\t\tif errCards != nil {\n\t\t\t\t\t\t\t log.Print(\"Error: :\"+ errCards.Error())\n\t\t\t\t\t\t\t errorGeneral=errCards.Error()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvar cuantos int\n\t\t\t\t\t\t\tcuantos = 0\n\t\t\t\t \tfor _, d := range resultCards {\n\t\t\t\t \t\tlog.Print(\"el registor trae:\"+d.Token+\" \"+d.Bin)\n\t\t\t\t\t\t\t cuantos =1\n\t\t\t \t\t}\n\t\t\t\t\t\t\tif cuantos == 0 {\n\t\t\t\t\t\t\t log.Print(\"DB: records not found\")\n\t\t\t\t\t\t\t errorGeneral=\"Not cards found for the customer reference received\"\n\t\t\t\t\t\t\t}\t\t\n\n\t\t\t\t\t }\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t \n\t\t\t\t// END fetchFromDB\n \n //END\n \t return resultCards, errorGeneral\n }", "func (kvs *keyValueServer) handleRequest(req *Request) {\n\tvar request []string\n\trequest = kvs.parseRequest(req.input)\n\tif request[0] == \"get\" {\n\t\tclient := kvs.clienter[req.cid]\n\t\tkvs.getFromDB(request, client)\n\t}\n\tif request[0] == \"put\" {\n\t\tkvs.putIntoDB(request)\n\t}\n}", "func Db_access_list(w http.ResponseWriter, r *http.Request) {\n\n///\n/// show d.b. access list inf. on web\n///\n\n process3.Db_access_list(w , r )\n\n}", "func (s *Server) sqlHandler(w http.ResponseWriter, req *http.Request) {\n if(s.block) {\n time.Sleep(1000000* time.Second)\n }\n\n\tquery, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't read body: %s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\n\tif s.leader != s.listen {\n\n\t\tcs, errLeader := transport.Encode(s.leader)\n\t\t\n\t\tif errLeader != nil {\n\t\t\thttp.Error(w, \"Only the primary can service queries, but this is a secondary\", http.StatusBadRequest)\t\n\t\t\tlog.Printf(\"Leader ain't present?: %s\", errLeader)\n\t\t\treturn\n\t\t}\n\n\t\t//_, errLeaderHealthCheck := s.client.SafeGet(cs, \"/healthcheck\") \n\n //if errLeaderHealthCheck != nil {\n // http.Error(w, \"Primary is down\", http.StatusBadRequest)\t\n // return\n //}\n\n\t\tbody, errLResp := s.client.SafePost(cs, \"/sql\", bytes.NewBufferString(string(query)))\n\t\tif errLResp != nil {\n s.block = true\n http.Error(w, \"Can't forward request to primary, gotta block now\", http.StatusBadRequest)\t\n return \n\t//\t log.Printf(\"Didn't get reply from leader: %s\", errLResp)\n\t\t}\n\n formatted := fmt.Sprintf(\"%s\", body)\n resp := []byte(formatted)\n\n\t\tw.Write(resp)\n\t\treturn\n\n\t} else {\n\n\t\tlog.Debugf(\"Primary Received query: %#v\", string(query))\n\t\tresp, err := s.execute(query)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\tw.Write(resp)\n\t\treturn\n\t}\n}", "func handleRequest(payload Payload) (string, error) {\n action := payload.Action\n\tvar result = \"\"\n\tvar err error\n\n\tif action == \"create\" {\n\t\tresult, err = CreateToken(payload.UserID, payload.SecretName)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error: \" + err.Error())\n\t\t\treturn \"\", err\n\t\t}\n\t} else if action == \"verify\" {\n\t\tresult, err = VerifyToken(payload.TokenStr, payload.SecretName)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error: \" + err.Error())\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn result, err\n}", "func HandleGetPreparedQuery(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t_ = json.NewEncoder(w).Encode(map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)\n\t\tdefer cancel()\n\t\t// get project id and dbType from url\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\t\tdbAlias := \"\"\n\t\tdbAliasQuery, exists := r.URL.Query()[\"dbAlias\"]\n\t\tif exists {\n\t\t\tdbAlias = dbAliasQuery[0]\n\t\t}\n\t\tidQuery, exists := r.URL.Query()[\"id\"]\n\t\tid := \"\"\n\t\tif exists {\n\t\t\tid = idQuery[0]\n\t\t}\n\t\tresult, err := syncMan.GetPreparedQuery(ctx, projectID, dbAlias, id)\n\t\tif err != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t_ = json.NewEncoder(w).Encode(map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_ = json.NewEncoder(w).Encode(model.Response{Result: result})\n\t}\n}", "func DataRetrievalHandler(reader fcrserver.FCRServerRequestReader, writer fcrserver.FCRServerResponseWriter, request *fcrmessages.FCRReqMsg) error {\n\tlogging.Debug(\"Handle data retrieval\")\n\t// Get core structure\n\tc := core.GetSingleInstance()\n\tc.MsgSigningKeyLock.RLock()\n\tdefer c.MsgSigningKeyLock.RUnlock()\n\n\t// Message decoding\n\tnonce, senderID, offer, accountAddr, voucher, err := fcrmessages.DecodeDataRetrievalRequest(request)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in decoding payload: %v\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Verify signature\n\tif request.VerifyByID(senderID) != nil {\n\t\t// Verify by signing key\n\t\tgwInfo := c.PeerMgr.GetGWInfo(senderID)\n\t\tif gwInfo == nil {\n\t\t\t// Not found, try sync once\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil {\n\t\t\t\terr = fmt.Errorf(\"Error in obtaining information for gateway %v\", senderID)\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t\tif request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t// Try update\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil || request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t\terr = fmt.Errorf(\"Error in verifying request from gateway %v: %v\", senderID, err.Error())\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check payment\n\trefundVoucher := \"\"\n\treceived, lane, err := c.PaymentMgr.Receive(accountAddr, voucher)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in receiving voucher %v:\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tif lane != 1 {\n\t\terr = fmt.Errorf(\"Not correct lane received expect 1 got %v:\", lane)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\texpected := big.NewInt(0).Add(c.Settings.SearchPrice, offer.GetPrice())\n\tif received.Cmp(expected) < 0 {\n\t\t// Short payment\n\t\t// Refund money\n\t\tif received.Cmp(c.Settings.SearchPrice) <= 0 {\n\t\t\t// No refund\n\t\t} else {\n\t\t\tvar ierr error\n\t\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\t\tif ierr != nil {\n\t\t\t\t// This should never happen\n\t\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"Short payment received, expect %v got %v, refund voucher %v\", expected.String(), received.String(), refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Payment is fine, verify offer\n\tif offer.Verify(c.OfferSigningPubKey) != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer signature, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer merkle proof\n\tif offer.VerifyMerkleProof() != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer merkle proof, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer expiry\n\tif offer.HasExpired() {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Offer has expired, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Offer is verified. Respond\n\t// First get the tag\n\ttag := c.OfferMgr.GetTagByCID(offer.GetSubCID())\n\t// Second read the data\n\tdata, err := ioutil.ReadFile(filepath.Join(c.Settings.RetrievalDir, tag))\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in finding the content, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Third encoding response\n\tresponse, err := fcrmessages.EncodeDataRetrievalResponse(nonce, tag, data)\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in encoding the response, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tc.OfferMgr.IncrementCIDAccessCount(offer.GetSubCID())\n\n\treturn writer.Write(response, c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n}", "func handleRequests(cfg datastructures.Configuration, mgoClient *mgo.Session, redisClient *redis.Client) {\n\tm := func(ctx *fasthttp.RequestCtx) {\n\t\tif cfg.SSL.Enabled {\n\t\t\tlog.Debug(\"handleRequests | SSL is enabled!\")\n\t\t}\n\t\thttputils.SecureRequest(ctx, cfg.SSL.Enabled)\n\t\tctx.Response.Header.Set(\"AuthentiGo\", \"$v0.2.1\")\n\n\t\t// Avoid to print stats for the expvar handler\n\t\tif strings.Compare(string(ctx.Path()), \"/stats\") != 0 {\n\t\t\tlog.Info(\"\\n|REQUEST --> \", ctx, \" \\n|Headers: \", ctx.Request.Header.String(), \"| Body: \", string(ctx.PostBody()))\n\t\t}\n\n\t\tswitch string(ctx.Path()) {\n\t\tcase \"/middleware\":\n\t\t\tmiddleware(ctx, redisClient)\n\t\tcase \"/benchmark\":\n\t\t\tfastBenchmarkHTTP(ctx) // Benchmark API\n\t\tcase \"/auth/login\":\n\t\t\tAuthLoginWrapper(ctx, mgoClient, redisClient, cfg) // Login functionality [Test purpouse]\n\t\tcase \"/auth/register\":\n\t\t\tAuthRegisterWrapper(ctx, mgoClient, cfg) // Register an user into the DB [Test purpouse]\n\t\tcase \"/auth/delete\":\n\t\t\tDeleteCustomerHTTP(ctx, cfg.Mongo.Users.DB, cfg.Mongo.Users.Collection, redisClient, mgoClient)\n\t\tcase \"/auth/verify\":\n\t\t\tVerifyCookieFromRedisHTTP(ctx, redisClient) // Verify if an user is authorized to use the service\n\t\tcase \"/test/crypt\":\n\t\t\tCryptDataHTTPWrapper(ctx)\n\t\tcase \"/test/decrypt\":\n\t\t\tDecryptDataHTTPWrapper(ctx)\n\t\tcase \"/stats\":\n\t\t\texpvarhandler.ExpvarHandler(ctx)\n\t\tdefault:\n\t\t\t_, err := ctx.WriteString(\"The url \" + string(ctx.URI().RequestURI()) + string(ctx.QueryArgs().QueryString()) + \" does not exist :(\\n\")\n\t\t\tcommonutils.Check(err, \"handleRequests\")\n\t\t\tctx.Response.SetStatusCode(404)\n\t\t\tfastBenchmarkHTTP(ctx)\n\t\t}\n\t}\n\t// ==== GZIP HANDLER ====\n\t// The gzipHandler will serve a compress request only if the client request it with headers (Content-Type: gzip, deflate)\n\tgzipHandler := fasthttp.CompressHandlerLevel(m, fasthttp.CompressBestSpeed) // Compress data before sending (if requested by the client)\n\tlog.Info(\"HandleRequests | Binding services to @[\", cfg.Host, \":\", cfg.Port)\n\n\t// ==== SSL HANDLER + GZIP if requested ====\n\tif cfg.SSL.Enabled {\n\t\thttputils.ListAndServerSSL(cfg.Host, cfg.SSL.Path, cfg.SSL.Cert, cfg.SSL.Key, cfg.Port, gzipHandler)\n\t}\n\t// ==== Simple GZIP HANDLER ====\n\thttputils.ListAndServerGZIP(cfg.Host, cfg.Port, gzipHandler)\n\n\tlog.Trace(\"HandleRequests | STOP\")\n}", "func (requestHandler *RequestHandler) handler(request events.APIGatewayProxyRequest) {\n\t//Initialize DB if requestHandler.Db = nil\n\tif errResponse := requestHandler.InitializeDB(); errResponse != (structs.ErrorResponse{}) {\n\t\tlog.Fatalf(\"Could not connect to DB when creating AOD/AODICE/QOD/QODICE\")\n\t}\n\tyear, month, day := time.Now().Date()\n\ttoday := fmt.Sprintf(\"%d-%d-%d\", year, month, day)\n\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\tgo func() { defer wg.Done(); requestHandler.insertEnglishQOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertIcelandicQOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertEnglishAOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertIcelandicAOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertTopicsQOD(today) }()\n\twg.Wait()\n}", "func (s *Server) handleRequest(m *cloud.TokenRequest) (*cloud.TokenResponse, error) {\n\treq := request{m: m, ch: make(chan *response)}\n\tdefer close(req.ch)\n\ts.queue.queue <- req\n\tresp := <-req.ch\n\treturn resp.resp, resp.err\n}", "func handleGetAccess(tokens []string, kvs *keyValueServer){\n\t/*fmt.Printf(\"Processed get cmd %v %v\\n\", strings.Trim(tokens[0], \" \"),\n\t\tstrings.Trim(tokens[1], \" \"))\n\t*/\n\tres := string(kvs.kvstore.get(strings.Trim(tokens[1], \" \")))\n\tfor i := 0; i < kvs.conns_num; i++ {\n\t\tdataChan := kvs.conns_chans[i]\n\t\treply := fmt.Sprintf(\"%v,%v\\n\", strings.Trim(tokens[1], \" \"), res)\n\t\tdataChan <- reply\n\t}\n}", "func handleConnection(conn net.Conn) {\n\tencoder := json.NewEncoder(conn)\n\tdecoder := json.NewDecoder(conn)\n\n\tvar incomingMsg BackendPayload\n\t// recieveing the response from the backend through the json decoder\n\terr := decoder.Decode(&incomingMsg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tswitch incomingMsg.Mode { // choose function based on the mode sent by front end server\n\tcase \"getTasks\":\n\t\tgetTasks(encoder)\n\tcase \"createTask\":\n\t\tcreateTask(incomingMsg)\n\tcase \"updateTask\":\n\t\tupdateTask(incomingMsg)\n\tcase \"deleteTask\":\n\t\tdeleteTask(incomingMsg)\n\t}\n}", "func HandlerMessage(aResponseWriter http.ResponseWriter, aRequest *http.Request) {\n\taRequest.ParseForm()\n\n\tbody := aRequest.Form\n\tlog.Printf(\"aRequest.Form=%s\", body)\n\tbytesBody, err := ioutil.ReadAll(aRequest.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading body, err=%s\", err.Error())\n\t}\n\t//\tlog.Printf(\"bytesBody=%s\", string(bytesBody))\n\n\t//check Header Token\n\t//\theaderAuthentication := aRequest.Header.Get(STR_Authorization)\n\t//\tisValid, userId := DbIsTokenValid(headerAuthentication, nil)\n\t//\tlog.Printf(\"HandlerMessage, headerAuthentication=%s, isValid=%t, userId=%d\", headerAuthentication, isValid, userId)\n\t//\tif !isValid {\n\t//\t\tresult := new(objects.Result)\n\t//\t\tresult.ErrorMessage = STR_MSG_login\n\t//\t\tresult.ResultCode = http.StatusOK\n\t//\t\tServeResult(aResponseWriter, result, STR_template_result)\n\t//\t\treturn\n\t//\t}\n\n\treport := new(objects.Report)\n\tjson.Unmarshal(bytesBody, report)\n\tlog.Printf(\"HandlerMessage, report.ApiKey=%s, report.ClientId=%s, report.Message=%s, report.Sequence=%d, report.Time=%d\",\n\t\treport.ApiKey, report.ClientId, report.Message, report.Sequence, report.Time)\n\tvar isApiKeyValid = false\n\tif report.ApiKey != STR_EMPTY {\n\t\tisApiKeyValid, _ = IsApiKeyValid(report.ApiKey)\n\t}\n\tif !isApiKeyValid {\n\t\tresult := new(objects.Result)\n\t\tresult.ErrorMessage = STR_MSG_invalidapikey\n\t\tresult.ResultCode = http.StatusOK\n\t\tServeResult(aResponseWriter, result, STR_template_result)\n\t\treturn\n\t}\n\n\tDbAddReport(report.ApiKey, report.ClientId, report.Time, report.Sequence, report.Message, report.FilePath, nil)\n\n\tresult := new(objects.Result)\n\tresult.ErrorMessage = STR_EMPTY\n\tresult.ResultCode = http.StatusOK\n\tServeResult(aResponseWriter, result, STR_template_result)\n}", "func (h *Handler) serveAuthenticateDBUser(w http.ResponseWriter, r *http.Request) {}", "func doGet(cmd string, conn net.Conn, kvs *keyValueServer){\n\t//fmt.Printf(\"Processing a get request %v\\n\", cmd)\n\tkvs.dataChan <- cmd[:len(cmd) - 1]\n}", "func (sr *sapmReceiver) handleRequest(req *http.Request) error {\n\tsapm, err := sapmprotocol.ParseTraceV2Request(req)\n\t// errors processing the request should return http.StatusBadRequest\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := sr.obsrecv.StartTracesOp(req.Context())\n\n\ttd, err := jaeger.ProtoToTraces(sapm.Batches)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif sr.config.AccessTokenPassthrough {\n\t\tif accessToken := req.Header.Get(splunk.SFxAccessTokenHeader); accessToken != \"\" {\n\t\t\trSpans := td.ResourceSpans()\n\t\t\tfor i := 0; i < rSpans.Len(); i++ {\n\t\t\t\trSpan := rSpans.At(i)\n\t\t\t\tattrs := rSpan.Resource().Attributes()\n\t\t\t\tattrs.PutStr(splunk.SFxAccessTokenLabel, accessToken)\n\t\t\t}\n\t\t}\n\t}\n\n\t// pass the trace data to the next consumer\n\terr = sr.nextConsumer.ConsumeTraces(ctx, td)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error passing trace data to next consumer: %w\", err)\n\t}\n\n\tsr.obsrecv.EndTracesOp(ctx, \"protobuf\", td.SpanCount(), err)\n\treturn err\n}", "func cmdHandler(cmd string, db *sql.DB) (retVal int) {\n // cmd : the string of the user input\n // db : connection to the database\n\n cmd_tkn := strings.Split(strings.Trim(cmd, \"\\n\"), \" \") // tokenize command for easy parsing\n\n // check the balance of an account\n if cmd_tkn[0] == \"balance\" { // balance acctId\n if len(cmd_tkn) == 2 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n dispBalance(acctId, db)\n retVal = 0\n } else {\n dispError(\"Incorrect parameters supplied for balance request.\")\n }\n\n // deposit an amount into an account\n } else if cmd_tkn[0] == \"deposit\" { // deposit acctId amt interestRate\n if len(cmd_tkn) == 4 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n amt, _ := strconv.ParseFloat(cmd_tkn[2], 64)\n intRate, _ := strconv.ParseFloat(cmd_tkn[3], 64)\n retVal = deposit(acctId, db, amt, time.Now(), intRate)\n } else {\n dispError(\"Incorrect parameters supplied for deposit request.\")\n }\n\n // withdraw an amount from an account\n } else if cmd_tkn[0] == \"withdraw\" { // withdraw acctId amt\n if len(cmd_tkn) == 3 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n amt, _ := strconv.ParseFloat(cmd_tkn[2], 64)\n err := withdraw(acctId, db, amt, time.Now())\n if err != nil {\n dispError(err.Error())\n }\n } else {\n dispError(\"Incorrect parameters supplied for withdraw request.\")\n }\n\n // display the information on a transaction\n } else if cmd_tkn[0] == \"xtn\" { // xtn xtnId\n if len(cmd_tkn) == 2 {\n xtnId, _ := strconv.Atoi(cmd_tkn[1])\n dispXtn(xtnId, db)\n } else {\n dispError(\"Incorrect parameters supplied for deposit request.\")\n }\n\n // end the program\n } else if cmd_tkn[0] == \"exit\" || cmd_tkn[0] == \"quit\" {\n retVal = 1\n\n // handle incorrect inputs\n } else {\n dispError(\"Invalid command. Try again.\")\n }\n\n return\n}", "func TokenizeHandler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// get pan\n\t// tokenize\n\t// store in db\n\t// return token\n\n\treturn events.APIGatewayProxyResponse{\n\t\tBody: \"Tokenize\",\n\t\tStatusCode: 200,\n\t}, nil\n}", "func HandleRequest(query []byte, conn *DatabaseConnection) {\n\tlog.Printf(\"Handling raw query: %s\", query)\n\tlog.Printf(\"Parsing request...\")\n\trequest, err := grammar.ParseRequest(query)\n\tlog.Printf(\"Parsed request\")\n\tvar response grammar.Response\n\n\tif err != nil {\n\t\tlog.Printf(\"Error in request parsing! %s\", err.Error())\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_INVALID_QUERY\n\t\tresponse.Data = err.Error()\n\t\tconn.Write(grammar.GetBufferFromResponse(response))\n\t}\n\n\tswitch request.Type {\n\tcase grammar.AUTH_REQUEST:\n\t\t// AUTH {username} {password}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_AUTH_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in AUTH request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\t// bucketname := tokens[2]\n\t\tlog.Printf(\"Client wants to authenticate.<username>:<password> %s:%s\", username, password)\n\n\t\tauthRequest := AuthRequest{Username: username, Password: password, Conn: conn}\n\t\tresponse = processAuthRequest(authRequest)\n\tcase grammar.SET_REQUEST:\n\t\t// SET {key} {value} [ttl] [nooverride]\n\t\trequest.Type = grammar.SET_RESPONSE\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_SET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in SET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tvalue := request.RequestData[1]\n\t\tlog.Printf(\"Setting %s:%s\", key, value)\n\t\tsetRequest := SetRequest{Key: key, Value: value, Conn: conn}\n\t\tresponse = processSetRequest(setRequest)\n\n\tcase grammar.GET_REQUEST:\n\t\t// GET {key}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_GET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in GET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tlog.Printf(\"Client wants to get key '%s'\", key)\n\t\tgetRequest := GetRequest{Key: key, Conn: conn}\n\t\tresponse = processGetRequest(getRequest)\n\n\tcase grammar.DELETE_REQUEST:\n\t\t// DELETE {key}\n\t\tlog.Println(\"Client wants to delete a bucket/key\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_DELETE_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in DELETE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\t// TODO implement\n\tcase grammar.CREATE_BUCKET_REQUEST:\n\t\tlog.Println(\"Client wants to create a bucket\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_BUCKET_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE bucket request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketName := request.RequestData[0]\n\t\tcreateBucketRequest := CreateBucketRequest{BucketName: bucketName, Conn: conn}\n\n\t\tresponse = processCreateBucketRequest(createBucketRequest)\n\tcase grammar.CREATE_USER_REQUEST:\n\t\tlog.Printf(\"Client wants to create a user\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_USER_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE user request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\tcreateUserRequest := CreateUserRequest{Username: username, Password: password, Conn: conn}\n\n\t\tresponse = processCreateUserRequest(createUserRequest)\n\tcase grammar.USE_REQUEST:\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_USE_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in USE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketname := request.RequestData[0]\n\t\tif bucketname == SALTS_BUCKET || bucketname == USERS_BUCKET {\n\t\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNAUTHORIZED\n\t\t\tbreak\n\t\t}\n\n\t\tuseRequest := UseRequest{BucketName: bucketname, Conn: conn}\n\t\tresponse = processUseRequest(useRequest)\n\tdefault:\n\t\tlog.Printf(illegalRequestTemplate, request.Type)\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNKNOWN_COMMAND\n\t}\n\tif response.Status != 0 {\n\t\tlog.Printf(\"Error in request. status: %d\", response.Status)\n\t}\n\tconn.Write(grammar.GetBufferFromResponse(response))\n\tlog.Printf(\"Wrote buffer: %s to client\", grammar.GetBufferFromResponse(response))\n\n}", "func handleGetData(request []byte, bc *Blockchain) {\n\tvar buff bytes.Buffer\n\tvar payload getdata\n\n\tbuff.Write(request[commandLength:])\n\tdec := gob.NewDecoder(&buff)\n\terr := dec.Decode(&payload)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif payload.Type == \"block\" {\n\t\tblock, err := bc.GetBlock([]byte(payload.ID))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tsendBlock(payload.AddrFrom, &block)\n\t}\n\n\tif payload.Type == \"tx\" {\n\t\ttxID := hex.EncodeToString(payload.ID)\n\t\ttx := mempool[txID]\n\n\t\tsendTx(payload.AddrFrom, &tx)\n\t\t// delete(mempool, txID)\n\t}\n}", "func (httpServer *HttpServer) handleListRewardAmount(params interface{}, closeChan <-chan struct{}) (interface{}, *rpcservice.RPCError) {\n\tresult := httpServer.databaseService.ListRewardAmount()\n\treturn result, nil\n}", "func handler2(w http.ResponseWriter, r *http.Request) {\n\tmu.Lock()\n\tcount++\n\tmu.Unlock()\n\t//fmt.Fprintf(w, \"%s %s %s\\n\", r.Method, r.URL, r.Proto)\n\t//for k, v := range r.Header {\n\t//\tfmt.Fprintf(w, \"Header[%q] = %q\\n\", k, v)\n\t//}\n\t//fmt.Fprintf(w, \"Host = %q\\n\", r.Host)\n\t//fmt.Fprintf(w, \"RemoteAddr = %q\\n\", r.RemoteAddr)\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Print(err)\n\t}\n\ttitle := \"play,comments,danmu,favorites,coins\\n\"\n\tdealed := false\n\taid := \"\"\n\tplay := \"\"\n\tcomm := \"\"\n\tdanmu := \"\"\n\tfav := \"\"\n\tfor k, v := range r.Form {\n\t\tswitch k {\n\t\tcase \"aid\":\n\t\t\tdealed = true\n\t\t\taid = v[0]\n\t\t\t//fmt.Fprintf(w, \"Form[%s] = %s\\n\", k, v)\n\t\tcase \"play\":\n\t\t\tplay = v[0]\n\t\t\t//fmt.Fprintf(w, \"Form[%s] = %s\\n\", k, v)\n\t\tcase \"comm\":\n\t\t\tcomm = v[0]\n\t\t\t//fmt.Fprintf(w, \"Form[%s] = %s\\n\", k, v)\n\t\tcase \"danmu\":\n\t\t\tdanmu = v[0]\n\t\t\t//fmt.Fprintf(w, \"Form[%s] = %s\\n\", k, v)\n\t\tcase \"fav\":\n\t\t\tfav = v[0]\n\t\t\t//fmt.Fprintf(w, \"Form[%s] = %s\\n\", k, v)\n\t\t}\n\t}\n\tif aid != \"\" || (play != \"\" && comm != \"\" && danmu != \"\" && fav != \"\") {\n\t\tdealed = true\n\t}\n\tif !dealed {\n\t\tfmt.Fprintf(w, \"wrong request!\")\n\t} else {\n\t\ts := fmt.Sprintf(\"%s%s,%s,%s,%s,%s\\n\", title, play, comm, danmu, fav, \"1\")\n\t\tfname := \"t/\" + strconv.Itoa(count) + \".csv\"\n\t\tSave(fname, s)\n\n\t\tfmt.Fprintf(w, s)\n\n\t\tmu.Lock()\n\t\ttestData, err := base.ParseCSVToInstances(fname, true)\n\t\terrexit(err)\n\t\tpredictions, err2 := lr.Predict(testData)\n\t\terrexit(err2)\n\t\texpectedValue, _ := strconv.ParseFloat(base.GetClass(predictions, 0), 64)\n\t\tmu.Unlock()\n\t\tfmt.Fprintf(w, fmt.Sprintf(\"expected value: %v\", expectedValue))\n\t}\n}", "func Handle(req []byte) string {\n\tvar database db.Database\n\n\t// Piggy-back off the command line parsing\n\t// to get the database object.\n\tapp := cli.NewApp()\n\tapp.Flags = tasks.DatabaseFlags\n\n\tapp.Action = func(c *cli.Context) error {\n\t\t// Connect to the database, if we haven't already\n\t\tvar err error\n\t\tdatabase, err = tasks.CreateDatabase(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Let's get the database, if we need it\n\tif err := app.Run([]string{\"\"}); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Parse query string\n\tquery, err := url.ParseQuery(os.Getenv(\"Http_Query\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Setup the finder\n\tfinder := database.NewInfoFinder()\n\n\tif val, ok := query[\"superseded\"]; ok {\n\t\tsuperseded, err := strconv.ParseBool(val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.Superseded(superseded)\n\t}\n\n\tif _, ok := query[\"status\"]; ok {\n\t\tvar status cap.Status\n\t\tstatus.UnmarshalString(query[\"status\"][0])\n\t\tfinder = finder.Status(status)\n\t}\n\n\tif _, ok := query[\"message_type\"]; ok {\n\t\tvar messageType cap.MessageType\n\t\tmessageType.UnmarshalString(query[\"message_type\"][0])\n\t\tfinder = finder.MessageType(messageType)\n\t}\n\n\tif _, ok := query[\"scope\"]; ok {\n\t\tvar scope cap.Scope\n\t\tscope.UnmarshalString(query[\"scope\"][0])\n\t\tfinder = finder.Scope(scope)\n\t}\n\n\tif _, ok := query[\"language\"]; ok {\n\t\tfinder = finder.Language(query[\"language\"][0])\n\t}\n\n\tif _, ok := query[\"certainty\"]; ok {\n\t\tvar certainty cap.Certainty\n\t\tcertainty.UnmarshalString(query[\"certainty\"][0])\n\t\tfinder = finder.Certainty(certainty)\n\t}\n\n\tif _, ok := query[\"urgency\"]; ok {\n\t\tvar urgency cap.Urgency\n\t\turgency.UnmarshalString(query[\"urgency\"][0])\n\t\tfinder = finder.Urgency(urgency)\n\t}\n\n\tif _, ok := query[\"severity\"]; ok {\n\t\tvar severity cap.Severity\n\t\tseverity.UnmarshalString(query[\"severity\"][0])\n\t\tfinder = finder.Severity(severity)\n\t}\n\n\tif _, ok := query[\"headline\"]; ok {\n\t\tfinder = finder.Headline(query[\"headline\"][0])\n\t}\n\n\tif _, ok := query[\"description\"]; ok {\n\t\tfinder = finder.Description(query[\"description\"][0])\n\t}\n\n\tif _, ok := query[\"instruction\"]; ok {\n\t\tfinder = finder.Instruction(query[\"instruction\"][0])\n\t}\n\n\tif val, ok := query[\"effective_gte\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.EffectiveGte(t)\n\t}\n\n\tif val, ok := query[\"effective_gt\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.EffectiveGt(t)\n\t}\n\n\tif val, ok := query[\"effective_lte\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.EffectiveLte(t)\n\t}\n\n\tif val, ok := query[\"effective_lt\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.EffectiveLt(t)\n\t}\n\n\tif val, ok := query[\"expires_gte\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.ExpiresGte(t)\n\t}\n\n\tif val, ok := query[\"expires_gt\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.ExpiresGt(t)\n\t}\n\n\tif val, ok := query[\"expires_lte\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.ExpiresLte(t)\n\t}\n\n\tif val, ok := query[\"expires_lt\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.ExpiresLt(t)\n\t}\n\n\tif val, ok := query[\"onset_gte\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.OnsetGte(t)\n\t}\n\n\tif val, ok := query[\"onset_gt\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.OnsetGt(t)\n\t}\n\n\tif val, ok := query[\"onset_lte\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.OnsetLte(t)\n\t}\n\n\tif val, ok := query[\"onset_lt\"]; ok {\n\t\tt, err := time.Parse(time.RFC3339, val[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.OnsetLt(t)\n\t}\n\n\tif _, ok := query[\"area\"]; ok {\n\t\tfinder = finder.Area(query[\"area\"][0])\n\t}\n\n\tif _, ok := query[\"point\"]; ok {\n\t\tstr := strings.Split(query[\"point\"][0], \",\")\n\n\t\tlat, err := strconv.ParseFloat(str[0], 64)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tlon, err := strconv.ParseFloat(str[1], 64)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfinder = finder.Point(lat, lon)\n\t}\n\n\tif _, ok := query[\"from\"]; ok {\n\t\tfrom, err := strconv.Atoi(query[\"from\"][0])\n\t\tif err == nil {\n\t\t\tfinder = finder.Start(from)\n\t\t}\n\t}\n\n\tif _, ok := query[\"size\"]; ok {\n\t\tsize, err := strconv.Atoi(query[\"size\"][0])\n\t\tif err == nil {\n\t\t\tfinder = finder.Count(size)\n\t\t}\n\t}\n\n\tif _, ok := query[\"sort\"]; ok {\n\t\tfinder = finder.Sort(query[\"sort\"][0])\n\t}\n\n\tres, err := finder.Find()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tb, err := json.Marshal(&res)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn string(b)\n}", "func HandleMemo(w http.ResponseWriter, req *http.Request, body string) {\n\n\tvar tokens = strings.Split(body, \".\")\n\tvar lastToken = (tokens[len(tokens)-1])\n\tif len(strings.Split(lastToken, \":\")) < 2 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\te := map[string]string{\"message\": \"Please Provide The Authorization Key as loggedin_id\"}\n\t\tjson.NewEncoder(w).Encode(e)\n\t\treturn\n\t}\n\t\n\tif strings.Split(lastToken, \":\")[0] != \"loggedin_id\" || strings.Split(lastToken, \":\")[1] == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\te := map[string]string{\"message\": \"Please Provide The Authorization Key as loggedin_id\"}\n\t\tjson.NewEncoder(w).Encode(e)\n\t\treturn\n\t}\n\tvar idToken = strings.Split(lastToken, \":\")[1]\n\n\t// validate the request header\n\tif idToken == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\te := map[string]string{\"message\": \"Please Provide The Authorization Key\"}\n\t\tjson.NewEncoder(w).Encode(e)\n\t\treturn \n\t}\n\t// validate the database connection\n\tauth := idToken\n\tsession, err := mgo.Dial(\"mongodb://mahmoud.salem:123a456@ds145223.mlab.com:45223/personalassistant\")\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\te := map[string]string{\"message\": \"Internal Error\"}\n\t\tjson.NewEncoder(w).Encode(e)\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\n\t// validat the id\n\tusers := session.DB(\"personalassistant\").C(\"users\")\n\tfoundUser := User{}\n\terr = users.Find(bson.M{\"unique\": string(auth)}).One(&foundUser)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\te := map[string]string{\"message\": \"No Such an Authorization ID.\"}\n\t\tjson.NewEncoder(w).Encode(e)\n\t\treturn\n\t}\n\n\tvar newBody = \"\"\n\tfor i := 0; i < len(tokens)-1; i++ {\n\t\tif i == len(tokens)-2 {\n\t\t\tnewBody = newBody + tokens[i]\n\t\t} else {\n\t\t\tnewBody = newBody + tokens[i] + \".\"\n\t\t}\n\t\t}\n\n\tbody = newBody\n\tfmt.Println(body)\n\t//route to a handler based on the request\n\tif strings.Contains(body, \"make\") {\n\t\tMakeMemoHandler(w, req, body, auth)\n\t} else if strings.Contains(body, \"edit\") {\n\t\tEditMemoHandler(w, req, body, auth)\n\t} else if strings.Contains(body, \"delete\") {\n\t\tDeleteMemoHandler(w, req, body, auth)\n\t} else if strings.Contains(body, \"showAll\") {\n\t\tShowAllMemosHandler(w, req, body, auth)\n\t} else if strings.Contains(body, \"show\") {\n\t\tShowMemoHandler(w, req, body, auth)\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\te := map[string]string{\"message\": \"Not a valid instruction for Memo operations {make,edit,delete,showAll}\"}\n\t\tjson.NewEncoder(w).Encode(e)\n\t\treturn\n\t}\n\n}", "func (h *Handler) serveDBUsers(w http.ResponseWriter, r *http.Request) {}", "func PurchasedRewardsAPIHandler(response http.ResponseWriter, request *http.Request) {\n\tt := time.Now()\n\tlogRequest := t.Format(\"2006/01/02 15:04:05\") + \" | Request:\" + request.Method + \" | Endpoint: purchasedrewards | \" //Connect to database\n\tfmt.Println(logRequest)\n\tdb, e := sql.Open(\"mysql\", dbConnectionURL)\n\tif e != nil {\n\t\tfmt.Print(e)\n\t}\n\n\t//set mime type to JSON\n\tresponse.Header().Set(\"Content-type\", \"application/json\")\n\n\terr := request.ParseForm()\n\tif err != nil {\n\t\thttp.Error(response, fmt.Sprintf(\"error parsing url %v\", err), 500)\n\t}\n\n\t//can't define dynamic slice in golang\n\tvar result = make([]string, 1000)\n\n\tswitch request.Method {\n\tcase GET:\n\t\tGroupId := strings.Replace(request.URL.Path, \"/api/purchasedrewards/\", \"\", -1)\n\n\t\t//fmt.Println(GroupId)\n\t\tst, getErr := db.Prepare(\"select * from PurchasedRewards where GroupId=?\")\n\t\tif err != nil {\n\t\t\tfmt.Print(getErr)\n\t\t}\n\t\trows, getErr := st.Query(GroupId)\n\t\tif getErr != nil {\n\t\t\tfmt.Print(getErr)\n\t\t}\n\t\ti := 0\n\t\tfor rows.Next() {\n\t\t\tvar RequestId int\n\t\t\tvar GroupId int\n\t\t\tvar RewardName string\n\t\t\tvar PointCost int\n\t\t\tvar RewardDescription string\n\t\t\tvar RewardedUser string\n\n\t\t\tgetErr := rows.Scan(&RequestId, &GroupId, &RewardName, &PointCost, &RewardDescription, &RewardedUser)\n\t\t\treward := &PurchasedReward{RequestId: RequestId, GroupId: GroupId, RewardName: RewardName, PointCost: PointCost, RewardDescription: RewardDescription, RewardedUser: RewardedUser}\n\t\t\tb, getErr := json.Marshal(reward)\n\t\t\tif getErr != nil {\n\t\t\t\tfmt.Println(getErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresult[i] = fmt.Sprintf(\"%s\", string(b))\n\t\t\ti++\n\t\t}\n\t\tresult = result[:i]\n\n\tcase POST:\n\n\t\tGroupId := request.PostFormValue(\"GroupId\")\n\t\tRewardName := request.PostFormValue(\"RewardName\")\n\t\tPointCost := request.PostFormValue(\"PointCost\")\n\t\tRewardDescription := request.PostFormValue(\"RewardDescription\")\n\t\tRewardedUser := request.PostFormValue(\"RewardedUser\")\n\n\t\tvar UserBalance int\n\t\tuserBalanceQueryErr := db.QueryRow(\"SELECT TotalPoints FROM `Points` WHERE `EmailAddress`=? AND `GroupId`=?\", RewardedUser, GroupId).Scan(&UserBalance)\n\t\tswitch {\n\t\tcase userBalanceQueryErr == sql.ErrNoRows:\n\t\t\tlog.Printf(logRequest, \"Unable to find user and group: \\n\", RewardedUser, GroupId)\n\t\tcase userBalanceQueryErr != nil:\n\t\t\tlog.Fatal(userBalanceQueryErr)\n\t\tdefault:\n\t\t}\n\t\tcostInt, err := strconv.Atoi(PointCost)\n\t\tif UserBalance > costInt {\n\t\t\t// Update user's points\n\t\t\tUserBalance -= costInt\n\n\t\t\t// Update database row\n\t\t\tstBalanceUpdate, postBalanceUpdateErr := db.Prepare(\"UPDATE Points SET `totalpoints`=?, `emailaddress`=? WHERE `groupid`=?\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Print(err)\n\t\t\t}\n\t\t\tresBalanceUpdate, postBalanceUpdateErr := stBalanceUpdate.Exec(UserBalance, RewardedUser, GroupId)\n\t\t\tif postBalanceUpdateErr != nil {\n\t\t\t\tfmt.Print(postBalanceUpdateErr)\n\t\t\t}\n\t\t\tif resBalanceUpdate != nil {\n\t\t\t\tresult[0] = \"Points Subtracted\"\n\t\t\t}\n\t\t\tresult = result[:1]\n\n\t\t\t// Add purchase to record\n\t\t\tstPurchase, postPurchaseErr := db.Prepare(\"INSERT INTO PurchasedRewards(`requestid`, `groupid`, `rewardname`, `pointcost`, `rewarddescription`, `rewardeduser`) VALUES(NULL,?,?,?,?,?)\")\n\t\t\tif postPurchaseErr != nil {\n\t\t\t\tfmt.Print(postPurchaseErr)\n\t\t\t}\n\t\t\tresPurchase, postPurchaseErr := stPurchase.Exec(GroupId, RewardName, PointCost, RewardDescription, RewardedUser)\n\t\t\tif postPurchaseErr != nil {\n\t\t\t\tfmt.Print(postPurchaseErr)\n\t\t\t}\n\n\t\t\tif resPurchase != nil {\n\t\t\t\tresult[0] = \"Purchase Added\"\n\t\t\t}\n\n\t\t\tresult = result[:1]\n\t\t} else {\n\t\t\tresult[0] = \"Purchase Rejected\"\n\t\t\tresult = result[:1]\n\t\t}\n\n\tcase PUT:\n\t\tRequestId := request.PostFormValue(\"RequestId\")\n\t\tGroupId := request.PostFormValue(\"GroupId\")\n\t\tRewardName := request.PostFormValue(\"RewardName\")\n\t\tPointCost := request.PostFormValue(\"PointCost\")\n\t\tRewardDescription := request.PostFormValue(\"RewardDescription\")\n\t\tRewardedUser := request.PostFormValue(\"RewardedUser\")\n\n\t\tst, putErr := db.Prepare(\"UPDATE PurchasedRewards SET GroupId=?, RewardName=?, PointCost=?, RewardDescription=?, RewardedUser=? WHERE RequestId=?\")\n\t\tif err != nil {\n\t\t\tfmt.Print(putErr)\n\t\t}\n\t\tres, putErr := st.Exec(GroupId, RewardName, PointCost, RewardDescription, RewardedUser, RequestId)\n\t\tif putErr != nil {\n\t\t\tfmt.Print(putErr)\n\t\t}\n\n\t\tif res != nil {\n\t\t\tresult[0] = \"Reward Modified\"\n\t\t}\n\t\tresult = result[:1]\n\n\tcase DELETE:\n\t\tRequestId := strings.Replace(request.URL.Path, \"/api/purchasedrewards/\", \"\", -1)\n\t\tst, deleteErr := db.Prepare(\"DELETE FROM PurchasedRewards where RequestId=?\")\n\t\tif deleteErr != nil {\n\t\t\tfmt.Print(deleteErr)\n\t\t}\n\t\tres, deleteErr := st.Exec(RequestId)\n\t\tif deleteErr != nil {\n\t\t\tfmt.Print(deleteErr)\n\t\t}\n\n\t\tif res != nil {\n\t\t\tresult[0] = \"Reward Deleted\"\n\t\t}\n\t\tresult = result[:1]\n\n\tdefault:\n\t}\n\n\tjson, err := json.Marshal(result)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t// Send the text diagnostics to the client. Clean backslashes from json\n\tfmt.Fprintf(response, \"%v\", CleanJSON(string(json)))\n\t//fmt.Fprintf(response, \" request.URL.Path '%v'\\n\", request.Method)\n\tdb.Close()\n}", "func AuthenticateClient(db *sql.DB, \n\t\treq *http.Request) (code int, dealerkey string, \n\t\tdealerid int, bsvkeyid int, err error) {\n\t//06.03.2013 naj - initialize some variables\n\t//08.06.2015 ghh - added ipaddress\n\tvar accountnumber, sentdealerkey, bsvkey, ipadd string\n\tcode = http.StatusOK\n\n\t//05.29.2013 naj - first we grab the AccountNumber and DealerKey\n\tif req.Method == \"GET\" {\n\t\t//first we need to grab the query string from the url so\n\t\t//that we can retrieve our variables\n\t\ttemp := req.URL.Query()\n\t\taccountnumber = temp.Get(\"accountnumber\")\n\t\tsentdealerkey = temp.Get(\"dealerkey\")\n\t\tbsvkey = temp.Get(\"bsvkey\")\n\t} else {\n\t\taccountnumber = req.FormValue(\"accountnumber\")\n\t\tsentdealerkey = req.FormValue(\"dealerkey\")\n\t\tbsvkey = req.FormValue(\"bsvkey\")\n\t}\n\n\n\t//if we don't get back a BSV key then we need to bail as\n\t//its a requirement. \n\tif bsvkey == \"\" {\n\t\terr = errors.New(\"Missing BSV Key In Package\")\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//if we didn't get an account number for the customer then we need to\n\t//also bail\n\tif accountnumber == \"\" {\n\t\terr = errors.New(\"Missing account number\")\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.03.2013 naj - validate the BSVKey to make sure the the BSV has been certified for MerX\n\terr = db.QueryRow(`select BSVKeyID from AuthorizedBSVKeys \n\t\t\t\t\t\t\twhere BSVKey = '?'`, bsvkey).Scan(&bsvkeyid)\n\n\t//default to having a valid bsvkey\n\tvalidbsvkey := 1\n\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\t//08.06.2015 ghh - before we send back an invalid BSV key we're going to instead\n\t\t\t//flag us to look again after validating the dealer. If the dealer ends up getting\n\t\t\t//validated then we're going to go ahead and insert this BSVKey into our accepted\n\t\t\t//list for this vendor.\n\t\t\tvalidbsvkey = 0\n\n\t\t\t//err = errors.New(\"Invalid BSV Key\")\n\t\t\t//code = http.StatusUnauthorized\n\t\t\t//return\n\t\tcase err != nil:\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t\t}\n\n\t//05.29.2013 naj - check to see if the supplied credentials are correct.\n\t//06.24.2014 naj - new format of request allows for the dealer to submit a request without a dealerkey on the first request to merX.\n\terr = db.QueryRow(`select DealerID, ifnull(DealerKey, '') as DealerKey,\n\t\t\t\t\t\t\tIPAddress\n\t\t\t\t\t\t\tfrom DealerCredentials where AccountNumber = ? \n\t\t\t\t\t\t\tand Active = 1 `, \n\t\t\t\t\t\t\taccountnumber).Scan(&dealerid, &dealerkey, &ipadd )\n\n\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\terr = errors.New(\"Account not found\")\n\t\t\tcode = http.StatusUnauthorized\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t}\n\n\t//05.06.2015 ghh - now we check to see if we have a valid key for the dealer\n\t//already. If they don't match then we get out. Keep in mind they could send\n\t//a blank key on the second attempt after we've generated a key and we need\n\t//to not allow that.\n\tif sentdealerkey != dealerkey {\n\t\terr = errors.New(\"Access Key Is Not Valid\" )\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.03.2013 naj - parse the RemoteAddr and update the client credentials\n\taddress := strings.Split(req.RemoteAddr, \":\")\n\n\t//08.06.2015 ghh - added check to make sure they are coming from the\n\t//linked ipadd if it exists\n\tif ipadd != \"\" && ipadd != address[0] {\n\t\terr = errors.New(\"Invalid IPAddress\" )\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.24.2014 naj - If we got this far then we have a dealerid, now we need to see if \n\t//they dealerkey is empty, if so create a new key and update the dealer record.\n\tif dealerkey == \"\" {\n\t\tdealerkey = uuid.NewV1().String()\n\n\t\t_, err = db.Exec(`update DealerCredentials set DealerKey = ?,\n\t\t\t\t\t\t\t\tLastIPAddress = inet_aton(?),\n\t\t\t\t\t\t\t\tAccessedDateTime = now()\n\t\t\t\t\t\t\t\twhere DealerID = ?`, dealerkey, address[0], dealerid)\n\n\t\tif err != nil {\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t\t}\n\n\t\t//08.06.2015 ghh - if this is the first time the dealer has attempted an order\n\t\t//and we're also missing the bsvkey then we're going to go ahead and insert into\n\t\t//the bsvkey table. The thought is that to hack this you'd have to find a dealer\n\t\t//that themselves has not ever placed an order and then piggy back in to get a valid\n\t\t//key. \n\t\tvar result sql.Result\n\t\tif validbsvkey == 0 {\n\t\t\t//here we need to insert the key into the table so future correspondence will pass\n\t\t\t//without conflict.\n\t\t\tresult, err = db.Exec(`insert into AuthorizedBSVKeys values ( null,\n\t\t\t\t\t\t\t\t\t?, 'Unknown' )`, bsvkey)\n\n\t\t\tif err != nil {\n\t\t\t\treturn \n\t\t\t}\n\n\t\t\t//now grab the bsvkeyid we just generated so we can return it\n\t\t\ttempbsv, _ := result.LastInsertId()\n\t\t\tbsvkeyid = int( tempbsv )\n\t\t}\n\n\t} else {\n\t\t//08.06.2015 ghh - if we did not find a valid bsv key above and flipped this\n\t\t//flag then here we need to raise an error. We ONLY allow this to happen on the\n\t\t//very first communcation with the dealer where we're also pulling a new key for \n\t\t//them\n\t\tif validbsvkey == 0 {\n\t\t\terr = errors.New(\"Invalid BSV Key\")\n\t\t\tcode = http.StatusUnauthorized\n\t\t\treturn\n\t\t}\n\t}\n\n\t_, err = db.Exec(`update DealerCredentials set LastIPAddress = inet_aton(?), \n\t\t\t\t\t\tAccessedDateTime = now() \n\t\t\t\t\t\twhere DealerID = ?`, address[0], dealerid)\n\n\tif err != nil {\n\t\tcode = http.StatusInternalServerError\n\t\treturn\n\t}\n\n\treturn\n}", "func (ths *ReceiveBackEnd) handleLogin(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close();\n\tths.log.Println(\"Login Handler on Backend !\");\n\tusername := r.URL.Query().Get(\"username\");\n\tpassword := r.URL.Query().Get(\"password\");\n\n\n\tif (username == \"\" || password == \"\") {\n\t\thttp.Error(w, \"username, password or location is not set\", http.StatusBadRequest);\n\t\treturn;\n\t}\n\n\tths.log.Println(\"Welcome to user \" + username + \" at \");\n\n\tusers := ths.store.GetJSonBlobs(UserBlobNew(username, password).ToJSonMap());\n\n\tths.log.Println(\"We found \" + goh.IntToStr(len(users)) + \" entries with this user in our database\");\n\t//\n\t// If user does not exists at all lets create him :-) That is no blob with \"username\" set to\n\t// the given username.\n\t//\n\tif (len(users) == 0) {\n\t\tths.log.Println(\"No user with that password and username, is the any user called \" + username + \"?\")\n\t\tusers = ths.store.GetJSonBlobs(UserBlobNew(username, \"\").ToJSonMap());\n\t\tvar sessionId = ths.createSession(username);\n\t\tuserBlob := UserBlobNewFull(username, password, sessionId);\n\t\tif len(users) == 0 {\n\t\t\tths.log.Println(\"No, lets create \" + username);\n\t\t\tths.store.PutJSonBlob(userBlob.ToJSonMap());\n\t\t\tths.store.PutJSonBlob(NewMBox(username, model.MBOX_NAME_INBOX).ToJSonMap());\n\t\t\tw.Write([]byte(sessionId));\n\t\t\tths.log.Println(\"Just sent \" + goh.IntToStr(len(sessionId)) + \" bytes across\");\n\t\t\treturn; // success\n\t\t} else {\n\t\t\thttp.Error(w, \"Access Denied\", http.StatusForbidden);\n\t\t}\n\t\treturn;\n\t}\n\n\t//\n\t// Ok we found a user\n\t//\n\tif (len(users) == 1) {\n\t\tvar sessionId = ths.createSession(username);\n\t\tw.Write([]byte(sessionId));\n\t\tths.store.UpdJSonBlob(UserBlobNew(username, password).ToJSonMap(), UserBlobNewFull(username, password, sessionId).ToJSonMap());\n\t} else {\n\t\thttp.Error(w, \"Access Denied\", http.StatusForbidden);\n\n\t}\n\tr.Body.Close();\n}", "func GETHandler(w http.ResponseWriter, r *http.Request) {\r\n\tquery := r.URL.Query()\r\n\t//pagination list using limit and offset query parameters\r\n\tlimit := query.Get(\"limit\")\r\n\toffset := query.Get(\"offset\")\r\n\tdb := OpenConnection()\r\n\tdefer db.Close()\r\n\tvar rows *sql.Rows\r\n\tvar err error\r\n\tmutex.Lock()\r\n\tdefer mutex.Unlock()\r\n\tswitch {\r\n\tcase limit == \"\" && offset != \"\":\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC OFFSET $1 \"\r\n\t\trows, err = db.Query(sqlstatement, offset)\r\n\tcase limit != \"\" && offset == \"\":\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC LIMIT $1 \"\r\n\t\trows, err = db.Query(sqlstatement, limit)\r\n\tcase limit == \"\" && offset == \"\":\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC\"\r\n\t\trows, err = db.Query(sqlstatement)\r\n\tdefault:\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC LIMIT $1 OFFSET $2 \"\r\n\t\trows, err = db.Query(sqlstatement, limit, offset)\r\n\t}\r\n\tdefer rows.Close()\r\n\tif err != nil {\r\n\t\tw.Write([]byte(err.Error()))\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\tvar all []Article\r\n\tfor rows.Next() {\r\n\t\tvar article Article\r\n\t\trows.Scan(&article.ID, &article.Title, &article.Subtitle, &article.Content, &article.CreationTimestamp)\r\n\t\tall = append(all, article)\r\n\t}\r\n\tpeopleBytes, err := json.MarshalIndent(all, \"\", \"\\t\")\r\n\tif err != nil {\r\n\t\tw.WriteHeader(http.StatusInternalServerError)\r\n\t\tw.Write([]byte(err.Error()))\r\n\t\treturn\r\n\t}\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tw.WriteHeader(http.StatusOK)\r\n\tw.Write(peopleBytes)\r\n}", "func (cli *srvClient) processRequest(ctx context.Context, msgID int, pkt *Packet) error {\n\tctx, cancel := context.WithTimeout(ctx, cli.srv.processingTimeout)\n\tdefer cancel()\n\n\t// TODO: use context for deadlines and cancellations\n\tvar res Response\n\tswitch pkt.Tag {\n\tdefault:\n\t\t// _ = pkt.Format(os.Stdout)\n\t\treturn UnsupportedRequestTagError(pkt.Tag)\n\tcase ApplicationUnbindRequest:\n\t\treturn io.EOF\n\tcase ApplicationBindRequest:\n\t\t// TODO: SASL\n\t\treq, err := parseBindRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Bind(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationSearchRequest:\n\t\treq, err := parseSearchRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif req.BaseDN == \"\" && req.Scope == ScopeBaseObject { // TODO check filter\n\t\t\tres, err = cli.rootDSE(req)\n\t\t} else {\n\t\t\tres, err = cli.srv.Backend.Search(ctx, cli.state, req)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationAddRequest:\n\t\treq, err := parseAddRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Add(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationDelRequest:\n\t\treq, err := parseDeleteRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Delete(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyRequest:\n\t\treq, err := parseModifyRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Modify(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyDNRequest:\n\t\treq, err := parseModifyDNRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.ModifyDN(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationExtendedRequest:\n\t\treq, err := parseExtendedRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch req.Name {\n\t\tdefault:\n\t\t\tres, err = cli.srv.Backend.ExtendedRequest(ctx, cli.state, req)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase OIDStartTLS:\n\t\t\tif cli.srv.tlsConfig == nil {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tBaseResponse: BaseResponse{\n\t\t\t\t\t\tCode: ResultUnavailable,\n\t\t\t\t\t\tMessage: \"TLS not configured\",\n\t\t\t\t\t},\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := cli.wr.Flush(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcli.cn = tls.Server(cli.cn, cli.srv.tlsConfig)\n\t\t\t\tcli.wr.Reset(cli.cn)\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase OIDPasswordModify:\n\t\t\tvar r *PasswordModifyRequest\n\t\t\tif len(req.Value) != 0 {\n\t\t\t\tp, _, err := ParsePacket(req.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tr, err = parsePasswordModifyRequest(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr = &PasswordModifyRequest{}\n\t\t\t}\n\t\t\tgen, err := cli.srv.Backend.PasswordModify(ctx, cli.state, r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp := NewPacket(ClassUniversal, false, TagSequence, nil)\n\t\t\tif gen != nil {\n\t\t\t\tp.AddItem(NewPacket(ClassContext, true, 0, gen))\n\t\t\t}\n\t\t\tb, err := p.Encode()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: b,\n\t\t\t}\n\t\tcase OIDWhoAmI:\n\t\t\tv, err := cli.srv.Backend.Whoami(ctx, cli.state)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: []byte(v),\n\t\t\t}\n\t\t}\n\t}\n\tif err := cli.cn.SetWriteDeadline(time.Now().Add(cli.srv.responseTimeout)); err != nil {\n\t\treturn fmt.Errorf(\"failed to set deadline for write: %w\", err)\n\t}\n\tdefer func() {\n\t\tif err := cli.cn.SetWriteDeadline(time.Time{}); err != nil {\n\t\t\tlog.Printf(\"failed to clear deadline for write: %s\", err)\n\t\t}\n\t}()\n\tif res != nil {\n\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn cli.wr.Flush()\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\thandlerKeySecret := KeySecret{}\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(&handlerKeySecret); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\ttokens := []KeySecret{}\n\tquery := \"SELECT key, secret, rules FROM tokens WHERE key=$1 and secret=$2 LIMIT 1\"\n\tcq := config.PrestConf.Adapter.Query(query, handlerKeySecret.Key, handlerKeySecret.Secret)\n\terr := json.Unmarshal(cq.Bytes(), &tokens)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tif len(tokens) == 0 {\n\t\thttp.Error(w, \"Key/Secret not found\", http.StatusBadRequest)\n\t\treturn\n\t}\n\ttokenJson, err := json.Marshal(tokens[0])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\ttokenString, err := token.Generate(fmt.Sprintf(string(tokenJson)))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\tauthPF := Auth{\n\t\tData: tokens[0],\n\t\tToken: tokenString,\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tret, _ := json.Marshal(authPF)\n\tw.Write(ret)\n}", "func (kvs *keyValueServer) getFromDB(request []string, client *Clienter) {\n\tkey := request[1]\n\tans := get(key)\n\tn := len(ans)\n\tfor i := 0; i < n; i++ {\n\t\tres := key + \",\" + string(ans[i]) + \"\\n\"\n\t\t// If response number exceed 500, return.\n\t\tselect {\n\t\tcase client.response <- res:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (client *GremlinResourcesClient) getGremlinDatabaseHandleResponse(resp *http.Response) (GremlinResourcesClientGetGremlinDatabaseResponse, error) {\n\tresult := GremlinResourcesClientGetGremlinDatabaseResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.GremlinDatabaseGetResults); err != nil {\n\t\treturn GremlinResourcesClientGetGremlinDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func DBHandler(db storage.DB) atreugo.View {\n\treturn func(ctx *atreugo.RequestCtx) error {\n\t\tworld := storage.AcquireWorld()\n\t\tdb.GetOneRandomWorld(world)\n\t\terr := ctx.JSONResponse(world)\n\n\t\tstorage.ReleaseWorld(world)\n\n\t\treturn err\n\t}\n}", "func fetchFraudDetectionRequests(c *gin.Context) {\n\t// swagger:route GET /api/v1/payments/fraud-detection/ fetchFraudDetectionRequests\n\t//\n\t// Handler returning list of All Fraud-Detection requests from Database.\n\t//\n\t// List of All Fraud-Detection requests from Database\n\t//\n\t// Responses:\n\t// 200: repoResp\n\t// 403: forbidden\n\n\tc.Header(\"Content-Type\", \"application/json\")\n\n\t// Read from Database:\n\t// ?\n\n\t// gin.H is a shortcut for map[string]interface{}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"message\": \"Fraud-Detection handler is not implemented yet\",\n\t})\n}", "func (app *App) retrieveHandler(w http.ResponseWriter, r *http.Request) {\n\tbaseErr := \"retrieveHandler fails: %v\"\n\n\tid, err := app.assets.Tokens.RetrieveAccountIDFromRequest(r.Context(), r)\n\tif err != nil {\n\t\tlog.Printf(baseErr, err)\n\t\tswitch {\n\t\tcase errors.Is(err, tokens.AuthHeaderError):\n\t\t\tapi.Error2(w, api.AuthHeaderError)\n\t\tcase errors.Is(err, tokens.ErrDoesNotExist):\n\t\t\tapi.Error2(w, api.NotExistError)\n\t\tdefault:\n\t\t\tapi.Error2(w, api.DatabaseError)\n\t\t}\n\t\treturn\n\t}\n\n\t// todo (rr): we need one query for retrieve account info\n\taccount, err := app.RetrieveByID(r.Context(), id)\n\tif err != nil {\n\t\tlog.Printf(baseErr, err)\n\t\tapi.Error2(w, api.DatabaseError)\n\t\treturn\n\t}\n\n\tapi.Response(w, account)\n}", "func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\tm.verifyHandler(w, r)\n\t\treturn\n\t}\n\n\tvar rec Receive\n\n\t// consume a *copy* of the request body\n\tbody, _ := ioutil.ReadAll(r.Body)\n\tr.Body = ioutil.NopCloser(bytes.NewBuffer(body))\n\n\terr := json.Unmarshal(body, &rec)\n\tif err != nil {\n\t\terr = xerrors.Errorf(\"could not decode response: %w\", err)\n\t\tfmt.Println(err)\n\t\tfmt.Println(\"could not decode response:\", err)\n\t\trespond(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif rec.Object != \"page\" {\n\t\tfmt.Println(\"Object is not page, undefined behaviour. Got\", rec.Object)\n\t\trespond(w, http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tif m.verify {\n\t\tif err := m.checkIntegrity(r); err != nil {\n\t\t\tfmt.Println(\"could not verify request:\", err)\n\t\t\trespond(w, http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t}\n\n\tm.dispatch(rec)\n\n\trespond(w, http.StatusAccepted) // We do not return any meaningful response immediately so it should be 202\n}", "func (server *Server) handleRequestBlob(client *Client, msg *Message) {\n\tblobreq := &mumbleproto.RequestBlob{}\n\terr := proto.Unmarshal(msg.buf, blobreq)\n\tif err != nil {\n\t\tclient.Panic(err)\n\t\treturn\n\t}\n\n\tuserstate := &mumbleproto.UserState{}\n\n\t// Request for user textures\n\tif len(blobreq.SessionTexture) > 0 {\n\t\tfor _, sid := range blobreq.SessionTexture {\n\t\t\tif target, ok := server.clients[sid]; ok {\n\t\t\t\tif target.user == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif target.user.HasTexture() {\n\t\t\t\t\tbuf, err := BlobStore.Get(target.user.TextureBlob)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tserver.Panicf(\"Blobstore error: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tuserstate.Reset()\n\t\t\t\t\tuserstate.Session = proto.Uint32(uint32(target.Session()))\n\t\t\t\t\tuserstate.Texture = buf\n\t\t\t\t\tif err := client.sendMessage(userstate); err != nil {\n\t\t\t\t\t\tclient.Panic(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Request for user comments\n\tif len(blobreq.SessionComment) > 0 {\n\t\tfor _, sid := range blobreq.SessionComment {\n\t\t\tif target, ok := server.clients[sid]; ok {\n\t\t\t\tif target.user == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif target.user.HasComment() {\n\t\t\t\t\tbuf, err := BlobStore.Get(target.user.CommentBlob)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tserver.Panicf(\"Blobstore error: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tuserstate.Reset()\n\t\t\t\t\tuserstate.Session = proto.Uint32(uint32(target.Session()))\n\t\t\t\t\tuserstate.Comment = proto.String(string(buf))\n\t\t\t\t\tif err := client.sendMessage(userstate); err != nil {\n\t\t\t\t\t\tclient.Panic(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tchanstate := &mumbleproto.ChannelState{}\n\n\t// Request for channel descriptions\n\tif len(blobreq.ChannelDescription) > 0 {\n\t\tfor _, cid := range blobreq.ChannelDescription {\n\t\t\tif channel, ok := server.Channels[int(cid)]; ok {\n\t\t\t\tif channel.HasDescription() {\n\t\t\t\t\tchanstate.Reset()\n\t\t\t\t\tbuf, err := BlobStore.Get(channel.DescriptionBlob)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tserver.Panicf(\"Blobstore error: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tchanstate.ChannelId = proto.Uint32(uint32(channel.Id))\n\t\t\t\t\tchanstate.Description = proto.String(string(buf))\n\t\t\t\t\tif err := client.sendMessage(chanstate); err != nil {\n\t\t\t\t\t\tclient.Panic(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func handleRequest(conn net.Conn, c *C) {\n\tc.Assert(conn, NotNil)\n\tdefer conn.Close()\n\tvar msg msgpb.Message\n\tmsgID, err := util.ReadMessage(conn, &msg)\n\tc.Assert(err, IsNil)\n\tc.Assert(msgID, Greater, uint64(0))\n\tc.Assert(msg.GetMsgType(), Equals, msgpb.MessageType_KvReq)\n\n\treq := msg.GetKvReq()\n\tc.Assert(req, NotNil)\n\tvar resp pb.Response\n\tresp.Type = req.Type\n\tmsg = msgpb.Message{\n\t\tMsgType: msgpb.MessageType_KvResp,\n\t\tKvResp: &resp,\n\t}\n\terr = util.WriteMessage(conn, msgID, &msg)\n\tc.Assert(err, IsNil)\n}", "func (s *Server) handleCustomerGetToken(writer http.ResponseWriter, request *http.Request) {\n\tvar item *types.Auth\n\n\terr := json.NewDecoder(request.Body).Decode(&item)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttoken, err := s.customersSvc.Token(request.Context(), item.Login, item.Password)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\trespondJSON(writer, &types.Token{Token: token})\n}", "func performHTTPRequest(req *http.Request, sess *UserSession) ([]byte, []string) {\n\treq.Header.Set(\"User-Agent\", \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36\")\n\treq.Header.Set(\"Accept\", \"application/json, text/javascript, */*; q=0.01\")\n\t// form token is bound to vid\n\treq.Header.Set(`Cookie`, `vid=`+sess.vid+`; identifier=`+sess.identifier+`; login-options={\"stay\":true,\"no_ip_check\":true,\"leave_others\":true}; prf_ls_uad=price.a.200.normal; rtif-legacy=1; login-options={\"stay\":true,\"no_ip_check\":true,\"leave_others\":true}`)\n\n\t/*\n\t // this is for debug proxying\n\t proxy, _ :=url.Parse(\"http://127.0.0.1:8080\")\n\t tr := &http.Transport{\n\t \tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t \tProxy: http.ProxyURL(proxy),\n\t }\n\t*/\n\n\ttr := &http.Transport{}\n\t// for avoiding infinite redirect loops\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(\"[!] HTTP request failed to\" + req.URL.Host + req.URL.Path)\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(\"[!] HTTP request failed to\" + req.URL.Host + req.URL.Path)\n\t\tpanic(err)\n\t}\n\t// fmt.Println(string(resp.Header.Values(\"Set-Cookie\")[0]))\n\n\treturn respBody, resp.Header.Values(\"Set-Cookie\")\n}", "func HandleMytokenFromTransferCode(ctx *fiber.Ctx) *model.Response {\n\trlog := logger.GetRequestLogger(ctx)\n\trlog.Debug(\"Handle mytoken from transfercode\")\n\treq := response.NewExchangeTransferCodeRequest()\n\tif err := errors.WithStack(json.Unmarshal(ctx.Body(), &req)); err != nil {\n\t\treturn model.ErrorToBadRequestErrorResponse(err)\n\t}\n\trlog.Trace(\"Parsed request\")\n\tvar errorRes *model.Response = nil\n\tvar tokenStr string\n\tif err := db.Transact(\n\t\trlog, func(tx *sqlx.Tx) error {\n\t\t\tstatus, err := transfercoderepo.CheckTransferCode(rlog, tx, req.TransferCode)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !status.Found {\n\t\t\t\terrorRes = &model.Response{\n\t\t\t\t\tStatus: fiber.StatusUnauthorized,\n\t\t\t\t\tResponse: api.ErrorBadTransferCode,\n\t\t\t\t}\n\t\t\t\treturn errors.New(errResPlaceholder)\n\t\t\t}\n\t\t\tif status.Expired {\n\t\t\t\terrorRes = &model.Response{\n\t\t\t\t\tStatus: fiber.StatusUnauthorized,\n\t\t\t\t\tResponse: api.ErrorTransferCodeExpired,\n\t\t\t\t}\n\t\t\t\treturn errors.New(errResPlaceholder)\n\t\t\t}\n\t\t\ttokenStr, err = transfercoderepo.PopTokenForTransferCode(\n\t\t\t\trlog, tx, req.TransferCode, *ctxutils.ClientMetaData(ctx),\n\t\t\t)\n\t\t\treturn err\n\t\t},\n\t); err != nil {\n\t\tif errorRes != nil {\n\t\t\treturn errorRes\n\t\t}\n\t\trlog.Errorf(\"%s\", errorfmt.Full(err))\n\t\treturn model.ErrorToInternalServerErrorResponse(err)\n\t}\n\n\ttoken, err := universalmytoken.Parse(rlog, tokenStr)\n\tif err != nil {\n\t\trlog.Errorf(\"%s\", errorfmt.Full(err))\n\t\treturn model.ErrorToBadRequestErrorResponse(err)\n\t}\n\tmt, err := mytoken.ParseJWT(token.JWT)\n\tif err != nil {\n\t\trlog.Errorf(\"%s\", errorfmt.Full(err))\n\t\treturn model.ErrorToInternalServerErrorResponse(err)\n\t}\n\treturn &model.Response{\n\t\tStatus: fiber.StatusOK,\n\t\tResponse: response.MytokenResponse{\n\t\t\tMytokenResponse: api.MytokenResponse{\n\t\t\t\tMytoken: token.OriginalToken,\n\t\t\t\tExpiresIn: mt.ExpiresIn(),\n\t\t\t\tCapabilities: mt.Capabilities,\n\t\t\t\tMOMID: mt.ID.Hash(),\n\t\t\t},\n\t\t\tMytokenType: token.OriginalTokenType,\n\t\t\tRestrictions: mt.Restrictions,\n\t\t},\n\t}\n\n}", "func GetCards(c *gin.Context) {\n\tif c.Request.Header.Get(\"x-auth\") != \"\" {\n\t\tappEngine := appengine.NewContext(c.Request)\n\t\ttokens := GetTokenList(appEngine)\n\t\tif tokens == nil {\n\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"status_code\": http.StatusUnauthorized, \"status_message\": \"Authentication Token is invalid.\"})\n\t\t} else {\n\t\t\tif CheckTokenValidity(tokens, c.Request.Header.Get(\"x-auth\")) {\n\t\t\t\tcardQuery := datastore.NewQuery(CardsKey).Ancestor(SandboxPromotionsKey(appEngine, CardsKey))\n\t\t\t\tvar cards []Card\n\t\t\t\tcardQuery.GetAll(appEngine, &cards)\n\t\t\t\tif cards != nil {\n\t\t\t\t\tc.JSON(http.StatusOK, gin.H{\"status_code\": http.StatusOK, \"status_message\": \"Success\", \"data\": cards})\n\t\t\t\t} else {\n\t\t\t\t\tc.JSON(http.StatusOK, gin.H{\"status_code\": http.StatusOK, \"status_message\": \"Success\", \"data\": []Card{}})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"status_code\": http.StatusUnauthorized, \"status_message\": \"Authentication Token is invalid.\"})\n\t\t\t}\n\t\t}\n\t} else {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\"status_code\": http.StatusUnauthorized, \"status_message\": \"Authentication Token is invalid.\"})\n\t}\n}", "func fetchPostHandler(w http.ResponseWriter, r *http.Request) {\n\tkeys := readKeys(r.Body)\n\tservs := servers()\n\tnumServers := len(servs)\n\tserverKeys := groupKeysByServer(numServers, keys)\n\tresult := make([]Element, 0)\n\tfor idx, keys := range serverKeys {\n\t\tif len(keys) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tencodedList, err := json.Marshal(keys)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error marshalling list of keys:\", err)\n\t\t}\n\t\tels := fetchListFromServer(servs[idx], encodedList)\n\t\tresult = append(result, decodeKVs(els)...)\n\t}\n\tif len(keys) == len(result) {\n\t\tw.WriteHeader(http.StatusOK)\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\tjson.NewEncoder(w).Encode(result)\n}", "func (client *DatabaseVulnerabilityAssessmentScansClient) getHandleResponse(resp *http.Response) (DatabaseVulnerabilityAssessmentScansClientGetResponse, error) {\n\tresult := DatabaseVulnerabilityAssessmentScansClientGetResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.VulnerabilityAssessmentScanRecord); err != nil {\n\t\treturn DatabaseVulnerabilityAssessmentScansClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func handleGetRequest(key string, s *Sailor, st *storage.State) (string, error) {\n\tgt := storage.GenerateTransaction(storage.GetOp, key, \"\")\n\treturn st.ApplyTransaction(gt)\n}", "func middleware(ctx *fasthttp.RequestCtx, redisClient *redis.Client) {\n\tctx.Response.Header.SetContentType(\"application/json; charset=utf-8\")\n\tlog.Info(\"CTX: \", string(ctx.PostBody())) // Logging the arguments of the request\n\tvar req datastructures.MiddlewareRequest\n\terr := json.Unmarshal(ctx.PostBody(), &req) // Populate the structure from the json\n\tcommonutils.Check(err, \"middleware\")\n\tlog.Info(\"Request unmarshalled: \", req)\n\tlog.Debug(\"Validating request ...\")\n\tif authutils.ValidateMiddlewareRequest(&req) { // Verify it the json is valid\n\t\tlog.Info(\"Request valid! Verifying token from Redis ...\")\n\t\tauth := authutils.VerifyCookieFromRedisHTTPCore(req.Username, req.Token, redisClient) // Call the core function for recognize if the user have the token\n\t\tif strings.Compare(auth, \"AUTHORIZED\") == 0 { // Token in redis, call the external service..\n\t\t\tlog.Info(\"REQUEST OK> \", req)\n\t\t\tlog.Warn(\"Using service \", req.Method, \" | ARGS: \", req.Data, \" | Token: \", req.Token, \" | USR: \", req.Username)\n\t\t\t_, err := ctx.Write(sendGet(req))\n\t\t\tcommonutils.Check(err, \"middleware\")\n\t\t\treturn\n\t\t}\n\t\terr = json.NewEncoder(ctx).Encode(datastructures.Response{Status: false, Description: \"NOT AUTHORIZED!!\", ErrorCode: \"YOU_SHALL_NOT_PASS\", Data: nil})\n\t\tcommonutils.Check(err, \"middleware\")\n\t\treturn\n\t}\n\terr = json.NewEncoder(ctx).Encode(datastructures.Response{Status: false, Description: \"Not Valid Json!\", ErrorCode: \"\", Data: req})\n\tcommonutils.Check(err, \"middleware\")\n}", "func (client *SQLResourcesClient) getSQLDatabaseHandleResponse(resp *http.Response) (SQLResourcesClientGetSQLDatabaseResponse, error) {\n\tresult := SQLResourcesClientGetSQLDatabaseResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SQLDatabaseGetResults); err != nil {\n\t\treturn SQLResourcesClientGetSQLDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func handle(connection net.Conn) {\n\t//Read client input line-by-line (scanner.Scan() looks for \\n automatically)\n\tscanner := bufio.NewScanner(connection)\n\tfor scanner.Scan() {\n\t\tsplitLine, err := validateAndSplitLine(scanner.Text())\n\t\tif err != nil {\n\t\t\tlog.Println(\"[ERROR] \" + err.Error())\n\t\t\tconnection.Write([]byte(\"ERROR\\n\"))\n\t\t\tcontinue\n\t\t}\n\n\t\tresponse := crud(splitLine)\n\t\tconnection.Write([]byte(response))\n\t}\n}", "func HandleConn(c net.Conn, ms message.Service, cs contact.Service, as account.Service, gms groupMessage.Service, gs group.Service) {\n\tdefer c.Close()\n\tvar requestToken RequestToken\n\tconDecoder := json.NewDecoder(c)\n\tconEncoder := json.NewEncoder(c)\n\terr := conDecoder.Decode(&requestToken)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tlog.Println(requestToken.Token)\n\tclaims := &security.JwtClaims{}\n\ttoken, err := jwt.ParseWithClaims(requestToken.Token, claims, func(token *jwt.Token) (interface{}, error) {\n\t\ttoken.SigningString()\n\t\treturn security.GetSecret(), err\n\t})\n\tif err != nil || !token.Valid {\n\t\tlog.Println(\"Bad token. Rejecting Connection: \" + err.Error())\n\t\treturn\n\t}\n\tlog.Println(\"Credentials ok! Establishing connection\")\n\n\tfor {\n\t\tvar request Request\n\n\t\terr := conDecoder.Decode(&request)\n\t\tif err == io.EOF {\n\t\t\tlog.Print(\"Client Disconnected\")\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\tcontinue\n\t\t}\n\t\t// log.Println(request)\n\n\t\tswitch request.Type {\n\t\tcase requestContacts:\n\t\t\tcontacts, err := cs.GetContacts(claims.ID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjsonByteArray, err := json.Marshal(ToResponseContacts(contacts))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse := Response{\n\t\t\t\tType: responseContacts,\n\t\t\t\tData: jsonByteArray,\n\t\t\t}\n\t\t\tconEncoder.Encode(response)\n\n\t\tcase updateContactLastRead:\n\t\t\tvar updateContactLastRead UpdateContactLastRead\n\t\t\terr = json.Unmarshal(request.Data, &updateContactLastRead)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = cs.UpdateLastRead(claims.ID, updateContactLastRead.AccountID, updateContactLastRead.LastReadID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tcase updateContactGroupLastRead:\n\t\t\tvar updateContactGroupLastRead UpdateContactGroupLastRead\n\t\t\terr = json.Unmarshal(request.Data, &updateContactGroupLastRead)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = cs.UpdateGroupLastRead(claims.ID, updateContactGroupLastRead.GroupID, updateContactGroupLastRead.LastReadID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tcase addMessage:\n\t\t\tvar addMessage AddMessage\n\t\t\terr = json.Unmarshal(request.Data, &addMessage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = ms.AddMessage(addMessage.ToDomian(claims.ID))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tcase requestMessages:\n\t\t\tvar requestMessages RequestMessages\n\t\t\terr = json.Unmarshal(request.Data, &requestMessages)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmessageModels, err := ms.GetMessage(requestMessages.DateTime, claims.ID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjsonByteArray, err := json.Marshal(ToResponseMessages(messageModels))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse := Response{\n\t\t\t\tType: responseMessages,\n\t\t\t\tData: jsonByteArray,\n\t\t\t}\n\t\t\tconEncoder.Encode(response)\n\n\t\tcase addGroupMessage:\n\t\t\tvar addGroupMessage AddGroupMessage\n\t\t\terr = json.Unmarshal(request.Data, &addGroupMessage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = gms.AddGroupMessage(addGroupMessage.ToDomian(claims.ID))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tcase requestGroupMessages:\n\t\t\tvar requestGroupMessages RequestGroupMessages\n\t\t\terr = json.Unmarshal(request.Data, &requestGroupMessages)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgroupMessageModels, err := gms.GetGroupMessage(requestGroupMessages.DateTime, claims.ID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjsonByteArray, err := json.Marshal(ToResponseGroupMessages(groupMessageModels))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse := Response{\n\t\t\t\tType: responseGroupMessages,\n\t\t\t\tData: jsonByteArray,\n\t\t\t}\n\t\t\tconEncoder.Encode(response)\n\n\t\tcase requestAccount:\n\t\t\tvar requestAccount RequestAccount\n\t\t\terr = json.Unmarshal(request.Data, &requestAccount)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taccountModel, err := as.GetAccountByID(requestAccount.ID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjsonByteArray, err := json.Marshal(ToResponseAccount(accountModel))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse := Response{\n\t\t\t\tType: responseAccount,\n\t\t\t\tData: jsonByteArray,\n\t\t\t}\n\t\t\tconEncoder.Encode(response)\n\n\t\tcase requestGroup:\n\t\t\tvar requestGroup RequestGroup\n\t\t\terr = json.Unmarshal(request.Data, &requestGroup)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgroupModel, err := gs.FindGroupByID(requestGroup.ID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjsonByteArray, err := json.Marshal(ToResponseGroup(groupModel))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse := Response{\n\t\t\t\tType: responseGroup,\n\t\t\t\tData: jsonByteArray,\n\t\t\t}\n\t\t\tconEncoder.Encode(response)\n\t\t}\n\t}\n}", "func (app *Application) GetBatchHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]interface{}\n\tdata = make(map[string]interface{})\n\tvar bInfo webutil.BatchInfo\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\t//befor send request we need to check session\n\t\tuName := webutil.MySession.GetUserName(r)\n\t\toName := webutil.MySession.GetOrgName(r)\n\t\tif fSetup, ok := app.Fabric[uName]; ok {\n\n\t\t\tvar cn string\n\t\t\tvar ccn string\n\t\t\tvar fcn string\n\n\t\t\tsuppliertypeValue := r.FormValue(\"suppliertype\")\n\t\t\t//find cfg name\n\t\t\t//according supplier type to choose corresponding channel\n\t\t\tfor _, v := range webutil.Orgnization[oName] {\n\t\t\t\tif v.UserName == uName {\n\t\t\t\t\tswitch suppliertypeValue {\n\t\t\t\t\tcase \"battery\":\n\t\t\t\t\t\tcn = v.UserOperation[\"GetBatchBattery\"].ChannelName\n\t\t\t\t\t\tccn = v.UserOperation[\"GetBatchBattery\"].CCName\n\t\t\t\t\t\tfcn = v.UserOperation[\"GetBatchBattery\"].Fcn\n\t\t\t\t\tcase \"display\":\n\t\t\t\t\t\tcn = v.UserOperation[\"GetBatchDisplay\"].ChannelName\n\t\t\t\t\t\tccn = v.UserOperation[\"GetBatchDisplay\"].CCName\n\t\t\t\t\t\tfcn = v.UserOperation[\"GetBatchDisplay\"].Fcn\n\t\t\t\t\tcase \"cpu\":\n\t\t\t\t\t\tcn = v.UserOperation[\"GetBatchCpu\"].ChannelName\n\t\t\t\t\t\tccn = v.UserOperation[\"GetBatchCpu\"].CCName\n\t\t\t\t\t\tfcn = v.UserOperation[\"GetBatchCpu\"].Fcn\n\t\t\t\t\tcase \"assembly\":\n\t\t\t\t\t\tcn = v.UserOperation[\"GetBatchAssembly\"].ChannelName\n\t\t\t\t\t\tccn = v.UserOperation[\"GetBatchAssembly\"].CCName\n\t\t\t\t\t\tfcn = v.UserOperation[\"GetBatchAssembly\"].Fcn\n\t\t\t\t\tcase \"logistics\":\n\t\t\t\t\t\tcn = v.UserOperation[\"GetBatchLogistics\"].ChannelName\n\t\t\t\t\t\tccn = v.UserOperation[\"GetBatchLogistics\"].CCName\n\t\t\t\t\t\tfcn = v.UserOperation[\"GetBatchLogistics\"].Fcn\n\t\t\t\t\tcase \"sales\":\n\t\t\t\t\t\tcn = v.UserOperation[\"GetBatchSales\"].ChannelName\n\t\t\t\t\t\tccn = v.UserOperation[\"GetBatchSales\"].CCName\n\t\t\t\t\t\tfcn = v.UserOperation[\"GetBatchSales\"].Fcn\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tkey := r.FormValue(\"pmodel\")\n\t\t\t//add properties to args\n\t\t\t//TODO: here to map batchinfo to data\n\t\t\tbatchinfo, err := fSetup.QueryCC(cn, ccn, fcn, []byte(key))\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, \"Unable to invoke hello in the blockchain\", 500)\n\t\t\t}\n\t\t\tjson.Unmarshal([]byte(batchinfo), &bInfo)\n\t\t\tdata[\"PhoneModel\"] = key\n\t\t\tdata[\"BatchInfo\"] = bInfo.Batch\n\t\t}\n\t\t// txid, err := app.Fabric.InvokeSupplier(passargs)\n\t}\n\trenderTemplate(w, r, \"getbatch.html\", data)\n}", "func (client *ManagedDatabasesClient) getHandleResponse(resp *http.Response) (ManagedDatabasesClientGetResponse, error) {\n\tresult := ManagedDatabasesClientGetResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.ManagedDatabase); err != nil {\n\t\treturn ManagedDatabasesClientGetResponse{}, err\n\t}\n\treturn result, nil\n}", "func captchaVerifyHandle(w http.ResponseWriter, r *http.Request) {\n\n\t//parse request parameters\n\tdecoder := json.NewDecoder(r.Body)\n\n\tvar postParameters ConfigJsonBody\n\terr := decoder.Decode(&postParameters)\n\tif err != nil {\n\t\tglog.Infoln(err)\n\t}\n\tdefer r.Body.Close()\n\t//verify the captcha\n\tverifyResult := base64Captcha.VerifyCaptcha(postParameters.Id, postParameters.VerifyValue)\n\t//fmt.Println(\"postParameters:\", postParameters)\n\n\t//set json response\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tbody := map[string]interface{}{\"code\": \"error\", \"data\": \"\", \"msg\": \"captcha failed\"}\n\tif verifyResult {\n\t\ttoken := common.MakeToken()\n\t\tredis := redisCluster.GetNodeByString(token)\n\n\t\tif redis != nil {\n\t\t\t// save token to redis\n\t\t\t//fmt.Println(\"token = \", token)\n\t\t\tredis.Set(fmt.Sprintf(common.Redis_Key_Captcha_Format, token), \"\", time.Duration(cfg_captcha_expiration))\n\n\t\t\t// send token to client\n\t\t\tbody = map[string]interface{}{\"code\": \"success\", \"data\": token, \"msg\": \"captcha verified\"}\n\t\t} else {\n\t\t\tbody = map[string]interface{}{\"code\": \"error\", \"data\": \"\", \"msg\": \"no redis client\"}\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(body)\n}", "func generateHandler(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\n\t// Default length for the body to generate.\n\ttokenLen := 50\n\n\tif r.URL.Query().Get(\"limit\") != \"\" {\n\t\ttokenLen, err = strconv.Atoi(r.URL.Query().Get(\"limit\"))\n\t\tif err != nil {\n\t\t\terrHandler(w, 500, err)\n\t\t}\n\t}\n\n\tout, err := index.Babble(\"\", tokenLen) // Starting seed is left blank for random choice.\n\tif err != nil {\n\t\tif err == ngrams.ErrEmptyIndex {\n\t\t\tm, err := json.Marshal(map[string]interface{}{\n\t\t\t\t\"err\": \"index is empty; please learn ngrams before generating.\",\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\terrHandler(w, 400, err)\n\t\t\t}\n\n\t\t\tw.Write(m)\n\t\t\treturn\n\t\t}\n\n\t\terrHandler(w, 500, err)\n\t}\n\n\tm, err := json.Marshal(map[string]interface{}{\n\t\t\"body\": out,\n\t\t\"limit\": tokenLen,\n\t})\n\tif err != nil {\n\t\terrHandler(w, 500, err)\n\t}\n\n\tw.Write(m)\n\n}", "func (s *HTTPServer) getDataTokenHandler(w http.ResponseWriter, r *http.Request) {\n\ttoken, err := extractToken(r)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t} else if token == \"\" {\n\t\thttp.Error(w, \"missing token\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tdataToken, err := s.coreService.GetDataAPIToken(token)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t_, err = w.Write([]byte(dataToken))\n\tif err != nil {\n\t\ts.loggerHelper.LogError(\"getDataTokenHandler\", err.Error(), pbLogger.ErrorMessage_FATAL)\n\t}\n\n}", "func queryHandler(w http.ResponseWriter, r *http.Request) {\r\n\r\n\tif r.Header.Get(\"Content-Type\") != \"application/json\" {\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\t//To allocate slice for request body\r\n\tlength, err := strconv.Atoi(r.Header.Get(\"Content-Length\"))\r\n\tif err != nil {\r\n\t\tw.WriteHeader(http.StatusInternalServerError)\r\n\t\treturn\r\n\t}\r\n\r\n\t//Read body data to parse json\r\n\tbody := make([]byte, length)\r\n\tlength, err = r.Body.Read(body)\r\n\tif err != nil && err != io.EOF {\r\n\t\tw.WriteHeader(http.StatusInternalServerError)\r\n\t\treturn\r\n\t}\r\n\r\n\t//parse json\r\n\tvar jsonBody map[string]interface{}\r\n\terr = json.Unmarshal(body[:length], &jsonBody)\r\n\tif err != nil {\r\n\t\tw.WriteHeader(http.StatusInternalServerError)\r\n\t\treturn\r\n\t}\r\n\r\n\tvar time_from,time_to time.Time\r\n\tif time_from, err = getTimeFromReq(jsonBody, \"from\"); err != nil{\r\n\t\tfmt.Printf(\"ERR: %v\\n\", err)\r\n\t\tw.WriteHeader(http.StatusBadRequest)\t\t\r\n\t\treturn \r\n\t}\r\n\r\n\tif time_to, err = getTimeFromReq(jsonBody, \"to\"); err != nil{\r\n\t\tfmt.Printf(\"ERR: %v\\n\", err)\r\n\t\tw.WriteHeader(http.StatusBadRequest)\t\t\r\n\t\treturn \r\n\t}\r\n\r\n\tvar targets []string\r\n\tif targets, err = getTargetFromReq(jsonBody); err != nil {\r\n\t\tfmt.Printf(\"ERR: %v\\n\", err)\r\n\t}\r\n\r\n\tjsonOut := getRedisVal(*redisHost,\r\n\t\ttargets,\r\n\t\tstrconv.FormatInt(time_from.Unix(), 10),\r\n\t\tstrconv.FormatInt(time_to.Unix(), 10),\r\n\t\tint(jsonBody[\"maxDataPoints\"].(float64)))\r\n\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tfmt.Fprintf(w, jsonOut)\r\n\treturn\r\n}", "func handlePostRequest(rw rest.ResponseWriter, req *rest.Request) {\n\t//try and fill buffer from request body\n\tbuffer := new(bytes.Buffer)\n\t_, err := buffer.ReadFrom(req.Body)\n\n\tif err == nil {\n\t\t//if successful, convert to JSON string\n\t\tvar data string\n\t\tdata = buffer.String()\n\t\terr = isValidSyncJSON(data)\n\t\tif err == nil {\n\t\t\t//if JSON is valid:\n\t\t\t//find storageId for this user\n\t\t\tauthHeader := req.Header.Get(\"Authorization\")\n\t\t\tauthToken := strings.Split(authHeader, \"Basic \")[1]\n\t\t\tbase64Text := make([]byte, base64.StdEncoding.DecodedLen(len(authToken)))\n\t\t\tbase64.StdEncoding.Decode(base64Text, []byte(authToken))\n\t\t\tstorageID := strings.Split(string(base64Text), \":\")[0]\n\t\t\t//add storageId to JSON\n\t\t\tout := map[string]interface{}{}\n\t\t\tjson.Unmarshal([]byte(data), &out)\n\t\t\tout[\"storageId\"] = storageID\n\t\t\toutputJSON, err := json.Marshal(out)\n\t\t\tdata = string(outputJSON)\n\t\t\t// store in DB\n\t\t\tfor i := 0; i < 5; i++ {\n\t\t\t\terr = storeInDB(data)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\t//retry n times if failed\n\t\t\t\t\terr = storeInDB(data)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\trw.WriteHeader(http.StatusOK)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\t//if persisting to DB failed, send appropriate status\n\t\t\t\trw.WriteHeader(http.StatusTooManyRequests)\n\t\t\t}\n\t\t} else {\n\t\t\t//if JSON is invalid, send appropriate status\n\t\t\trw.WriteHeader(http.StatusExpectationFailed)\n\t\t}\n\t} else {\n\t\t//if Request.Body is invalid, send appropriate status\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t}\n\n\t//if this is reached, the request was unsuccessful; print error\n\tlog.Printf(\"error: %v\", err.Error())\n}", "func authHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {\n\tif c.Auth.Method == \"none\" {\n\t\t// NoAuth instances shouldn't call this method.\n\t\treturn 0, nil\n\t}\n\n\tif c.Auth.Method == \"proxy\" {\n\t\t// Receive the Username from the Header and check if it exists.\n\t\tu, err := c.Store.Users.GetByUsername(r.Header.Get(c.Auth.Header), c.NewFS)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// Receive the credentials from the request and unmarshal them.\n\tvar cred cred\n\n\tif r.Body == nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\terr := json.NewDecoder(r.Body).Decode(&cred)\n\tif err != nil {\n\t\treturn http.StatusForbidden, err\n\t}\n\n\t// Wenkun, Validate the token of user from cloud server and return JWT token.\n\tif c.Auth.Method != \"none\" {\n\t\tok, u := validateAuthByUserId(c, cred.Username)\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// If ReCaptcha is enabled, check the code.\n\tif len(c.ReCaptcha.Secret) > 0 {\n\t\tok, err := reCaptcha(c.ReCaptcha.Host, c.ReCaptcha.Secret, cred.ReCaptcha)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, err\n\t\t}\n\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\t}\n\n\t// Checks if the user exists.\n\tu, err := c.Store.Users.GetByUsername(cred.Username, c.NewFS)\n\tif err != nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\t// Checks if the password is correct.\n\tif !fb.CheckPasswordHash(cred.Password, u.Password) {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\tc.User = u\n\treturn printToken(c, w)\n}", "func (p *pbft) handleClientRequest(content []byte) {\n\tfmt.Println(\"The primary node has received the request from the client.\")\n\t//The Request structure is parsed using JSON\n\tr := new(Request)\n\terr := json.Unmarshal(content, r)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t//to add infoID\n\tp.sequenceIDAdd()\n\t//to get the digest\n\tdigest := getDigest(*r)\n\tfmt.Println(\"The request has been stored into the temporary message pool.\")\n\t//to store into the temp message pool\n\tp.messagePool[digest] = *r\n\t//to sign the digest by the primary node\n\tdigestByte, _ := hex.DecodeString(digest)\n\tsignInfo := p.RsaSignWithSha256(digestByte, p.node.rsaPrivKey)\n\t//setup PrePrepare message and send to other nodes\n\tpp := PrePrepare{*r, digest, p.sequenceID, signInfo}\n\tb, err := json.Marshal(pp)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Println(\"sending PrePrepare messsage to all the other nodes...\")\n\t//to send PrePrepare message to other nodes\n\tp.broadcast(cPrePrepare, b)\n\tfmt.Println(\"PrePrepare is done.\")\n}", "func (client *DatabaseVulnerabilityAssessmentScansClient) listByDatabaseHandleResponse(resp *http.Response) (DatabaseVulnerabilityAssessmentScansClientListByDatabaseResponse, error) {\n\tresult := DatabaseVulnerabilityAssessmentScansClientListByDatabaseResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.VulnerabilityAssessmentScanRecordListResult); err != nil {\n\t\treturn DatabaseVulnerabilityAssessmentScansClientListByDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func (h *handler) invoke(method handlerMethod) error {\n\t// exp vars used for reading request counts\n\trestExpvars.Add(\"requests_total\", 1)\n\trestExpvars.Add(\"requests_active\", 1)\n\tdefer restExpvars.Add(\"requests_active\", -1)\n\n\tswitch h.rq.Header.Get(\"Content-Encoding\") {\n\tcase \"\":\n\t\th.requestBody = h.rq.Body\n\tdefault:\n\t\treturn base.HTTPErrorf(http.StatusUnsupportedMediaType, \"Unsupported Content-Encoding;\")\n\t}\n\n\th.setHeader(\"Server\", VersionString)\n\n\t//To Do: If there is a \"db\" path variable, look up the database context:\n\tvar dbc *db.DatabaseContext\n dbc, err := h.server.GetDatabase();\n\n\tif err != nil {\n\t\t\th.logRequestLine()\n\t\t\treturn err\n\t}\n\t\n\t\n\t// Authenticate, if not on admin port:\n\tif h.privs != adminPrivs {\n\t\tif err := h.checkAuth(dbc); err != nil { \n\t\t\th.logRequestLine()\n\t\t\treturn err\n\t\t}\n\t}\n\t\n\th.logRequestLine()\n\n\t//assign db to handler h\n\n\treturn method(h) // Call the actual handler code\n\t\n}", "func (server *Server) handleRequestBlob(client *Client, message *Message) {\n\trequestBlob := &protocol.RequestBlob{}\n\terr := protobuf.Unmarshal(message.buffer, requestBlob)\n\tif err != nil {\n\t\tclient.Panic(err)\n\t\treturn\n\t}\n\n\t//userState := &protocol.UserState{}\n\n\t// Request for user textures\n\t// TODO: Why count if you only want to know 1 count?\n\tif len(requestBlob.SessionTexture) > 0 {\n\t\tfor _, sid := range requestBlob.SessionTexture {\n\t\t\tif target, ok := server.clients[sid]; ok {\n\t\t\t\t// TODO: NOT OK, use errors, don't leave everyone including yourself in the fucking dark\n\t\t\t\t// TODO: No, and its a validation!!!!!\n\t\t\t\tif target.user == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif target.user.HasTexture() {\n\t\t\t\t\t// TODO: Replace this shit alter, just get the first major structure changes in\n\t\t\t\t\t//buffer, err := blobStore.Get(target.user.TextureBlob)\n\t\t\t\t\t//if err != nil {\n\t\t\t\t\t//\tserver.Panic(err)\n\t\t\t\t\t//\treturn\n\t\t\t\t\t//}\n\t\t\t\t\t//userState.Reset()\n\t\t\t\t\t//userState.Session = protobuf.Uint32(uint32(target.Session()))\n\t\t\t\t\t//// TODO: What is a texture????? BETTER NAMES\n\t\t\t\t\t//userState.Texture = buffer\n\t\t\t\t\t//if err := client.sendMessage(userState); err != nil {\n\t\t\t\t\t//\tclient.Panic(err)\n\t\t\t\t\t//\treturn\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Request for user comments\n\t// TODO: Stop counting os high!\n\tif len(requestBlob.SessionComment) > 0 {\n\t\tfor _, sid := range requestBlob.SessionComment {\n\t\t\t// TODO: Err not ok!\n\t\t\tif target, ok := server.clients[sid]; ok {\n\t\t\t\t// TODO: REPEATED VALIDATION!!!!!\n\t\t\t\tif target.user == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif target.user.HasComment() {\n\t\t\t\t\t// TODO: Ughh just comment blob shit out now for the first major structure changes to work and tackle this after\n\t\t\t\t\t//buffer, err := requestBlob.Get(target.user.CommentBlob)\n\t\t\t\t\t//if err != nil {\n\t\t\t\t\t//\t// TODO: There is no reason to repeat these fucntions for each class, its just bad\n\t\t\t\t\t//\tserver.Panic(err)\n\t\t\t\t\t//\treturn\n\t\t\t\t\t//}\n\t\t\t\t\t//userState.Reset()\n\t\t\t\t\t//userState.Session = protobuf.Uint32(uint32(target.Session()))\n\t\t\t\t\t//userState.Comment = protobuf.String(string(buffer))\n\t\t\t\t\t//if err := client.sendMessage(userState); err != nil {\n\t\t\t\t\t//\tclient.Panic(err)\n\t\t\t\t\t//\treturn\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tchannelState := &protocol.ChannelState{}\n\n\t// Request for channel descriptions\n\t// TODO: Added up, there is SO MUCH WASTE. THESE ARE PER MESSAGE!\n\tif len(requestBlob.ChannelDescription) > 0 {\n\t\tfor _, cid := range requestBlob.ChannelDescription {\n\t\t\tif channel, ok := server.Channels[cid]; ok {\n\t\t\t\tif channel.HasDescription() {\n\t\t\t\t\tchannelState.Reset()\n\t\t\t\t\t//buffer, err := requestBlob.Get(channel.DescriptionBlob)\n\t\t\t\t\t//if err != nil {\n\t\t\t\t\t//\tserver.Panic(err)\n\t\t\t\t\t//\treturn\n\t\t\t\t\t//}\n\t\t\t\t\t//// TODO: you should be asking yourself, if you are doing a conversion everytime you use a variable, is there something majorly wrong? the answer is yes\n\t\t\t\t\t//channelState.ChannelID = protobuf.Uint32(channel.ID)\n\t\t\t\t\t//channelState.Description = protobuf.String(string(buffer))\n\t\t\t\t\t//if err := client.sendMessage(channelState); err != nil {\n\t\t\t\t\t//\tclient.Panic(err)\n\t\t\t\t\t//\treturn\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Server) handler(r request) response {\n\tvar endCode uint16\n\tdata := []byte{}\n\tswitch r.commandCode {\n\tcase CommandCodeMemoryAreaRead, CommandCodeMemoryAreaWrite:\n\t\tmemAddr := decodeMemoryAddress(r.data[:4])\n\t\tic := binary.BigEndian.Uint16(r.data[4:6]) // Item count\n\n\t\tswitch memAddr.memoryArea {\n\t\tcase MemoryAreaDMWord:\n\n\t\t\tif memAddr.address+ic*2 > DM_AREA_SIZE { // Check address boundary\n\t\t\t\tendCode = EndCodeAddressRangeExceeded\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif r.commandCode == CommandCodeMemoryAreaRead { //Read command\n\t\t\t\tdata = s.dmarea[memAddr.address : memAddr.address+ic*2]\n\t\t\t} else { // Write command\n\t\t\t\tcopy(s.dmarea[memAddr.address:memAddr.address+ic*2], r.data[6:6+ic*2])\n\t\t\t}\n\t\t\tendCode = EndCodeNormalCompletion\n\n\t\tcase MemoryAreaDMBit:\n\t\t\tif memAddr.address+ic > DM_AREA_SIZE { // Check address boundary\n\t\t\t\tendCode = EndCodeAddressRangeExceeded\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tstart := memAddr.address + uint16(memAddr.bitOffset)\n\t\t\tif r.commandCode == CommandCodeMemoryAreaRead { //Read command\n\t\t\t\tdata = s.bitdmarea[start : start+ic]\n\t\t\t} else { // Write command\n\t\t\t\tcopy(s.bitdmarea[start:start+ic], r.data[6:6+ic])\n\t\t\t}\n\t\t\tendCode = EndCodeNormalCompletion\n\n\t\tdefault:\n\t\t\tlog.Printf(\"Memory area is not supported: 0x%04x\\n\", memAddr.memoryArea)\n\t\t\tendCode = EndCodeNotSupportedByModelVersion\n\t\t}\n\n\tdefault:\n\t\tlog.Printf(\"Command code is not supported: 0x%04x\\n\", r.commandCode)\n\t\tendCode = EndCodeNotSupportedByModelVersion\n\t}\n\treturn response{defaultResponseHeader(r.header), r.commandCode, endCode, data}\n}", "func (server *Server) dispatch(address string) {\n\tdefer server.free_chan()\n\tif server.Stat.Connections[address] != nil {\n\t\tserver.Stat.Connections[address].State = \"conn_new_cmd\"\n\t}\n\tconnection := server.connections[address]\n\tconnectionReader := bufio.NewReader(connection)\n\t// let's loop the process for open connection, until it will get closed.\n\tfor {\n\t\t// let's read a header first\n\t\tif server.Stat.Connections[address] != nil {\n\t\t\tserver.Stat.Connections[address].State = \"conn_read\"\n\t\t}\n\t\treceived_message, n, err := readRequest(connectionReader, -1)\n\t\tif err != nil {\n\t\t\tif server.Stat.Connections[address] != nil {\n\t\t\t\tserver.Stat.Connections[address].State = \"conn_swallow\"\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\tserver.Logger.Info(\"Input stream has got EOF, and now is being closed.\")\n\t\t\t\tserver.breakConnection(connection)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tserver.Logger.Warning(\"Dispatching error: \", err, \" Message: \", received_message)\n\t\t\tif !server.makeResponse(connection, []byte(\"ERROR\\r\\n\"), 5){\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tif server.Stat.Connections[address] != nil {\n\t\t\t\tserver.Stat.Connections[address].Cmd_hit_ts = time.Now().Unix()\n\t\t\t}\n\t\t\t// Here the message should be handled\n\t\t\tserver.Stat.Read_bytes += uint64(n)\n\t\t\tparsed_request := protocol.ParseProtocolHeader(string(received_message[ : n - 2]))\n\t\t\tserver.Logger.Info(\"Header: \", *parsed_request)\n\n\t\t\tif (parsed_request.Command() == \"cas\" || parsed_request.Command() == \"gets\") && server.cas_disabled ||\n\t\t\t parsed_request.Command() == \"flush_all\" && server.flush_disabled{\n\t\t\t\terr_msg := parsed_request.Command() + \" command is forbidden.\"\n\t\t\t\tserver.Logger.Warning(err_msg)\n\t\t\t\tif server.Stat.Connections[address] != nil {\n\t\t\t\t\tserver.Stat.Connections[address].State = \"conn_write\"\n\t\t\t\t}\n\t\t\t\terr_msg = strings.Replace(protocol.CLIENT_ERROR_TEMP, \"%s\", err_msg, 1)\n\t\t\t\tserver.makeResponse(connection, []byte(err_msg), len(err_msg))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif parsed_request.DataLen() > 0 {\n\t\t\t\tif server.Stat.Connections[address] != nil {\n\t\t\t\t\tserver.Stat.Connections[address].State = \"conn_nread\"\n\t\t\t\t}\n\t\t\t\treceived_message, _, err := readRequest(connectionReader, parsed_request.DataLen())\n\t\t\t\tif err != nil {\n\t\t\t\t\tserver.Logger.Error(\"Error occurred while reading data:\", err)\n\t\t\t\t\tserver.breakConnection(connection)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tparsed_request.SetData(received_message[0 : ])\n\t\t\t}\n\t\t\tserver.Logger.Info(\"Start handling request:\", *parsed_request)\n\t\t\tresponse_message, err := parsed_request.HandleRequest(server.storage, server.Stat)\n\t\t\tserver.Logger.Info(\"Server is sending response:\\n\", string(response_message[0 : len(response_message)]))\n\t\t\t// if there is no flag \"noreply\" in the header:\n\t\t\tif parsed_request.Reply() {\n\t\t\t\tif server.Stat.Connections[address] != nil {\n\t\t\t\t\tserver.Stat.Connections[address].State = \"conn_write\"\n\t\t\t\t}\n\t\t\t\tserver.makeResponse(connection, response_message, len(response_message))\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tserver.Logger.Error(\"Impossible to send response:\", err)\n\t\t\t\tserver.breakConnection(connection)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif server.Stat.Connections[address] != nil {\n\t\t\tserver.Stat.Connections[address].State = \"conn_waiting\"\n\t\t}\n\t}\n}", "func (s *Server) HandleClient() {\n\tdefer s.Close()\n\n\tdb := DB.NewDataStore()\n\tdefer db.Close()\n\n\tvar msg message.Message\n\ts.r.Decode(&msg)\n\n\tif msg.CMD == command.Reserved {\n\t\treturn\n\t}\n\n\tswitch msg.CMD {\n\tcase command.Register:\n\t\tif msg.ULID != \"\" {\n\t\t\tlog.Infof(\"[%s] Processing Register command\", msg.ULID)\n\t\t} else {\n\t\t\tlog.Infof(\"[%s] Processing Register command\", s.conn.RemoteAddr())\n\t\t}\n\t\ts.processRegister(msg, db)\n\tcase command.Ping:\n\t\tif msg.ULID != \"\" {\n\t\t\tlog.Infof(\"[%s] Processing Ping command\", msg.ULID)\n\t\t} else {\n\t\t\tlog.Infof(\"[%s] Processing Ping command\", s.conn.RemoteAddr())\n\t\t}\n\t\ts.processPing(msg, db)\n\n\tcase command.ScanFile:\n\t\tif msg.ULID != \"\" {\n\t\t\tlog.Infof(\"[%s] Processing ScanFile command\", msg.ULID)\n\t\t} else {\n\t\t\tlog.Infof(\"[%s] Processing ScanFile command\", s.conn.RemoteAddr())\n\t\t}\n\t\ts.processScanFile(msg, db)\n\n\tcase command.ScanDir:\n\t\tif msg.ULID != \"\" {\n\t\t\tlog.Infof(\"[%s] Processing ScanDir command\", msg.ULID)\n\t\t} else {\n\t\t\tlog.Infof(\"[%s] Processing ScanDir command\", s.conn.RemoteAddr())\n\t\t}\n\t\ts.processScanDir(msg, db)\n\n\tcase command.ScanPID:\n\t\tif msg.ULID != \"\" {\n\t\t\tlog.Infof(\"[%s] Processing ScanPID command\", msg.ULID)\n\t\t} else {\n\t\t\tlog.Infof(\"[%s] Processing ScanPID command\", s.conn.RemoteAddr())\n\t\t}\n\t\ts.processScanPID(msg, db)\n\t}\n}", "func queryHandler(w http.ResponseWriter, r *http.Request) {\n\tkeys := readKeys(r.Body)\n\tservs := servers()\n\tnumServers := len(servs)\n\tserverKeys := groupKeysByServer(numServers, keys)\n\tresult := make([]QueryResponse, 0)\n\tfor idx, keys := range serverKeys {\n\t\tif len(keys) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tencodedList, err := json.Marshal(keys)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error marshalling list of keys:\", err)\n\t\t\tbreak\n\t\t}\n\t\tels := fetchQueryRespFromServer(servs[idx], encodedList)\n\t\tresult = append(result, decodeQueryResponse(els)...)\n\t}\n\tif len(keys) == len(result) {\n\t\tw.WriteHeader(http.StatusOK)\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\tjson.NewEncoder(w).Encode(result)\n}", "func handleGetRequest(rw rest.ResponseWriter, req *rest.Request) {\n\trw.WriteJson(map[string]string{\"body\": \"use POST https://localhost:433/sync, include authentication\"})\n}", "func main() {\n\n testBooks()\n //timesOfIndia();\n /*yt := make(chan interface{})\n go youTubeVideo(&yt,\"crime patrol\");\n\n msg:=<-yt\n fmt.Println(msg)*/\n\n\n\n //connectMong(\"hello\")\n\n\n // random no testing with encryption and decryption statement\n\n\n\n /*randTemp:=\"badcodercpp@gmail.com\"\n mnk:=generateHashAndReplicateToDbPratibhaPlease(&randTemp)\n jjh:=mnk[0]\n jjm:=mnk[1]\n kli, _ := strconv.ParseInt(jjm, 10, 64)\n //btB:=[]byte(jjh)\n fmt.Println(jjh)\n fmt.Println(jjm)\n fmt.Println(kli)\n rest:=authorizeThisFace(&jjh,&kli)\n fmt.Println(\"seperate_auth\")\n fmt.Println(rest)*/\n\n //end random no testing with encryption and decryption\n\n\n\n //paypal beg\n\n\n\n\n\n\n\n\n //paypal end\n\n\n //twillio start\n\n //sendOtpToTheMyUserAjay(\"+919470717982\",\"Dhyan se dekhiya yahi hai ye ladki\")\n\n // twillio end\n\n // getMyAllNotification\n\n // alterDatingRequestTemplate\n\n\n port := os.Getenv(\"PORT\")\n if port == \"\" {\n log.Fatal(\"$PORT must be set\")\n }\n r := mux.NewRouter()\n r.HandleFunc(\"/\", serveMainTemplate)\n //r.HandleFunc(\"/signalRTC/{userId}/{rtcId}\",signalRTCHandler).Methods(\"GET\")\n r.HandleFunc(\"/login\", serveTemplate)\n r.HandleFunc(\"/saveMyDatingRequestPlease\", saveDatingRequestTemplate).Methods(\"POST\")\n r.HandleFunc(\"/alterDatingRequestPlease\", alterDatingRequestTemplate).Methods(\"POST\")\n r.HandleFunc(\"/loginMeToApp\", letTheUserLogin).Methods(\"POST\")\n r.HandleFunc(\"/getMyAllNotification/{target}\", getMyAllNotification).Methods(\"GET\")\n r.HandleFunc(\"/getAllSuggestion/{target}\", getAllVisibleForMe).Methods(\"GET\")\n r.HandleFunc(\"/modifyFcmCandidate/{candidate}/{status}\", setFCMCandidate).Methods(\"GET\")\n r.HandleFunc(\"/checkFcmCandidate/{candidate}\", getFCMCandidate).Methods(\"GET\")\n r.HandleFunc(\"/signup\", serveSignupTemplate)\n r.HandleFunc(\"/getAllD\", getAllData)\n r.HandleFunc(\"/removeAllD\", removeHashedData)\n r.HandleFunc(\"/signupApp\", signUpTheUser).Methods(\"POST\")\n r.HandleFunc(\"/any/{hash}/{Pkey}/{query}\", serveAnyTemplate)\n r.HandleFunc(\"/faces/{query}\", serveFaceTemplate)\n\n r.HandleFunc(\"/testdata/{hash}\", getidDataUrl)\n r.HandleFunc(\"/verifyHash/{hash}\", serveHashTemplate)\n\n r.HandleFunc(\"/zipvsid_anddata\", serveZipTemplate).Methods(\"POST\")\n r.HandleFunc(\"/alluserinazipcode/{zip}\", serveAllZipTemplate)\n\n r.HandleFunc(\"/bot/{interactionId}\", serveBotTemplate)\n r.HandleFunc(\"/workflow/{interactionId}/{workflowId}\", serveWorkflowTemplate)\n r.HandleFunc(\"/getMyCommonActionFacePratibha/{reference_id}/{Pkey}/{query}\", getMyCommonActionFacePratibhaHandler)\n r.HandleFunc(\"/myLinkedFaces\", serveMyLinedFaceTemplate)\n r.HandleFunc(\"/templateData\", serveDataTemplate)\n r.HandleFunc(\"/getMyOwnShopDetailsPratibhaPleaseLoveYou\", getMyOwnShopDetailsPratibhaPleaseLoveYouHandler)\n r.HandleFunc(\"/wowPratibhaYouLooksLikeAnAngel\", serveWowPratibhaYouLooksLikeAnAngel)\n r.HandleFunc(\"/wowPratibhaYouLooksLikeAnAngelPratibha\", serveWowPratibhaYouLooksLikeAnAngelPratibha)\n r.HandleFunc(\"/anyMore\",serveMoreVideosYoutube)\n r.HandleFunc(\"/anyBooks\",serveBooks)\n r.HandleFunc(\"/createMyJobPratibhaPleaseForMeSorry\",createMyJobPratibhaPleaseForMeSorryHandler).Methods(\"GET\")\n r.HandleFunc(\"/myTokenAuthTest\",myTokenAuthTest).Methods(\"GET\")\n r.HandleFunc(\"/createMyDirectConfessionPratibhaPleaseRecordMySin\",createMyDirectConfessionPratibhaPleaseRecordMySinHandler).Methods(\"GET\")\n r.HandleFunc(\"/seekDonationForMeAjayPlsTlfDonate\",seekDonationForMeAjayPlsTlfDonateHandler).Methods(\"GET\")\n r.HandleFunc(\"/submitMyLoyalityFormPratibhaPlsInDatingZone\",submitMyLoyalityFormPratibhaPlsInDatingZoneHandler).Methods(\"GET\")\n r.HandleFunc(\"/recieveMyPaymentPratibhaPleaseYouAreOnlyHopeOfMine\",recieveMyPaymentPratibhaPleaseYouAreOnlyHopeOfMineHandler).Methods(\"GET\")\n r.HandleFunc(\"/deleteMyAuthHashPratibhaPleaseHelp\",deleteMyAuthHashPratibhaPleaseHelpHandler).Methods(\"GET\")\n r.HandleFunc(\"/myDpWillBeEdittedPratibha\",myDpWillBeEdittedPratibhaHandler).Methods(\"GET\")\n r.HandleFunc(\"/letMeSeekMyJobPratibhaPlease\",letMeSeekMyJobPratibhaPleaseHandler).Methods(\"GET\")\n r.HandleFunc(\"/tumheDillaggibhulJaniParegiYaar\",tumheDillaggibhulJaniParegiYaarHandler)\n r.HandleFunc(\"/retriveMyEventSourceForMessagePratibha\",retriveMyEventSourceForMessagePratibhaHandler)\n r.HandleFunc(\"/saveMyMessagePratibhaPleaseHelp\",saveMyMessagePratibhaPleaseHelpHandler)\n r.HandleFunc(\"/replicateMyMessageToDbMongo\",replicateMyMessageToDbMongoHandler)\n r.HandleFunc(\"/getMyPostForProfilePratibhaPlease\",getMyPostForProfilePratibhaPleaseHandler)\n r.HandleFunc(\"/sendMyDateRequestPratibhaPlease\",sendMyDateRequestPratibhaPleaseHandler)\n r.HandleFunc(\"/letMeSeeMyPlaylistSongPratibhaPlease\",letMeSeeMyPlaylistSongPratibhaPleaseHandler)\n r.HandleFunc(\"/satayeMenuKyonOmyYaraIloveYou\",satayeMenuKyonOmyYaraIloveYouHandler)\n r.HandleFunc(\"/LinkMyFaceWithThemPratibhaPlease\",serveLinkMyFaceWithThemPratibhaPlease)\n r.HandleFunc(\"/getMyRelatedItemsToBuyPratibhaPlease\",getMyRelatedItemsToBuyPratibhaPleaseHandler)\n r.HandleFunc(\"/addItemToMyShopPratibhaPleaseLU\",addItemToMyShopPratibhaPleaseLUHandler)\n r.HandleFunc(\"/iLoveYouPratibhaSharmaAndIWillGetYouShopCreate\",iLoveYouPratibhaSharmaAndIWillGetYouShopCreateHandler)\n r.HandleFunc(\"/amazonQuery\",serveAmazonQuery)\n r.HandleFunc(\"/syncAmazonMongo\",syncAmazonMongoWebService)\n r.HandleFunc(\"/redirect\",redirectHandler)\n r.HandleFunc(\"/newPlaylistCreation\",newPlaylistCreationHandler)\n r.HandleFunc(\"/getMyAllRelatedPostBilla\",getMyAllRelatedPostBillaHandler)\n r.HandleFunc(\"/getMyAllRelatedFacesBilla\",getMyAllRelatedFacesBillaHandler)\n r.HandleFunc(\"/saveMyPostWithAttachment\",saveMyPostWithAttachmentHandler).Methods(\"POST\")\n r.HandleFunc(\"/mostPopularVideo/{newsType}\",timesOfIndia)\n r.HandleFunc(\"/linkAuth\", serveAuth).Methods(\"POST\")\n r.HandleFunc(\"/signUpMePlease\", serveAuthAndSignUp).Methods(\"POST\")\n r.HandleFunc(\"/fileUploadItemIcon\", uploadAndProcessMyNewDp).Methods(\"POST\")\n r.HandleFunc(\"/changingBytesOfCloudinaryDp\", changingBytesOfCloudinaryDpHandler).Methods(\"POST\")\n r.HandleFunc(\"/linkAuth\",notFound)\n r.NotFoundHandler = http.HandlerFunc(notFound)\n r.PathPrefix(\"/\").Handler(http.FileServer(http.Dir(\"./public/\")))\n http.Handle(\"/\", r)\n log.Println(\"Listening...to all\")\n http.ListenAndServe(\":\"+port, r)\n\n\n\n\n\n\n\n\n\n\n\n\n //Parse result\n /*if err == nil {\n aws := new(ItemLookupResponse)\n xml.Unmarshal([]byte(result), aws)\n //TODO: Use \"aws\" freely :-)\n }*/\n\n\n\n\n\n\n\n\n}", "func mainHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, HEAD\")\n\n\tif r.Method == \"POST\" {\n\t\tvar req dlRequest\n\t\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, \"bad request\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t// add to queue\n\t\tgo func(qreq *dlRequest) {\n\t\t\tm3u8.DlChan <- &m3u8.WJob{Type: m3u8.ListDL, URL: req.Url, DestPath: req.Path, Filename: req.Filename}\n\t\t}(&req)\n\t\tres := response{req.Url, req.Filename, \"Added to the queue\"}\n\t\tjson.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n}", "func (p *pbft) handlePrepare(content []byte) {\n\t//The Request structure is parsed using JSON\n\tpre := new(Prepare)\n\terr := json.Unmarshal(content, pre)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Printf(\"This node has received the Prepare message from %s ... \\n\", pre.NodeID)\n\t//\n\tMessageNodePubKey := p.getPubKey(pre.NodeID)\n\tdigestByte, _ := hex.DecodeString(pre.Digest)\n\tif _, ok := p.messagePool[pre.Digest]; !ok {\n\t\tfmt.Println(\"The current temporary message pool does not have this digest. Deny sending Commit message.\")\n\t} else if p.sequenceID != pre.SequenceID {\n\t\tfmt.Println(\"ID is not correct. Deny sending Commit message.\")\n\t} else if !p.RsaVerySignWithSha256(digestByte, pre.Sign, MessageNodePubKey) {\n\t\tfmt.Println(\"The signiture is not valid! Deny sending Commit message.\")\n\t} else {\n\t\tp.setPrePareConfirmMap(pre.Digest, pre.NodeID, true)\n\t\tcount := 0\n\t\tfor range p.prePareConfirmCount[pre.Digest] {\n\t\t\tcount++\n\t\t}\n\t\t//Since the primary node does not send Prepare message, so it does not include itself.\n\t\tspecifiedCount := 0\n\t\tif p.node.nodeID == \"N0\" {\n\t\t\tspecifiedCount = nodeCount / 3 * 2\n\t\t} else {\n\t\t\tspecifiedCount = (nodeCount / 3 * 2) - 1\n\t\t}\n\t\t\n\t\tp.lock.Lock()\n\t\t\n\t\tif count >= specifiedCount && !p.isCommitBordcast[pre.Digest] {\n\t\t\tfmt.Println(\"This node has received at least 2f (including itself) Prepare messages.\")\n\t\t\t\n\t\t\tsign := p.RsaSignWithSha256(digestByte, p.node.rsaPrivKey)\n\t\t\tc := Commit{pre.Digest, pre.SequenceID, p.node.nodeID, sign}\n\t\t\tbc, err := json.Marshal(c)\n\t\t\tif err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t\t\n\t\t\tfmt.Println(\"sending Commit message to other nodes...\")\n\t\t\tp.broadcast(cCommit, bc)\n\t\t\tp.isCommitBordcast[pre.Digest] = true\n\t\t\tfmt.Println(\"Commit is done.\")\n\t\t}\n\t\tp.lock.Unlock()\n\t}\n}", "func handleKVRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest) () {\n\tlog.Println(\"start handling request\")\n\tlog.Println(msgID)\n\tlog.Println(\"sender IP:\", net.IPv4(msgID[0], msgID[1], msgID[2], msgID[3]).String(), \":\", binary.LittleEndian.Uint16(msgID[4:6]))\n\tlog.Println(\"command:\", reqPay.Command)\n\tif reqPay.Addr == nil {\n\n\t\treqPay.Addr = []byte(clientAddr.String())\n\t}\n\n\t// Try to find the response in the cache\n\tif respMsgBytes, ok := GetCachedResponse(msgID); ok {\n\t\t// Send the message back to the client\n\t\t_, _ = conn.WriteToUDP(respMsgBytes, clientAddr)\n\t} else {\n\t\t// Handle the command\n\t\trespPay := pb.KVResponse{}\n\n\t\t/*\n\t\t\tIf the command is PUT, GET or REMOVE, check whether the key exists in\n\t\t\tthis node first. Otherwise,\n\t\t*/\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\t// respPay.ErrCode = Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase GET:\n\t\t\t// var version int32\n\t\t\t// respPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t// respPay.Version = &version\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\tvar version int32\n\t\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t\trespPay.Version = version\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay,msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\t//log.Println(\"############################################################################\")\n\t\t\t//log.Println(\"########################### SHUT DOWN ! ####################################\")\n\t\t\t//log.Println(\"############################################################################\")\n\n\t\t\tshutdown <- true\n\t\t\treturn\n\t\tcase WIPEOUT:\n\t\t\trespPay.ErrCode = RemoveAll()\n\t\t\tnormalReplicate(WIPEOUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := int32(1) // Unused, return 1 for now\n\t\t\trespPay.MembershipCount = members\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_LIST:\n\t\t\tGetMemberShipList(clientAddr, msgID, respPay)\n\t\t\treturn\n\t\t//forward request\n\t\tcase PUT_FORWARD:\n\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase GET_FORWARD:\n\t\t\tvar version int32\n\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\trespPay.Version = version\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase REMOVE_FORWARD:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase PUT_REPLICATE_SON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 0)\n\t\t\treturn\n\t\tcase PUT_REPLICATE_GRANDSON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 1)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_SON:\n\t\t\tRemoveReplicate(reqPay.Key, 0)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_GRANDSON:\n\t\t\tRemoveReplicate(reqPay.Key, 1)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_SON:\n\t\t\tWipeoutReplicate(0)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_GRANDSON:\n\t\t\tWipeoutReplicate(1)\n\t\t\treturn\n\n\t\tcase GRANDSON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(FATHER_DIED, KVStore, addr)\n\t\t\treturn\n\t\tcase SON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(GRANDFATHER_DIED_1, KVStore, addr)\n\t\t\treturn\n\n\t\tcase HELLO:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\t\t\treceiveHello(addr, msgID)\n\t\t\treturn\n\t\tdefault:\n\t\t\trespPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t}\n\n\t\t// Send the response\n\t\tsendResponse(clientAddr, msgID, respPay)\n\t}\n}", "func getTokenswapHandler(clientCtx client.Context) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tclientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\thash := mux.Vars(r)[\"tx_hash\"]\n\t\tparam := types.NewQueryTokenswapParam(hash)\n\n\t\tbz, err := clientCtx.LegacyAmino.MarshalJSON(param)\n\t\tif rest.CheckBadRequestError(w, err) {\n\t\t\treturn\n\t\t}\n\n\t\tres, height, err := clientCtx.QueryWithData(fmt.Sprintf(\"custom/%s/%s\", types.QuerierRoute, types.QueryTokenswap), bz)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusNotFound, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tclientCtx = clientCtx.WithHeight(height)\n\t\trest.PostProcessResponse(w, clientCtx, res)\n\t}\n}", "func bungieCallback(c *gin.Context) {\n code := c.Query(\"code\")\n state := c.Query(\"state\")\n\n // Now use the code to receive an access token\n client := &http.Client{}\n data := url.Values{}\n data.Set(\"grant_type\", \"authorization_code\")\n data.Set(\"code\", code)\n req, _ := http.NewRequest(\"POST\", \"https://www.bungie.net/platform/app/oauth/token/\", strings.NewReader(data.Encode()))\n req.Header.Add(\"Authorization\", \"Basic \" + base64.StdEncoding.EncodeToString([]byte(os.Getenv(\"CLIENT_ID\") + \":\" + os.Getenv(\"CLIENT_SECRET\"))))\n req.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n resp, _ := client.Do(req)\n\n // Assess GetToken Response Code\n if resp.StatusCode == http.StatusOK {\n var tokenResponse TokenResponse\n // This could potentialy be changed to use unmarshalling to save memory\n err := json.NewDecoder(resp.Body).Decode(&tokenResponse)\n // err := json.Unmarshal(resp.Body, &tokenResponse)\n resp.Body.Close()\n if err != nil {\n fmt.Println(err)\n }\n\n deleteUser(state)\n\n // Collect the available destiny membership id(s) as an array\n req, _ = http.NewRequest(\"GET\", \"https://www.bungie.net/platform/User/GetBungieAccount/\" + tokenResponse.Membership_id + \"/254/\", nil)\n req.Header.Add(\"X-API-Key\", os.Getenv(\"API_KEY\"))\n resp, _ = client.Do(req)\n\n // Assess GetBungieAccount Response Code\n if resp.StatusCode == http.StatusOK {\n destinyMemberships := make([]Membership, 0)\n\n // Determine which Destiny membership IDs are associated with the Bungie account\n var accountResponse interface{}\n err = json.NewDecoder(resp.Body).Decode(&accountResponse)\n resp.Body.Close()\n\n accountMap := accountResponse.(map[string]interface{})\n responseMap := accountMap[\"Response\"].(map[string]interface{})\n destinyMembershipsArray := responseMap[\"destinyMemberships\"].([]interface{})\n\n activeMembership := \"-1\"\n for _, u := range destinyMembershipsArray {\n valuesMap := u.(map[string]interface{})\n\n\n //////\n ////\n //// For now, we assume PC is the active membership\n activeMembershipType := valuesMap[\"membershipType\"].(float64)\n if ( activeMembershipType == 3 ) {\n activeMembership = valuesMap[\"membershipId\"].(string)\n fmt.Println( \"Active Membership: \" + valuesMap[\"displayName\"].(string) )\n }\n //// Replace with getActiveMembership() implementation\n ////\n //////\n\n\n tmpMembership := Membership{activeMembershipType, valuesMap[\"membershipId\"].(string)}\n destinyMemberships = append(destinyMemberships, tmpMembership)\n }\n\n // Empty User Values\n loadouts := make([]Loadout, 0)\n\n // Insert new user entry\n newUser := User{loadouts, destinyMemberships, state, activeMembership, \"-1\", tokenResponse.Access_token, tokenResponse.Refresh_token}\n createUser(newUser)\n } else {\n // Error in GetBungieAccount\n fmt.Println(resp.StatusCode)\n }\n\n } else {\n // Error in GetTokenResponse\n fmt.Println(resp.StatusCode)\n }\n}", "func (c *Operation) callback(w http.ResponseWriter, r *http.Request) { //nolint: funlen,gocyclo\n\tif len(r.URL.Query()[\"error\"]) != 0 {\n\t\tif r.URL.Query()[\"error\"][0] == \"access_denied\" {\n\t\t\thttp.Redirect(w, r, c.homePage, http.StatusTemporaryRedirect)\n\t\t}\n\t}\n\n\ttk, err := c.tokenIssuer.Exchange(r)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to exchange code for token: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to exchange code for token: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\t// user info from token will be used for to retrieve data from cms\n\tinfo, err := c.tokenResolver.Resolve(tk.AccessToken)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get token info: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get token info: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tuserID, subject, err := c.getCMSData(tk, \"email=\"+info.Subject, info.Scope)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get cms data: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get cms data: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tcallbackURLCookie, err := r.Cookie(callbackURLCookie)\n\tif err != nil && !errors.Is(err, http.ErrNoCookie) {\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get authMode cookie: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tif callbackURLCookie != nil && callbackURLCookie.Value != \"\" {\n\t\ttxnID := uuid.NewString()\n\t\tdata := txnData{\n\t\t\tUserID: userID,\n\t\t\tScope: info.Scope,\n\t\t\tToken: tk.AccessToken,\n\t\t}\n\n\t\tdataBytes, mErr := json.Marshal(data)\n\t\tif mErr != nil {\n\t\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\t\tfmt.Sprintf(\"failed to marshal txn data: %s\", mErr.Error()))\n\t\t\treturn\n\t\t}\n\n\t\terr = c.store.Put(txnID, dataBytes)\n\t\tif err != nil {\n\t\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\t\tfmt.Sprintf(\"failed to save txn data: %s\", err.Error()))\n\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, callbackURLCookie.Value+\"?txnID=\"+txnID, http.StatusTemporaryRedirect)\n\n\t\treturn\n\t}\n\n\tvcsProfileCookie, err := r.Cookie(vcsProfileCookie)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get cookie: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusBadRequest,\n\t\t\tfmt.Sprintf(\"failed to get cookie: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tcred, err := c.prepareCredential(subject, info.Scope, vcsProfileCookie.Value)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to create credential: %s\", err.Error())\n\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\tfmt.Sprintf(\"failed to create credential: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\tt, err := template.ParseFiles(c.didAuthHTML)\n\tif err != nil {\n\t\tlogger.Errorf(err.Error())\n\t\tc.writeErrorResponse(w, http.StatusInternalServerError,\n\t\t\tfmt.Sprintf(\"unable to load html: %s\", err.Error()))\n\n\t\treturn\n\t}\n\n\tif err := t.Execute(w, map[string]interface{}{\n\t\t\"Path\": generate + \"?\" + \"profile=\" + vcsProfileCookie.Value,\n\t\t\"Cred\": string(cred),\n\t}); err != nil {\n\t\tlogger.Errorf(fmt.Sprintf(\"failed execute qr html template: %s\", err.Error()))\n\t}\n}", "func is_accepted(w http.ResponseWriter, r *http.Request) {\r\n\tfmt.Println(\"\\n Api Hit====>isAccepted\")\r\n\tvar vars = mux.Vars(r)\r\n\tvar id = vars[\"id\"]\r\n\tproc := cache[id]\r\n\tflag := isAccepted(proc)\r\n\tif flag {\r\n\t\tjson.NewEncoder(w).Encode(\"Input tokens successfully Accepted\")\r\n\t} else {\r\n\t\tjson.NewEncoder(w).Encode(\"Input tokens Rejected by the PDA\")\r\n\t}\r\n}", "func D2CloudSyncHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Infoln(\"D2CloudSyncHandler invoked\", r.Method, r.URL.Path, r.RemoteAddr)\n\n\tvars := mux.Vars(r)\n\tdevid := vars[\"deviceid\"]\n\n\tlimit, _ := strconv.Atoi(r.URL.Query().Get(\"limit\"))\n\toffset, _ := strconv.Atoi(r.URL.Query().Get(\"offset\"))\n\tif limit <= 0 {\n\t\tlimit = 50\n\t}\n\n\tif devid == \"\" {\n\t\trespondError(w, http.StatusBadRequest, \"deviceid is null\")\n\t\treturn\n\t}\n\ta := Application{\n\t\tDeviceid: devid,\n\t}\n\tSendMqAction(append([]Application{}, a), ACTSTATUS)\n\ttime.Sleep(1 * time.Second)\n\n\tapps, err := DBscanBydeviceid(devid)\n\tif err != nil {\n\t\trespondError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tif limit > 0 {\n\t\tvar HttpApps RespHttpList\n\t\tapplength := len(apps)\n\t\tif offset+limit < applength {\n\t\t\tHttpApps = AppsToHttp(apps[offset:(offset + limit)])\n\t\t} else if offset < applength {\n\t\t\tHttpApps = AppsToHttp(apps[offset:])\n\t\t}\n\t\tHttpApps.Limit = limit\n\t\tHttpApps.Offset = offset\n\t\tHttpApps.Total = applength\n\n\t\trespondJSON(w, http.StatusOK, HttpApps)\n\t\treturn\n\t}\n\trespondJSON(w, http.StatusOK, AppsToHttp(apps))\n}", "func (s *Server) handlerConn(c net.Conn) {\n\tdefer c.Close()\n\tbuf := make([]byte, 2048)\n\trcvPacketSize, err := c.Read(buf)\n\tif err != nil && err != io.EOF {\n\t\tlog.Println(\"Read error: \", err)\n\t\treturn\n\t}\n\tdata := buf[:rcvPacketSize]\n\n\trec := strings.Split(string(data), \" \")\n\tlog.Println(\"Received data: \", rec)\n\n\t// rec must have 3 field (as at form)\n\tif len(rec) <= 3 {\n\t\tif err := s.db.Insert(rec); err != nil {\n\t\t\tlog.Printf(\"Insert error: %v\\n\", err)\n\t\t}\n\t\tlog.Printf(\"Save record in DB: %v\\n\", rec)\n\n\t\tif _, err = c.Write([]byte(\"OK\")); err != nil {\n\t\t\tlog.Printf(\"Response send error: %v\\n\", err)\n\t\t}\n\t}\n}", "func handleReadRequest(url string, httpMethod string, JWT_Token string) (response []byte, err error) {\n\thttpClient := &http.Client{}\n\t\n\tvar req *http.Request\n\treq, err = http.NewRequest(httpMethod, url, nil)\n\tif err != nil {\n\t\treturn \n\t}\n\n\treq.Header.Add(\"Authorization\", \"Bearer \"+JWT_Token)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresponse, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n\n}", "func (ctx *Context) handle() {\n\thandlers := append(ctx.g.handlers, ctx.g.defaultHandler)\n\tfor _, h := range handlers {\n\t\tvals, err := ctx.Call(h, ctx.g.Injector)\n\n\t\t// If a Handler returns values, and if the first value is a glue.AfterHandler\n\t\t// defer it to allow post-request logic\n\t\tif len(vals) > 0 {\n\t\t\tif vals[0].Type() == reflect.TypeOf(AfterHandler(nil)) {\n\t\t\t\tafterFn := vals[0].Interface().(AfterHandler)\n\t\t\t\tdefer afterFn(*ctx)\n\t\t\t} else if len(vals) == 1 {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It is instead of type: %+v\\n\", AfterHandler(nil), vals[0].Type())\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It instead returned %d values: %+v\", AfterHandler(nil), len(vals), vals)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif ctx.rw.WroteHeader() {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func indexApiHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Go card!\\n\"))\n}", "func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\n\t// Extract auth code\n\tauthReq := h.client.NewAuthorizeRequest(osincli.CODE)\n\tauthData, err := authReq.HandleRequest(req)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error handling request: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\tglog.V(4).Infof(\"Got auth data\")\n\n\t// Validate state before making any server-to-server calls\n\tok, err := h.state.Check(authData.State, req)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error verifying state: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\tif !ok {\n\t\tglog.V(4).Infof(\"State is invalid\")\n\t\terr := errors.New(\"State is invalid\")\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\t// Exchange code for a token\n\taccessReq := h.client.NewAccessRequest(osincli.AUTHORIZATION_CODE, authData)\n\taccessData, err := accessReq.GetToken()\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error getting access token: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\tglog.V(5).Infof(\"Got access data\")\n\n\tidentity, ok, err := h.provider.GetUserIdentity(accessData)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error getting userIdentityInfo info: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\tif !ok {\n\t\tglog.V(4).Infof(\"Could not get userIdentityInfo info from access token\")\n\t\terr := errors.New(\"Could not get userIdentityInfo info from access token\")\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\tuser, err := h.mapper.UserFor(identity)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error creating or updating mapping for: %#v due to %v\", identity, err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\tglog.V(4).Infof(\"Got userIdentityMapping: %#v\", user)\n\n\t_, err = h.success.AuthenticationSucceeded(user, authData.State, w, req)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error calling success handler: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n}", "func (app *App) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\r\n\treturn func(w http.ResponseWriter, r *http.Request) {\r\n\t\thandler(app.DB, w, r)\r\n\t}\r\n}", "func (s *Network) handleConn(ctx context.Context, conn net.Conn) {\n\tdefer conn.Close()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\t// read the request from connection\n\t\trequest, err := decode(conn)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.WithContext(ctx).WithError(err).Error(\"read and decode failed\")\n\t\t\treturn\n\t\t}\n\n\t\tvar response []byte\n\t\tswitch request.MessageType {\n\t\tcase FindNode:\n\t\t\tencoded, err := s.handleFindNode(ctx, request)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithContext(ctx).WithError(err).Error(\"handle find node request failed\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse = encoded\n\t\tcase FindValue:\n\t\t\t// handle the request for finding value\n\t\t\tencoded, err := s.handleFindValue(ctx, request)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithContext(ctx).WithError(err).Error(\"handle find value request failed\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse = encoded\n\t\tcase Ping:\n\t\t\tencoded, err := s.handlePing(ctx, request)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithContext(ctx).WithError(err).Error(\"handle ping request failed\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse = encoded\n\t\tcase StoreData:\n\t\t\t// handle the request for storing data\n\t\t\tencoded, err := s.handleStoreData(ctx, request)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithContext(ctx).WithError(err).Error(\"handle store data request failed\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresponse = encoded\n\t\tdefault:\n\t\t\tlog.WithContext(ctx).Errorf(\"impossible: invalid message type: %v\", request.MessageType)\n\t\t\treturn\n\t\t}\n\n\t\t// write the response\n\t\tif _, err := conn.Write(response); err != nil {\n\t\t\tlog.WithContext(ctx).WithError(err).Error(\"conn write: failed\")\n\t\t}\n\t}\n}", "func HandleGetDatabaseConfig(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\t\tctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)\n\t\tdefer cancel()\n\n\t\t// get project id and dbType from url\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\t\tdbAlias := \"\"\n\t\tdbAliasQuery, exists := r.URL.Query()[\"dbAlias\"]\n\t\tif exists {\n\t\t\tdbAlias = dbAliasQuery[0]\n\t\t}\n\t\tdbConfig, err := syncMan.GetDatabaseConfig(ctx, projectID, dbAlias)\n\t\tif err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t_ = utils.SendResponse(w, http.StatusOK, model.Response{Result: dbConfig})\n\t}\n}", "func process(w http.ResponseWriter, r *http.Request, connectionType string) {\n\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-type\", \"text/plain\")\n\n\tvar macAddress string\n\tvar response string\n\n\tclientIP, _, netSplitErr := net.SplitHostPort(r.RemoteAddr)\n\n\tif netSplitErr != nil {\n\n\t\tlogger.Error(netSplitErr.Error())\n\t\thttp.Error(w, \"Invalid host IP/PORT\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif r.Method == \"GET\" {\n\t\tmacAddress = r.URL.Path[1:]\n\t} else {\n\t\thttp.Error(w, r.Method+\" requests not accepted\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tif macAddress == \"\" {\n\t\thttp.Error(w, \"No MAC address provided\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcleanedMacAddress := cleanMacAddress(macAddress)\n\tcleanedAddressLength := len(cleanedMacAddress)\n\n\tvar vendor string\n\n\taddressMap.RLock()\n\tdefer addressMap.RUnlock()\n\n\tif cleanedAddressLength >= 9 {\n\t\t// Check for MA-S match\n\t\tif val, ok := addressMap.m[cleanedMacAddress[0:9]]; ok {\n\t\t\tvendor = val\n\t\t}\n\t}\n\n\tif vendor == \"\" && cleanedAddressLength >= 7 {\n\t\t// Check for MA-M match\n\t\tif val, ok := addressMap.m[cleanedMacAddress[0:7]]; ok {\n\t\t\tvendor = val\n\t\t}\n\t}\n\n\tif vendor == \"\" && cleanedAddressLength >= 6 {\n\t\t// Check for MA-L match\n\t\tif val, ok := addressMap.m[cleanedMacAddress[0:6]]; ok {\n\t\t\tvendor = val\n\t\t}\n\t}\n\n\tif vendor != \"\" {\n\t\tio.WriteString(w, vendor)\n\t\tresponse = vendor\n\t} else {\n\t\thttp.Error(w, \"Vendor not found\", http.StatusNotFound)\n\t\tresponse = \"Not Found\"\n\t}\n\n\tlogger.Info(\n\t\t\"api request\",\n\t\tzap.String(\"clientIp\", clientIP),\n\t\tzap.String(\"connectionType\", connectionType),\n\t\tzap.String(\"method\", r.Method),\n\t\tzap.String(\"macAddress\", cleanedMacAddress),\n\t\tzap.String(\"response\", response),\n\t)\n\n}", "func handleRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte) {\n\tif respMsgBytes := responseCache.Get(msgID, getNetAddress(clientAddr)); respMsgBytes != nil {\n\t\tfmt.Println(\"Handle repeated request - 😡\", respMsgBytes, \"sending to \", clientAddr.Port)\n\n\t\t_, err := conn.WriteToUDP(respMsgBytes, clientAddr)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"handleRequest WriteToUDP\", err)\n\t\t}\n\t} else {\n\t\tincomingCache.Add(msgID, clientAddr)\n\n\t\trespPay := pb.KVResponse{}\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\tfmt.Println(\"+PUT request come in from\", clientAddr.Port)\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\n\t\t\t\tfmt.Println(\"who's sending responsee 🤡 \", self.Addr.String(), \" to \", clientAddr.Port)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second) {\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase GET:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tvar version int32\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[0].Get(reqPay.Key)\n\t\t\t\trespPay.Version = &version\n\t\t\t\t// TODO: check failure, then send request to other two nodes.\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Get(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Remove(reqPay.Key)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second){\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error (can't revert primary lol)\n\t\t\t\t\tfmt.Println(\"????? can't remove fully??\")\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Remove(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\tshutdown <- true\n\t\tcase WIPEOUT:\n\t\t\tif reqPay.ReplicaNum != nil {\n\t\t\t\tdataStorage.Replicas[*reqPay.ReplicaNum].RemoveAll()\n\t\t\t} else {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].RemoveAll()\n\t\t\t\tdataStorage.Replicas[1].RemoveAll()\n\t\t\t\tdataStorage.Replicas[2].RemoveAll()\n\t\t\t}\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = &pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := GetMembershipCount()\n\t\t\trespPay.MembershipCount = &members\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase NOTIFY_FAUILURE:\n\t\t\tfailedNode := GetNodeByIpPort(*reqPay.NodeIpPort)\n\t\t\tif failedNode != nil {\n\t\t\t\tfmt.Println(self.Addr.String(), \" STARTT CONTIUE GOSSSSSSIP 👻💩💩💩💩💩🤢🤢🤢🤢\", *reqPay.NodeIpPort, \"failed\")\n\t\t\t\tRemoveNode(failedNode)\n\t\t\t\tstartGossipFailure(failedNode)\n\t\t\t}\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase ADD_REPLICA:\n\t\t\tkv := dataStorage.decompressReplica(reqPay.Value)\n\t\t\tdataStorage.addReplica(kv, int(*reqPay.ReplicaNum))\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase SEND_REPLICA:\n\t\t\trespPay.Value = dataStorage.compressReplica(int(*reqPay.ReplicaNum))\n\t\t\trespPay.ReceiveData = true\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase RECOVER_PREV_NODE_KEYSPACE:\n\t\t\t// TODO: error handling on and internal failure\n\t\t\tRecoverDataStorage()\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase TEST_GOSSIP:\n\t\t\tfmt.Println(self.Addr.String(), \" TESTING GOSSIP 😡\", *reqPay.NodeIpPort, \"failed\")\n\t\t\tRemoveNode(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\t\tstartGossipFailure(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\tcase TEST_RECOVER_REPLICA:\n\t\t\treqPay := pb.KVRequest{Command: SHUTDOWN}\n\t\t\tsendRequestToNodeUUID(reqPay, self.prevNode())\n\t\t\tRemoveNode(self.prevNode())\n\n\t\t\tRecoverDataStorage()\n\t\tdefault:\n\t\t\t//respPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t\t//sendResponse(clientAddr, msgID, respPay)\n\t\t}\n\t}\n\tprintReplicas(self.Addr.String())\n}", "func (api *Api) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\thandler(api.DB, w, r)\n\t}\n}", "func userCartHandler(formatter *render.Render) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\t/**\n\t\t\tMongo server setup\n\t\t**/\n\t\tsession, err := mgo.Dial(mongodb_server)\n if err != nil {\n fmt.Println(\"mongoserver panic\")\n }\n defer session.Close()\n session.SetMode(mgo.Monotonic, true)\n u := session.DB(mongodb_database).C(\"cart\")\n s := session.DB(mongodb_database).C(\"score\")\n c := session.DB(mongodb_database).C(\"cloth\")\n\t\t/**\n\t\t\tGet Post body\n\t\t**/ \n // body, err := ioutil.ReadAll(req.Body)\n\t\t// if err != nil {\n\t\t// \tlog.Fatalln(err)\n\t\t// }\n\t\t// fmt.Println(body)\n\n\t\t// var userPostResult UserPostId\n\t\t// json.Unmarshal(body, &userPostResult)\n\n\t\t// userId := userPostResult.UserId\n\n\t\tparams := mux.Vars(req)\n\t\tvar userId string = params[\"userId\"]\n\t\tfmt.Println(\"userId\", userId)\n\t\t/**\n\t\t\tGet cloth id by userid\n\t\t**/\n\t\tvar clothIdResult []bson.M\n\t\terr = u.Find(bson.M{\"userId\": userId}).All(&clothIdResult)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Get cloth id panic\")\n\t\t}\n\t\tcount := len(clothIdResult)\n\t\t/*\n\t\t\tDeclare return response\n\t\t*/\n\t\tresponse := make([]Predict, count)\n\n\t\tfor i := 0; i < count; i++ {\n\t\t\tclothSingleResult := clothIdResult[i]\n\t\t\tclothId := clothSingleResult[\"clothId\"].(string)\n\t\t\tvar clothInfo bson.M\n\t\t\terr = c.Find(bson.M{\"clothesId\": clothId}).One(&clothInfo)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Get cloth info panic\")\n\t\t\t}\n\t\t\tresponse[i].ClothId = clothId\n\t\t\tresponse[i].Url = clothInfo[\"url\"].(string)\n\t\t\tresponse[i].Name = clothInfo[\"name\"].(string)\n\t\t\tresponse[i].Price = clothInfo[\"price\"].(string)\n\t\t\tvar clothScore bson.M\n\t\t\terr = s.Find(bson.M{\"id\": clothId}).One(&clothScore)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Get cloth score panic\")\n\t\t\t}\n\t\t\tresponse[i].Score = clothScore[\"score\"].(string)\n\t\t}\n \n\t\tformatter.JSON(w, http.StatusOK, response)\n\t}\n}", "func (c *Client) ProcessRequest(req [][]byte) (err error) {\n\tvar (\n\t\tcommand Command\n\t)\n\tlog.Debugf(\"req:%v,%s\", strings.ToUpper(string(req[0])), req[1:])\n\tif len(req) == 0 {\n\t\tc.cmd = \"\"\n\t\tc.args = nil\n\t} else {\n\t\tc.cmd = strings.ToUpper(string(req[0]))\n\t\tc.args = req[1:]\n\t}\n\tif c.cmd != \"AUTH\" {\n\t\tif !c.isAuth {\n\t\t\tc.FlushResp(qkverror.ErrorNoAuth)\n\t\t\treturn nil\n\t\t}\n\t}\n\tlog.Debugf(\"command: %s argc:%d\", c.cmd, len(c.args))\n\tswitch c.cmd {\n\tcase \"AUTH\":\n\t\tif len(c.args) != 1 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tif c.auth == \"\" {\n\t\t\tc.FlushResp(qkverror.ErrorServerNoAuthNeed)\n\t\t} else if string(c.args[0]) != c.auth {\n\t\t\tc.isAuth = false\n\t\t\tc.FlushResp(qkverror.ErrorAuthFailed)\n\t\t} else {\n\t\t\tc.isAuth = true\n\t\t\tc.w.FlushString(\"OK\")\n\t\t}\n\t\treturn nil\n\tcase \"MULTI\":\n\t\tlog.Debugf(\"client transaction\")\n\t\tc.txn, err = c.tdb.NewTxn()\n\t\tif err != nil {\n\t\t\tc.resetTxn()\n\t\t\tc.w.FlushBulk(nil)\n\t\t\treturn nil\n\t\t}\n\t\tc.isTxn = true\n\t\tc.cmds = []Command{}\n\t\tc.respTxn = []interface{}{}\n\t\tc.w.FlushString(\"OK\")\n\t\terr = nil\n\t\treturn\n\tcase \"EXEC\":\n\t\tlog.Debugf(\"command length : %d txn:%v\", len(c.cmds), c.isTxn)\n\t\tif len(c.cmds) == 0 || !c.isTxn {\n\t\t\tc.w.FlushBulk(nil)\n\t\t\tc.resetTxn()\n\t\t\treturn nil\n\t\t}\n\t\tfor _, cmd := range c.cmds {\n\t\t\tlog.Debugf(\"execute command: %s\", cmd.cmd)\n\t\t\tc.cmd = cmd.cmd\n\t\t\tc.args = cmd.args\n\t\t\tif err = c.execute(); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tc.txn.Rollback()\n\t\t\tc.w.FlushBulk(nil)\n\t\t} else {\n\t\t\terr = c.txn.Commit(context.Background())\n\t\t\tif err == nil {\n\t\t\t\tc.w.FlushArray(c.respTxn)\n\t\t\t} else {\n\t\t\t\tc.w.FlushBulk(nil)\n\t\t\t}\n\t\t}\n\t\tc.resetTxn()\n\t\treturn nil\n\tcase \"DISCARD\":\n\t\t// discard transactional commands\n\t\tif c.isTxn {\n\t\t\terr = c.txn.Rollback()\n\t\t}\n\t\tc.w.FlushString(\"OK\")\n\t\tc.resetTxn()\n\t\treturn err\n\tcase \"PING\":\n\t\tif len(c.args) != 0 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tc.w.FlushString(\"PONG\")\n\t\treturn nil\n\t}\n\tif c.isTxn {\n\t\tcommand = Command{cmd: c.cmd, args: c.args}\n\t\tc.cmds = append(c.cmds, command)\n\t\tlog.Debugf(\"command:%s added to transaction queue, queue size:%d\", c.cmd, len(c.cmds))\n\t\tc.w.FlushString(\"QUEUED\")\n\t} else {\n\t\tc.execute()\n\t}\n\treturn\n\n}", "func BobPurchaseDataAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tLog.Infof(\"start purchase data...\")\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_BOB_TX\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\trequestData := r.FormValue(\"request_data\")\n\tvar data RequestData\n\terr := json.Unmarshal([]byte(requestData), &data)\n\tif err != nil {\n\t\tLog.Warnf(\"invalid parameter. data=%v, err=%v\", requestData, err)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"success to parse request data. data=%v\", requestData)\n\n\tif data.MerkleRoot == \"\" || data.AliceIP == \"\" || data.AliceAddr == \"\" || data.BulletinFile == \"\" || data.PubPath == \"\" {\n\t\tLog.Warnf(\"invalid parameter. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"read parameters. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tplog.Detail = fmt.Sprintf(\"merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tbulletin, err := readBulletinFile(data.BulletinFile, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to read bulletin File. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tplog.Detail = fmt.Sprintf(\"%v, merkle root=%v,\", plog.Detail, bulletin.SigmaMKLRoot)\n\n\tLog.Debugf(\"step0: prepare for transaction...\")\n\tvar params = BobConnParam{data.AliceIP, data.AliceAddr, bulletin.Mode, data.SubMode, data.OT, data.UnitPrice, \"\", bulletin.SigmaMKLRoot}\n\tnode, conn, params, err := preBobConn(params, ETHKey, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to prepare net for transaction. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := node.Close(); err != nil {\n\t\t\tfmt.Errorf(\"failed to close client node: %v\", err)\n\t\t}\n\t\tif err := conn.Close(); err != nil {\n\t\t\tLog.Errorf(\"failed to close connection on client side: %v\", err)\n\t\t}\n\t}()\n\tLog.Debugf(\"[%v]step0: success to establish connecting session with Alice. Alice IP=%v, Alice address=%v\", params.SessionID, params.AliceIPAddr, params.AliceAddr)\n\tplog.Detail = fmt.Sprintf(\"%v, sessionID=%v,\", plog.Detail, params.SessionID)\n\tplog.SessionId = params.SessionID\n\n\tvar tx BobTransaction\n\ttx.SessionID = params.SessionID\n\ttx.Status = TRANSACTION_STATUS_START\n\ttx.Bulletin = bulletin\n\ttx.AliceIP = params.AliceIPAddr\n\ttx.AliceAddr = params.AliceAddr\n\ttx.Mode = params.Mode\n\ttx.SubMode = params.SubMode\n\ttx.OT = params.OT\n\ttx.UnitPrice = params.UnitPrice\n\ttx.BobAddr = fmt.Sprintf(\"%v\", ETHKey.Address.Hex())\n\n\tLog.Debugf(\"[%v]step0: success to prepare for transaction...\", params.SessionID)\n\ttx.Status = TRANSACTION_STATUS_START\n\terr = insertBobTxToDB(tx)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to save transaction to db for Bob. err=%v\", err)\n\t\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_TRANSACTION_FAILED, \"failed to save transaction to db for Bob.\"))\n\t\treturn\n\t}\n\n\tvar response string\n\tif tx.Mode == TRANSACTION_MODE_PLAIN_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForPOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForPC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForPAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t}\n\t} else if tx.Mode == TRANSACTION_MODE_TABLE_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForTAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\tcase TRANSACTION_SUB_MODE_VRF:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.PhantomKeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\t}\n\t}\n\tvar resp Response\n\terr = json.Unmarshal([]byte(response), &resp)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to parse response. response=%v, err=%v\", response, err)\n\t\tfmt.Fprintf(w, RESPONSE_FAILED_TO_RESPONSE)\n\t\treturn\n\t}\n\tif resp.Code == \"0\" {\n\t\tplog.Result = LOG_RESULT_SUCCESS\n\t}\n\tLog.Debugf(\"[%v]the transaction finish. merkel root=%v, response=%v\", params.SessionID, bulletin.SigmaMKLRoot, response)\n\tfmt.Fprintf(w, response)\n\treturn\n}", "func HandleInsert(w http.ResponseWriter, r *http.Request) {\n\n\t// Decode the request body into RequestDetails\n\trequestDetails := &queue.RequestDetails{}\n\tif err := json.NewDecoder(r.Body).Decode(requestDetails); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Set the queueDetails\n\tqueueDetails := &queue.Details{}\n\tqueueDetails.Name = requestDetails.Name\n\tqueueDetails.Type = requestDetails.Type\n\tqueueDetails.Depth = requestDetails.Depth\n\tqueueDetails.Rate = requestDetails.Rate\n\tqueueDetails.LastProcessed = requestDetails.LastProcessed\n\tqueueDetails.LastReported = time.Now()\n\n\t// Get the dbsession and insert into the database\n\tdbsession := context.Get(r, \"dbsession\")\n\tinsertFunction := insertQueueDetails(queueDetails)\n\tif err := executeOperation(dbsession, insertFunction); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error occured while saving queue details: %q\", err.Error()), 100)\n\t\treturn\n\t}\n\n\t// Send response\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write([]byte(`{\"result\":\"success\"}`))\n}", "func init() {\n//\tvar _r = net.GetRouter()\n//\tvar r = _r.PathPrefix(\"/v1\").Subrouter()\n\n var r = net.GetRouter()\n\t//route for test\n\t log.Print(\"cz init net_v1\")\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBGettokenizedcards, nil)).Methods(\"GET\") //logicbusiness.go\n r.Handle(\"/v3/processpayment\", netHandle(v4handleDBProcesspayment, nil)).Methods(\"GET\") //logicbusiness.go \n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBGeneratetokenized, nil)).Methods(\"GET\") //logicbusiness.go\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBPostGettokenizedcards, nil)).Methods(\"POST\") //logicbusiness.go\n\tr.Handle(\"/v3/processpayment\", netHandle(v4handleDBPostProcesspayment, nil)).Methods(\"POST\") //logicbusiness.go \t \n\n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBPostGeneratetokenized, nil)).Methods(\"POST\") //logicbusiness.go\n\n\t \n}", "func (client *SyncGroupsClient) listByDatabaseHandleResponse(resp *http.Response) (SyncGroupsClientListByDatabaseResponse, error) {\n\tresult := SyncGroupsClientListByDatabaseResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SyncGroupListResult); err != nil {\n\t\treturn SyncGroupsClientListByDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func handle(ctx p2p.HandlerContext) error {\n\tif ctx.IsRequest() {\n\t\tctx.Logger().Debug(\"node_service/handle : Information \",\n\t\t\tzap.String(\"address\", ctx.ID().Address),\n\t\t\tzap.String(\"public key\", ctx.ID().PubKey.String()[:PrintedLength]),\n\t\t\tzap.String(\"handler context\", \"is request\"),\n\t\t)\n\t\treturn nil\n\t}\n\n\tobj, err := ctx.DecodeMessage()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tmsg, ok := obj.(*messageOverP2P)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tif len(msg.contents) == 0 {\n\t\treturn nil\n\t}\n\n\tatomic.AddUint32(&receivedMessageOverP2P, 1)\n\n\tctx.Logger().Debug(\"node_service/handle : Information \",\n\t\tzap.String(\"address\", ctx.ID().Address),\n\t\tzap.String(\"Public Key\", ctx.ID().PubKey.String()[:PrintedLength]),\n\t\tzap.String(\"Content Size\", humanize.Bytes(uint64(len(msg.contents)))),\n\t)\n\n\treturn nil\n}" ]
[ "0.6588198", "0.64763606", "0.6018936", "0.579982", "0.5634544", "0.56159276", "0.5453365", "0.5441846", "0.5394664", "0.5379061", "0.5350443", "0.5323084", "0.52241564", "0.51942533", "0.5153262", "0.51236796", "0.51103026", "0.510832", "0.5101802", "0.50940883", "0.50757515", "0.50743794", "0.50730085", "0.50672275", "0.50599414", "0.5059785", "0.50439006", "0.5042792", "0.50422555", "0.5035528", "0.50354475", "0.5021185", "0.5012591", "0.5009101", "0.5006265", "0.4993121", "0.4988861", "0.49663258", "0.49643287", "0.49434638", "0.49321795", "0.48997244", "0.48822144", "0.48787966", "0.48690048", "0.4863614", "0.48627737", "0.4859432", "0.48538172", "0.48518294", "0.48486638", "0.4840243", "0.48350894", "0.48343927", "0.4833942", "0.48332387", "0.48322114", "0.48278877", "0.48138335", "0.48108646", "0.48085925", "0.48084092", "0.4802465", "0.47949696", "0.4793092", "0.47921848", "0.47901803", "0.4785984", "0.47836643", "0.47703895", "0.47689825", "0.47678202", "0.47643828", "0.4762044", "0.47594893", "0.47584218", "0.47533274", "0.47493726", "0.47365826", "0.47352317", "0.4733509", "0.47311547", "0.4727176", "0.47243413", "0.47177288", "0.4714031", "0.47129944", "0.47103044", "0.4703017", "0.46983036", "0.46942705", "0.46895406", "0.4685509", "0.46811038", "0.4676473", "0.46761292", "0.4675188", "0.46737906", "0.46734056", "0.46690273" ]
0.78089374
0
/////////////////////////////v4 /////////////////////////////v4 v4handleDBProcesspayment receive and handle the request from client, access DB
/////////////////////////////v4 /////////////////////////////v4 v4handleDBProcesspayment получает и обрабатывает запрос от клиента, обращается к БД
func v4handleDBPostProcesspayment(w http.ResponseWriter, r *http.Request) { defer func() { db.Connection.Close(nil) }() var errorGeneral string var errorGeneralNbr string var requestData modelito.RequestPayment errorGeneral="" requestData,errorGeneral =obtainPostParmsProcessPayment(r,errorGeneral) //logicrequest_post.go ////////////////////////////////////////////////validate parms /// START ////////////////////////////////////////////////validate parms /// START if errorGeneral=="" { errorGeneral,errorGeneralNbr= v4ProcessProcessPayment(w , requestData) //logicbusiness.go } if errorGeneral!=""{ //send error response if any //prepare an error JSON Response, if any log.Print("CZ STEP Get the ERROR response JSON ready") /// START fieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr) ////////// write the response (ERROR) w.Header().Set("Content-Type", "application/json") w.Write(fieldDataBytesJson) if(err!=nil){ } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func v4handleDBProcesspayment(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n\n var errorGeneral string\n var\terrorGeneralNbr string\n var requestData modelito.RequestPayment\n errorGeneral=\"\"\nrequestData,errorGeneral =obtainParmsProcessPayment(r,errorGeneral)\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= v4ProcessProcessPayment(w , requestData) //logicbusiness.go \n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleDBPostGettokenizedcards(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var errorGeneral string\n var errorGeneralNbr string\n \n \tvar requestData modelito.RequestTokenizedCards\n\n errorGeneral=\"\"\n requestData, errorGeneral=obtainPostParmsGettokenizedcards(r,errorGeneral) //logicrequest_post.go\n\n\t////////////////////////////////////////////////process business rules\n\t/// START\n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGettokenizedcards(w , requestData)\n\t}\n\t/// END\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleDBGeneratetokenized(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var requestData modelito.RequestTokenized\n var errorGeneral string\n var errorGeneralNbr string\n \n errorGeneral=\"\"\n requestData,errorGeneral =obtainParmsGeneratetokenized(r,errorGeneral)\n\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGeneratetokenized(w , requestData)\n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleDBPostGeneratetokenized(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var requestData modelito.RequestTokenized\n var errorGeneral string\n var errorGeneralNbr string\n \n errorGeneral=\"\"\n\n\n requestData,errorGeneral =obtainPostParmsGeneratetokenized(r,errorGeneral) //logicrequest_post.go\n\n\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGeneratetokenized(w , requestData)\n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func logicDBMysqlProcessDash01Grafica01(requestData modelito.RequestDash01Grafica01, errorGeneral string) ([]modelito.Card,string) {\n\t////////////////////////////////////////////////obtain parms in JSON\n //START \nvar resultCards []modelito.Card\nvar errCards error\n\n\t\t\t\t// START fetchFromDB\n\t\t\t\t var errdb error\n\t\t\t\t var db *sql.DB\n\t\t\t\t // Create connection string\n\t\t\t\t\tconnString := fmt.Sprintf(\"host=%s dbname=%s user=%s password=%s port=%d sslmode=disable\",\n\t\t\t\t\t\tConfig_DB_server,Config_DB_name, Config_DB_user, Config_DB_pass, Config_DB_port)\n\t\t\t\t\n\t\t\t\t if (connString !=\"si\"){\n\n }\n//\"mysql\", \"root:password1@tcp(127.0.0.1:3306)/test\"\n\n\t\t\t\t\t // Create connection pool\n//\t\t\t\t\tdb, errdb = sql.Open(\"postgres\", connString)\n//this use the values set up in the configuration.go\n log.Print(\"Usando para conectar : \" + Config_dbStringType)\n\t\t\t\t\tdb, errdb = sql.Open(Config_dbStringType, Config_connString)\n \n\n\t\t\t\t\tif errdb != nil {\n\t\t\t\t\t\tlog.Print(\"Error creating connection pool: \" + errdb.Error())\n\t\t\t\t\t\terrorGeneral=errdb.Error()\n\t\t\t\t\t}\n\t\t\t\t\t// Close the database connection pool after program executes\n\t\t\t\t\t defer db.Close()\n\t\t\t\t\tif errdb == nil {\n\t\t\t\t\t\tlog.Print(\"Connected!\\n\")\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\terrPing := db.Ping()\n\t\t\t\t\t\tif errPing != nil {\n\t\t\t\t\t\t log.Print(\"Error: Could not establish a connection with the database:\"+ errPing.Error())\n\t\t\t\t\t\t\t errorGeneral=errPing.Error()\n\t\t\t\t\t\t}else{\n\t\t\t\t\t log.Print(\"Ping ok!\\n\")\n//\t\t\t\t\t var misCards modelito.Card\n\t\t\t\t\t \n\t\t\t\t\t resultCards,errCards =modelito.GetCardsByCustomer(db,requestData.Dash0101reference)\n\t\t\t\t\t \t\t\t\t\t log.Print(\"regresa func getCardsByCustomer ok!\\n\")\n\t\t\t\t\t\t\tif errCards != nil {\n\t\t\t\t\t\t\t log.Print(\"Error: :\"+ errCards.Error())\n\t\t\t\t\t\t\t errorGeneral=errCards.Error()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvar cuantos int\n\t\t\t\t\t\t\tcuantos = 0\n\t\t\t\t \tfor _, d := range resultCards {\n\t\t\t\t \t\tlog.Print(\"el registor trae:\"+d.Token+\" \"+d.Bin)\n\t\t\t\t\t\t\t cuantos =1\n\t\t\t \t\t}\n\t\t\t\t\t\t\tif cuantos == 0 {\n\t\t\t\t\t\t\t log.Print(\"DB: records not found\")\n\t\t\t\t\t\t\t errorGeneral=\"Not cards found for the customer reference received\"\n\t\t\t\t\t\t\t}\t\t\n\n\t\t\t\t\t }\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t \n\t\t\t\t// END fetchFromDB\n \n //END\n \t return resultCards, errorGeneral\n }", "func (ctx *Context) PaymentDB(ros ...dbRequestReadOnly) *sql.DB {\n\tvar ro bool\n\tif len(ros) > 0 {\n\t\tfor _, r := range ros {\n\t\t\tif r {\n\t\t\t\tro = true\n\t\t\t}\n\t\t}\n\t}\n\tif !ro {\n\t\treturn ctx.paymentDBWrite\n\t}\n\tif ctx.paymentDBReadOnly == nil {\n\t\treturn ctx.paymentDBWrite\n\t}\n\treturn ctx.paymentDBReadOnly\n}", "func (s *Server) sqlHandler(w http.ResponseWriter, req *http.Request) {\n if(s.block) {\n time.Sleep(1000000* time.Second)\n }\n\n\tquery, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't read body: %s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\n\tif s.leader != s.listen {\n\n\t\tcs, errLeader := transport.Encode(s.leader)\n\t\t\n\t\tif errLeader != nil {\n\t\t\thttp.Error(w, \"Only the primary can service queries, but this is a secondary\", http.StatusBadRequest)\t\n\t\t\tlog.Printf(\"Leader ain't present?: %s\", errLeader)\n\t\t\treturn\n\t\t}\n\n\t\t//_, errLeaderHealthCheck := s.client.SafeGet(cs, \"/healthcheck\") \n\n //if errLeaderHealthCheck != nil {\n // http.Error(w, \"Primary is down\", http.StatusBadRequest)\t\n // return\n //}\n\n\t\tbody, errLResp := s.client.SafePost(cs, \"/sql\", bytes.NewBufferString(string(query)))\n\t\tif errLResp != nil {\n s.block = true\n http.Error(w, \"Can't forward request to primary, gotta block now\", http.StatusBadRequest)\t\n return \n\t//\t log.Printf(\"Didn't get reply from leader: %s\", errLResp)\n\t\t}\n\n formatted := fmt.Sprintf(\"%s\", body)\n resp := []byte(formatted)\n\n\t\tw.Write(resp)\n\t\treturn\n\n\t} else {\n\n\t\tlog.Debugf(\"Primary Received query: %#v\", string(query))\n\t\tresp, err := s.execute(query)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\tw.Write(resp)\n\t\treturn\n\t}\n}", "func (requestHandler *RequestHandler) handler(request events.APIGatewayProxyRequest) {\n\t//Initialize DB if requestHandler.Db = nil\n\tif errResponse := requestHandler.InitializeDB(); errResponse != (structs.ErrorResponse{}) {\n\t\tlog.Fatalf(\"Could not connect to DB when creating AOD/AODICE/QOD/QODICE\")\n\t}\n\tyear, month, day := time.Now().Date()\n\ttoday := fmt.Sprintf(\"%d-%d-%d\", year, month, day)\n\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\tgo func() { defer wg.Done(); requestHandler.insertEnglishQOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertIcelandicQOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertEnglishAOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertIcelandicAOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertTopicsQOD(today) }()\n\twg.Wait()\n}", "func cmdHandler(cmd string, db *sql.DB) (retVal int) {\n // cmd : the string of the user input\n // db : connection to the database\n\n cmd_tkn := strings.Split(strings.Trim(cmd, \"\\n\"), \" \") // tokenize command for easy parsing\n\n // check the balance of an account\n if cmd_tkn[0] == \"balance\" { // balance acctId\n if len(cmd_tkn) == 2 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n dispBalance(acctId, db)\n retVal = 0\n } else {\n dispError(\"Incorrect parameters supplied for balance request.\")\n }\n\n // deposit an amount into an account\n } else if cmd_tkn[0] == \"deposit\" { // deposit acctId amt interestRate\n if len(cmd_tkn) == 4 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n amt, _ := strconv.ParseFloat(cmd_tkn[2], 64)\n intRate, _ := strconv.ParseFloat(cmd_tkn[3], 64)\n retVal = deposit(acctId, db, amt, time.Now(), intRate)\n } else {\n dispError(\"Incorrect parameters supplied for deposit request.\")\n }\n\n // withdraw an amount from an account\n } else if cmd_tkn[0] == \"withdraw\" { // withdraw acctId amt\n if len(cmd_tkn) == 3 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n amt, _ := strconv.ParseFloat(cmd_tkn[2], 64)\n err := withdraw(acctId, db, amt, time.Now())\n if err != nil {\n dispError(err.Error())\n }\n } else {\n dispError(\"Incorrect parameters supplied for withdraw request.\")\n }\n\n // display the information on a transaction\n } else if cmd_tkn[0] == \"xtn\" { // xtn xtnId\n if len(cmd_tkn) == 2 {\n xtnId, _ := strconv.Atoi(cmd_tkn[1])\n dispXtn(xtnId, db)\n } else {\n dispError(\"Incorrect parameters supplied for deposit request.\")\n }\n\n // end the program\n } else if cmd_tkn[0] == \"exit\" || cmd_tkn[0] == \"quit\" {\n retVal = 1\n\n // handle incorrect inputs\n } else {\n dispError(\"Invalid command. Try again.\")\n }\n\n return\n}", "func Handler(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// Log body and pass to the DAO\n\tfmt.Printf(\"Received body: %v\\n\", req)\n\n\trequest := new(vm.GeneralRequest)\n\tresponse := request.Validate(req.Body)\n\tif response.Code != 0 {\n\t\treturn events.APIGatewayProxyResponse{Body: response.Marshal(), StatusCode: 500}, nil\n\t}\n\n\trequest.Date = time.Now().Unix()\n\n\tvar mainTable = \"main\"\n\tif value, ok := os.LookupEnv(\"dynamodb_table_main\"); ok {\n\t\tmainTable = value\n\t}\n\n\t// insert data into the DB\n\tdal.Insert(mainTable, request)\n\n\t// Log and return result\n\tfmt.Println(\"Wrote item: \", request)\n\treturn events.APIGatewayProxyResponse{Body: response.Marshal(), StatusCode: 200}, nil\n}", "func DataRetrievalHandler(reader fcrserver.FCRServerRequestReader, writer fcrserver.FCRServerResponseWriter, request *fcrmessages.FCRReqMsg) error {\n\tlogging.Debug(\"Handle data retrieval\")\n\t// Get core structure\n\tc := core.GetSingleInstance()\n\tc.MsgSigningKeyLock.RLock()\n\tdefer c.MsgSigningKeyLock.RUnlock()\n\n\t// Message decoding\n\tnonce, senderID, offer, accountAddr, voucher, err := fcrmessages.DecodeDataRetrievalRequest(request)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in decoding payload: %v\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Verify signature\n\tif request.VerifyByID(senderID) != nil {\n\t\t// Verify by signing key\n\t\tgwInfo := c.PeerMgr.GetGWInfo(senderID)\n\t\tif gwInfo == nil {\n\t\t\t// Not found, try sync once\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil {\n\t\t\t\terr = fmt.Errorf(\"Error in obtaining information for gateway %v\", senderID)\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t\tif request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t// Try update\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil || request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t\terr = fmt.Errorf(\"Error in verifying request from gateway %v: %v\", senderID, err.Error())\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check payment\n\trefundVoucher := \"\"\n\treceived, lane, err := c.PaymentMgr.Receive(accountAddr, voucher)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in receiving voucher %v:\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tif lane != 1 {\n\t\terr = fmt.Errorf(\"Not correct lane received expect 1 got %v:\", lane)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\texpected := big.NewInt(0).Add(c.Settings.SearchPrice, offer.GetPrice())\n\tif received.Cmp(expected) < 0 {\n\t\t// Short payment\n\t\t// Refund money\n\t\tif received.Cmp(c.Settings.SearchPrice) <= 0 {\n\t\t\t// No refund\n\t\t} else {\n\t\t\tvar ierr error\n\t\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\t\tif ierr != nil {\n\t\t\t\t// This should never happen\n\t\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"Short payment received, expect %v got %v, refund voucher %v\", expected.String(), received.String(), refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Payment is fine, verify offer\n\tif offer.Verify(c.OfferSigningPubKey) != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer signature, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer merkle proof\n\tif offer.VerifyMerkleProof() != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer merkle proof, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer expiry\n\tif offer.HasExpired() {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Offer has expired, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Offer is verified. Respond\n\t// First get the tag\n\ttag := c.OfferMgr.GetTagByCID(offer.GetSubCID())\n\t// Second read the data\n\tdata, err := ioutil.ReadFile(filepath.Join(c.Settings.RetrievalDir, tag))\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in finding the content, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Third encoding response\n\tresponse, err := fcrmessages.EncodeDataRetrievalResponse(nonce, tag, data)\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in encoding the response, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tc.OfferMgr.IncrementCIDAccessCount(offer.GetSubCID())\n\n\treturn writer.Write(response, c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n}", "func (_BaseContent *BaseContentTransactor) ProcessRequestPayment(opts *bind.TransactOpts, request_ID *big.Int, payee common.Address, label string, amount *big.Int) (*types.Transaction, error) {\n\treturn _BaseContent.contract.Transact(opts, \"processRequestPayment\", request_ID, payee, label, amount)\n}", "func ProcessStripePayment(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"NOT IMPLEMENTED\"})\n}", "func (s *Server) handleDashboardPaymentView() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\n\t//steps on the page\n\tsteps := struct {\n\t\tStepDel string\n\t\tStepMarkPaid string\n\t}{\n\t\tStepDel: \"stepDel\",\n\t\tStepMarkPaid: \"stepMarkPaid\",\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"payment-view.html\")\n\t\t})\n\t\tctx, provider, data, errs, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamActiveNav] = provider.GetURLPayments()\n\t\tdata[TplParamSteps] = steps\n\n\t\t//load the booking\n\t\tnow := data[TplParamCurrentTime].(time.Time)\n\t\tvar paymentUI *paymentUI\n\t\tbookIDStr := r.FormValue(URLParams.BookID)\n\t\tif bookIDStr != \"\" {\n\t\t\tctx, book, ok := s.loadTemplateBook(w, r.WithContext(ctx), tpl, data, errs, bookIDStr, false, false)\n\t\t\tif !ok {\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata[TplParamFormAction] = book.GetURLPaymentView()\n\n\t\t\t//load the service\n\t\t\tctx, _, ok = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, book.Service.ID, now)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//probe for a payment\n\t\t\tctx, payment, err := LoadPaymentByProviderIDAndSecondaryIDAndType(ctx, s.getDB(), provider.ID, book.ID, PaymentTypeBooking)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"load payment\", \"error\", err, \"id\", book.ID)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif payment == nil {\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpaymentUI = s.createPaymentUI(payment)\n\t\t} else {\n\t\t\t//load the payment directly\n\t\t\tidStr := r.FormValue(URLParams.PaymentID)\n\t\t\tif idStr == \"\" {\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tid := uuid.FromStringOrNil(idStr)\n\t\t\tif id == uuid.Nil {\n\t\t\t\tlogger.Errorw(\"invalid uuid\", \"id\", idStr)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx, payment, err := LoadPaymentByID(ctx, s.getDB(), &id)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"load payment\", \"error\", err, \"id\", id)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpaymentUI = s.createPaymentUI(payment)\n\t\t\tdata[TplParamFormAction] = paymentUI.GetURLView()\n\n\t\t\t//probe for a booking\n\t\t\tctx, book, ok := s.loadTemplateBook(w, r.WithContext(ctx), tpl, data, errs, payment.SecondaryID.String(), false, false)\n\t\t\tif ok {\n\t\t\t\tctx, _, _ = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, book.Service.ID, now)\n\t\t\t} else if paymentUI.ServiceID != \"\" {\n\t\t\t\tsvcID := uuid.FromStringOrNil(paymentUI.ServiceID)\n\t\t\t\tif svcID == uuid.Nil {\n\t\t\t\t\tlogger.Errorw(\"invalid uuid\", \"id\", paymentUI.ServiceID)\n\t\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx, _, _ = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, &svcID, now)\n\t\t\t}\n\t\t}\n\t\tdata[TplParamPayment] = paymentUI\n\n\t\t//set-up the confirmation\n\t\tdata[TplParamConfirmMsg] = GetMsgText(MsgPaymentMarkPaid)\n\t\tdata[TplParamConfirmSubmitName] = URLParams.Step\n\t\tdata[TplParamConfirmSubmitValue] = steps.StepMarkPaid\n\n\t\t//check the method\n\t\tif r.Method == http.MethodGet {\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//process the step\n\t\tstep := r.FormValue(URLParams.Step)\n\t\tswitch step {\n\t\tcase steps.StepDel:\n\t\t\tctx, err := DeletePayment(ctx, s.getDB(), paymentUI.ID)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"delete payment\", \"error\", err, \"id\", paymentUI.ID)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase steps.StepMarkPaid:\n\t\t\tctx, err := UpdatePaymentDirectCapture(ctx, s.getDB(), paymentUI.ID, &now)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"update payment captured\", \"error\", err, \"id\", paymentUI.ID)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tlogger.Errorw(\"invalid step\", \"id\", paymentUI.ID, \"step\", step)\n\t\t\ts.SetCookieErr(w, Err)\n\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\ts.SetCookieMsg(w, MsgUpdateSuccess)\n\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t}\n}", "func paymentRequired(rw http.ResponseWriter, r *http.Request) {\n\n}", "func handleRequests(dbgorm *gorm.DB) {\n\n\t//\n\t// lets instantiate some simple things here\n\t//\n\text := echo.New() // This is the externally supported login API. It only exposes SignIn and Sign out\n\tinternal := echo.New() // This is the externally supported login API. It only exposes SignIn and Sign out\n\n\tdb := DAO{DB: dbgorm}\n\n\text.Use(middleware.Recover())\n\text.Use(middleware.Logger())\n\n\tinternal.Use(middleware.Recover())\n\tinternal.Use(middleware.Logger())\n\n\t// This is the only path that can be taken for the external\n\t// There is sign in.\n\t// TODO: Signout\n\text.POST(\"/signin\", signin(db)) // This validates the user, generates a jwt token, and shoves it in a cookie\n\t// This is the only path that can be taken for the external\n\t// There is sign in.\n\t// TODO: Signout\n\text.POST(\"/signout\", signout()) // Lets invalidate the cookie\n\n\t//\n\t// Restricted group\n\t// This is an internal call made by all other microservices\n\t//\n\tv := internal.Group(\"/validate\")\n\t// Configure middleware with the custom claims type\n\tconfig := middleware.JWTConfig{\n\t\tClaims: &m.Claims{},\n\t\tSigningKey: []byte(\"my_secret_key\"),\n\t\tTokenLookup: \"cookie:jwt\",\n\t}\n\tv.Use(validatetoken(db)) // Lets validate the Token to make sure its valid and user is still valid\n\tv.Use(middleware.JWTWithConfig(config)) // If we are good, lets unpack it\n\tv.GET(\"\", GeneratePayload) // lets place the payload\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(2)\n\n\t// Lets fire up the internal first\n\tgo func() {\n\t\tif Properties.InternalMS.IsHTTPS {\n\t\t\tinternal.Logger.Fatal(internal.StartTLS(fmt.Sprintf(\":%d\", Properties.InternalMS.Port), \"./keys/server.crt\",\"./keys/server.key\"))\n\t\t} else {\n\t\t\tinternal.Logger.Fatal(internal.Start(fmt.Sprintf(\":%d\", Properties.InternalMS.Port)))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\t// Lets fire up the external now\n\tgo func() {\n\t\tif Properties.ExternalMS.IsHTTPS {\n\t\t\text.Logger.Fatal(ext.StartTLS(fmt.Sprintf(\":%d\", Properties.ExternalMS.Port), \"./keys/server.crt\",\"./keys/server.key\"))\n\t\t} else {\n\t\t\text.Logger.Fatal(ext.Start(fmt.Sprintf(\":%d\", Properties.ExternalMS.Port)))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n}", "func Order(w http.ResponseWriter, r *http.Request, session *gocql.Session) {\n //Número da Order. Geralmente esse número representa o ID da Order em um sistema externo através da integração com parceiros.\n number := r.FormValue(\"number\")\n //Referência da Order. Usada para facilitar o acesso ou localização da mesma.\n reference := r.FormValue(\"reference\")\n //Status da Order. DRAFT | ENTERED | CANCELED | PAID | APPROVED | REJECTED | RE-ENTERED | CLOSED\n status := r.FormValue(\"status\")\n // Um texto livre usado pelo Merchant para comunicação.\n notes := r.FormValue(\"notes\")\n fmt.Printf(\"Chegou uma requisicoes de order: number %s, reference %s, status %s, notes %s \\n\", number, reference, status, notes)\n\n uuid := gocql.TimeUUID()\n statusInt := translateStatus(status)\n if statusInt == 99 {\n http.Error(w, \"Parametro status invalido\", http.StatusPreconditionFailed)\n return\n }\n\n // Gravar no banco e retornar o UUID gerado\n if err := session.Query(\"INSERT INTO neurorder (order_id, number, reference, status, notes) VALUES (?,?,?,?,?)\", uuid, number, reference, statusInt, notes).Exec(); err != nil {\n fmt.Println(err)\n http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n } else {\n // Retornar um JSON com o UUID (id da Order)\n w.WriteHeader(http.StatusCreated)\n orderResponse := OrderResponse { Uuid: uuid.String() }\n json.NewEncoder(w).Encode(orderResponse)\n }\n}", "func processTxHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/processTx/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif r.Method != \"POST\" { // expecting POST method\n\t\thttp.Error(w, \"Invalid request method.\", 405)\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar txIn TxInput\n\n\terr := decoder.Decode(&txIn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer r.Body.Close()\n\n\t// fmt.Printf(\"\\nTX input:\\n%+v\\n\", txIn)\n\n\ttxResultStr := processTx(&txIn)\n\n\tfmt.Fprintf(w, \"%s\", txResultStr)\n}", "func BobPurchaseDataAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tLog.Infof(\"start purchase data...\")\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_BOB_TX\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\trequestData := r.FormValue(\"request_data\")\n\tvar data RequestData\n\terr := json.Unmarshal([]byte(requestData), &data)\n\tif err != nil {\n\t\tLog.Warnf(\"invalid parameter. data=%v, err=%v\", requestData, err)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"success to parse request data. data=%v\", requestData)\n\n\tif data.MerkleRoot == \"\" || data.AliceIP == \"\" || data.AliceAddr == \"\" || data.BulletinFile == \"\" || data.PubPath == \"\" {\n\t\tLog.Warnf(\"invalid parameter. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"read parameters. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tplog.Detail = fmt.Sprintf(\"merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tbulletin, err := readBulletinFile(data.BulletinFile, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to read bulletin File. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tplog.Detail = fmt.Sprintf(\"%v, merkle root=%v,\", plog.Detail, bulletin.SigmaMKLRoot)\n\n\tLog.Debugf(\"step0: prepare for transaction...\")\n\tvar params = BobConnParam{data.AliceIP, data.AliceAddr, bulletin.Mode, data.SubMode, data.OT, data.UnitPrice, \"\", bulletin.SigmaMKLRoot}\n\tnode, conn, params, err := preBobConn(params, ETHKey, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to prepare net for transaction. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := node.Close(); err != nil {\n\t\t\tfmt.Errorf(\"failed to close client node: %v\", err)\n\t\t}\n\t\tif err := conn.Close(); err != nil {\n\t\t\tLog.Errorf(\"failed to close connection on client side: %v\", err)\n\t\t}\n\t}()\n\tLog.Debugf(\"[%v]step0: success to establish connecting session with Alice. Alice IP=%v, Alice address=%v\", params.SessionID, params.AliceIPAddr, params.AliceAddr)\n\tplog.Detail = fmt.Sprintf(\"%v, sessionID=%v,\", plog.Detail, params.SessionID)\n\tplog.SessionId = params.SessionID\n\n\tvar tx BobTransaction\n\ttx.SessionID = params.SessionID\n\ttx.Status = TRANSACTION_STATUS_START\n\ttx.Bulletin = bulletin\n\ttx.AliceIP = params.AliceIPAddr\n\ttx.AliceAddr = params.AliceAddr\n\ttx.Mode = params.Mode\n\ttx.SubMode = params.SubMode\n\ttx.OT = params.OT\n\ttx.UnitPrice = params.UnitPrice\n\ttx.BobAddr = fmt.Sprintf(\"%v\", ETHKey.Address.Hex())\n\n\tLog.Debugf(\"[%v]step0: success to prepare for transaction...\", params.SessionID)\n\ttx.Status = TRANSACTION_STATUS_START\n\terr = insertBobTxToDB(tx)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to save transaction to db for Bob. err=%v\", err)\n\t\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_TRANSACTION_FAILED, \"failed to save transaction to db for Bob.\"))\n\t\treturn\n\t}\n\n\tvar response string\n\tif tx.Mode == TRANSACTION_MODE_PLAIN_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForPOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForPC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForPAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t}\n\t} else if tx.Mode == TRANSACTION_MODE_TABLE_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForTAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\tcase TRANSACTION_SUB_MODE_VRF:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.PhantomKeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\t}\n\t}\n\tvar resp Response\n\terr = json.Unmarshal([]byte(response), &resp)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to parse response. response=%v, err=%v\", response, err)\n\t\tfmt.Fprintf(w, RESPONSE_FAILED_TO_RESPONSE)\n\t\treturn\n\t}\n\tif resp.Code == \"0\" {\n\t\tplog.Result = LOG_RESULT_SUCCESS\n\t}\n\tLog.Debugf(\"[%v]the transaction finish. merkel root=%v, response=%v\", params.SessionID, bulletin.SigmaMKLRoot, response)\n\tfmt.Fprintf(w, response)\n\treturn\n}", "func (g *gateway) ProcessRequest(ctx context.Context, rawRequest []byte) (rawResponse []byte, httpStatusCode int) {\n\t// decode\n\tmsg, err := g.codec.DecodeRequest(rawRequest)\n\tif err != nil {\n\t\treturn newError(g.codec, \"\", api.UserMessageParseError, err.Error())\n\t}\n\tif err = msg.Validate(); err != nil {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.UserMessageParseError, err.Error())\n\t}\n\t// find correct handler\n\thandler, ok := g.handlers[msg.Body.DonId]\n\tif !ok {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.UnsupportedDONIdError, \"unsupported DON ID\")\n\t}\n\t// send to the handler\n\tresponseCh := make(chan handlers.UserCallbackPayload, 1)\n\terr = handler.HandleUserMessage(ctx, msg, responseCh)\n\tif err != nil {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.InternalHandlerError, err.Error())\n\t}\n\t// await response\n\tvar response handlers.UserCallbackPayload\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn newError(g.codec, msg.Body.MessageId, api.RequestTimeoutError, \"handler timeout\")\n\tcase response = <-responseCh:\n\t\tbreak\n\t}\n\tif response.ErrCode != api.NoError {\n\t\treturn newError(g.codec, msg.Body.MessageId, response.ErrCode, response.ErrMsg)\n\t}\n\t// encode\n\trawResponse, err = g.codec.EncodeResponse(response.Msg)\n\tif err != nil {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.NodeReponseEncodingError, \"\")\n\t}\n\treturn rawResponse, api.ToHttpErrorCode(api.NoError)\n}", "func handleRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte) {\n\tif respMsgBytes := responseCache.Get(msgID, getNetAddress(clientAddr)); respMsgBytes != nil {\n\t\tfmt.Println(\"Handle repeated request - 😡\", respMsgBytes, \"sending to \", clientAddr.Port)\n\n\t\t_, err := conn.WriteToUDP(respMsgBytes, clientAddr)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"handleRequest WriteToUDP\", err)\n\t\t}\n\t} else {\n\t\tincomingCache.Add(msgID, clientAddr)\n\n\t\trespPay := pb.KVResponse{}\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\tfmt.Println(\"+PUT request come in from\", clientAddr.Port)\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\n\t\t\t\tfmt.Println(\"who's sending responsee 🤡 \", self.Addr.String(), \" to \", clientAddr.Port)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second) {\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase GET:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tvar version int32\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[0].Get(reqPay.Key)\n\t\t\t\trespPay.Version = &version\n\t\t\t\t// TODO: check failure, then send request to other two nodes.\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Get(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Remove(reqPay.Key)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second){\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error (can't revert primary lol)\n\t\t\t\t\tfmt.Println(\"????? can't remove fully??\")\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Remove(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\tshutdown <- true\n\t\tcase WIPEOUT:\n\t\t\tif reqPay.ReplicaNum != nil {\n\t\t\t\tdataStorage.Replicas[*reqPay.ReplicaNum].RemoveAll()\n\t\t\t} else {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].RemoveAll()\n\t\t\t\tdataStorage.Replicas[1].RemoveAll()\n\t\t\t\tdataStorage.Replicas[2].RemoveAll()\n\t\t\t}\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = &pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := GetMembershipCount()\n\t\t\trespPay.MembershipCount = &members\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase NOTIFY_FAUILURE:\n\t\t\tfailedNode := GetNodeByIpPort(*reqPay.NodeIpPort)\n\t\t\tif failedNode != nil {\n\t\t\t\tfmt.Println(self.Addr.String(), \" STARTT CONTIUE GOSSSSSSIP 👻💩💩💩💩💩🤢🤢🤢🤢\", *reqPay.NodeIpPort, \"failed\")\n\t\t\t\tRemoveNode(failedNode)\n\t\t\t\tstartGossipFailure(failedNode)\n\t\t\t}\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase ADD_REPLICA:\n\t\t\tkv := dataStorage.decompressReplica(reqPay.Value)\n\t\t\tdataStorage.addReplica(kv, int(*reqPay.ReplicaNum))\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase SEND_REPLICA:\n\t\t\trespPay.Value = dataStorage.compressReplica(int(*reqPay.ReplicaNum))\n\t\t\trespPay.ReceiveData = true\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase RECOVER_PREV_NODE_KEYSPACE:\n\t\t\t// TODO: error handling on and internal failure\n\t\t\tRecoverDataStorage()\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase TEST_GOSSIP:\n\t\t\tfmt.Println(self.Addr.String(), \" TESTING GOSSIP 😡\", *reqPay.NodeIpPort, \"failed\")\n\t\t\tRemoveNode(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\t\tstartGossipFailure(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\tcase TEST_RECOVER_REPLICA:\n\t\t\treqPay := pb.KVRequest{Command: SHUTDOWN}\n\t\t\tsendRequestToNodeUUID(reqPay, self.prevNode())\n\t\t\tRemoveNode(self.prevNode())\n\n\t\t\tRecoverDataStorage()\n\t\tdefault:\n\t\t\t//respPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t\t//sendResponse(clientAddr, msgID, respPay)\n\t\t}\n\t}\n\tprintReplicas(self.Addr.String())\n}", "func(r *PaymentBDRepository)AddPayment(userIDHex string, payment models.Payment)(models.Payment,error){\n\n\tvar response models.Payment\n\tuser := models.User{}\n\n\tpayment.Status = core.StatusActive\n/*\n\tvar queryFind = bson.M{\n\t\t\"_id\": bson.ObjectId(userIDHex),\n\t\t\"payments\": bson.M{ \n\t\t\t\"$elemMatch\": bson.M{ \n\t\t\t\t\"card_number\": payment.CardNumber,\n\t\t\t\t},\n\t\t},\n\t}\n*/\n\tvar queryAdd = bson.M{ \n\t\t\t\"$addToSet\": bson.M{ \n\t\t\t\t\"payments\": payment,\n\t\t\t},\n\t}\n/*\n\tvar queryUpdate = bson.M{\n\t\t\"$set\":bson.M{\n\t\t\t\"payment\": bson.M{\n\t\t\t\t\"payment_type\":\"credit_card\",\n\t\t\t\t\"card_number\": \"xxxxxxxxxxxxxxxx\",\n\t\t\t\t\"cvv\":\"xxx\",\n\t\t\t\t\"end_date\": \"01/19\",\n\t\t\t\t\"user_name\": nil,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t*/\n\n\tsession ,err := mgo.Dial(core.DBUrl)\n\tif err!=nil{\n\t\tfmt.Printf(\"AddPayment error session %s \\n\",err)\n\t\treturn response,err\n\t}\n/*\n\t// Find user with payment in DB\n\terr = session.DB(core.DBName).C(user.GetDocumentName()).FindId(bson.ObjectId(userIDHex)).One(&user)\n\tif err != nil{\n\t\tfmt.Printf(\"AddPayment: Error Finding user %s \\n\",err.Error())\n\t\treturn response,err\n\t}\n\t*/\n\n\t// Appends payment in user model\n\terr = session.DB(core.DBName).C(user.GetDocumentName()).UpdateId(bson.ObjectIdHex(userIDHex),queryAdd)\n\tif err != nil{\n\t\tfmt.Printf(\"AddPayment: Error updating %s \\n\",err.Error())\n\t\treturn response,err\n\t}\n\n\tdefer session.Close()\n\n\treturn payment,nil\n}", "func (h CreatePaymentRequestHandler) Handle(params paymentrequestop.CreatePaymentRequestParams) middleware.Responder {\n\t// TODO: authorization to create payment request\n\n\treturn h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,\n\t\tfunc(appCtx appcontext.AppContext) (middleware.Responder, error) {\n\n\t\t\tpayload := params.Body\n\t\t\tif payload == nil {\n\t\t\t\terr := apperror.NewBadDataError(\"Invalid payment request: params Body is nil\")\n\t\t\t\terrPayload := payloads.ClientError(handlers.SQLErrMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\t\t\t\tappCtx.Logger().Error(err.Error(), zap.Any(\"payload\", errPayload))\n\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestBadRequest().WithPayload(errPayload), err\n\t\t\t}\n\n\t\t\tappCtx.Logger().Info(\"primeapi.CreatePaymentRequestHandler info\", zap.String(\"pointOfContact\", params.Body.PointOfContact))\n\n\t\t\tmoveTaskOrderIDString := payload.MoveTaskOrderID.String()\n\t\t\tmtoID, err := uuid.FromString(moveTaskOrderIDString)\n\t\t\tif err != nil {\n\t\t\t\tappCtx.Logger().Error(\"Invalid payment request: params MoveTaskOrderID cannot be converted to a UUID\",\n\t\t\t\t\tzap.String(\"MoveTaskOrderID\", moveTaskOrderIDString), zap.Error(err))\n\t\t\t\t// create a custom verrs for returning a 422\n\t\t\t\tverrs :=\n\t\t\t\t\t&validate.Errors{Errors: map[string][]string{\n\t\t\t\t\t\t\"move_id\": {\"id cannot be converted to UUID\"},\n\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\terrPayload := payloads.ValidationError(err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), verrs)\n\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(errPayload), err\n\t\t\t}\n\n\t\t\tisFinal := false\n\t\t\tif payload.IsFinal != nil {\n\t\t\t\tisFinal = *payload.IsFinal\n\t\t\t}\n\n\t\t\tpaymentRequest := models.PaymentRequest{\n\t\t\t\tIsFinal: isFinal,\n\t\t\t\tMoveTaskOrderID: mtoID,\n\t\t\t}\n\n\t\t\t// Build up the paymentRequest.PaymentServiceItems using the incoming payload to offload Swagger data coming\n\t\t\t// in from the API. These paymentRequest.PaymentServiceItems will be used as a temp holder to process the incoming API data\n\t\t\tvar verrs *validate.Errors\n\t\t\tpaymentRequest.PaymentServiceItems, verrs, err = h.buildPaymentServiceItems(appCtx, payload)\n\n\t\t\tif err != nil || verrs.HasAny() {\n\n\t\t\t\tappCtx.Logger().Error(\"could not build service items\", zap.Error(err))\n\t\t\t\t// TODO: do not bail out before creating the payment request, we need the failed record\n\t\t\t\t// we should create the failed record and store it as failed with a rejection\n\t\t\t\terrPayload := payloads.ValidationError(err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), verrs)\n\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(errPayload), err\n\t\t\t}\n\n\t\t\tcreatedPaymentRequest, err := h.PaymentRequestCreator.CreatePaymentRequestCheck(appCtx, &paymentRequest)\n\t\t\tif err != nil {\n\t\t\t\tappCtx.Logger().Error(\"Error creating payment request\", zap.Error(err))\n\t\t\t\tswitch e := err.(type) {\n\t\t\t\tcase apperror.InvalidCreateInputError:\n\t\t\t\t\tverrs := e.ValidationErrors\n\t\t\t\t\tdetail := err.Error()\n\t\t\t\t\tpayload := payloads.ValidationError(detail, h.GetTraceIDFromRequest(params.HTTPRequest), verrs)\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(payload), err\n\n\t\t\t\tcase apperror.NotFoundError:\n\t\t\t\t\tpayload := payloads.ClientError(handlers.NotFoundMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestNotFound().WithPayload(payload), err\n\t\t\t\tcase apperror.ConflictError:\n\t\t\t\t\tpayload := payloads.ClientError(handlers.ConflictErrMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestConflict().WithPayload(payload), err\n\t\t\t\tcase apperror.InvalidInputError:\n\t\t\t\t\tpayload := payloads.ValidationError(err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), &validate.Errors{})\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(payload), err\n\t\t\t\tcase apperror.QueryError:\n\t\t\t\t\tif e.Unwrap() != nil {\n\t\t\t\t\t\t// If you can unwrap, log the internal error (usually a pq error) for better debugging\n\t\t\t\t\t\tappCtx.Logger().Error(\"primeapi.CreatePaymentRequestHandler query error\", zap.Error(e.Unwrap()))\n\t\t\t\t\t}\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestInternalServerError().WithPayload(\n\t\t\t\t\t\tpayloads.InternalServerError(nil, h.GetTraceIDFromRequest(params.HTTPRequest))), err\n\n\t\t\t\tcase *apperror.BadDataError:\n\t\t\t\t\tpayload := payloads.ClientError(handlers.BadRequestErrMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestBadRequest().WithPayload(payload), err\n\t\t\t\tdefault:\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestInternalServerError().WithPayload(\n\t\t\t\t\t\tpayloads.InternalServerError(nil, h.GetTraceIDFromRequest(params.HTTPRequest))), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturnPayload := payloads.PaymentRequest(createdPaymentRequest)\n\t\t\tappCtx.Logger().Info(\"Successful payment request creation for mto ID\", zap.String(\"moveID\", moveTaskOrderIDString))\n\t\t\treturn paymentrequestop.NewCreatePaymentRequestCreated().WithPayload(returnPayload), nil\n\t\t})\n}", "func getPayments(c *gin.Context) {\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"getPayments\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tpayments, err := paymentsDB.GetPayments()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem retrieving payments\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, payments)\n\n}", "func ProcessPaymentRequested(ctx fsm.Context, environment ClientDealEnvironment, deal rm.ClientDealState) error {\n\t// If the unseal payment hasn't been made, we need to send funds\n\tif deal.UnsealPrice.GreaterThan(deal.UnsealFundsPaid) {\n\t\tlog.Debugf(\"client: payment needed: unseal price %d > unseal paid %d\",\n\t\t\tdeal.UnsealPrice, deal.UnsealFundsPaid)\n\t\treturn ctx.Trigger(rm.ClientEventSendFunds)\n\t}\n\n\t// If all bytes received have been paid for, we don't need to send funds\n\tif deal.BytesPaidFor >= deal.TotalReceived {\n\t\tlog.Debugf(\"client: no payment needed: bytes paid for %d >= bytes received %d\",\n\t\t\tdeal.BytesPaidFor, deal.TotalReceived)\n\t\treturn nil\n\t}\n\n\t// Not all bytes received have been paid for\n\n\t// If all blocks have been received we need to send a final payment\n\tif deal.AllBlocksReceived {\n\t\tlog.Debugf(\"client: payment needed: all blocks received, bytes paid for %d < bytes received %d\",\n\t\t\tdeal.BytesPaidFor, deal.TotalReceived)\n\t\treturn ctx.Trigger(rm.ClientEventSendFunds)\n\t}\n\n\t// Payments are made in intervals, as bytes are received from the provider.\n\t// If the number of bytes received is at or above the size of the current\n\t// interval, we need to send a payment.\n\tif deal.TotalReceived >= deal.CurrentInterval {\n\t\tlog.Debugf(\"client: payment needed: bytes received %d >= interval %d, bytes paid for %d < bytes received %d\",\n\t\t\tdeal.TotalReceived, deal.CurrentInterval, deal.BytesPaidFor, deal.TotalReceived)\n\t\treturn ctx.Trigger(rm.ClientEventSendFunds)\n\t}\n\n\tlog.Debugf(\"client: no payment needed: received %d < interval %d (paid for %d)\",\n\t\tdeal.TotalReceived, deal.CurrentInterval, deal.BytesPaidFor)\n\treturn nil\n}", "func AuthenticateClient(db *sql.DB, \n\t\treq *http.Request) (code int, dealerkey string, \n\t\tdealerid int, bsvkeyid int, err error) {\n\t//06.03.2013 naj - initialize some variables\n\t//08.06.2015 ghh - added ipaddress\n\tvar accountnumber, sentdealerkey, bsvkey, ipadd string\n\tcode = http.StatusOK\n\n\t//05.29.2013 naj - first we grab the AccountNumber and DealerKey\n\tif req.Method == \"GET\" {\n\t\t//first we need to grab the query string from the url so\n\t\t//that we can retrieve our variables\n\t\ttemp := req.URL.Query()\n\t\taccountnumber = temp.Get(\"accountnumber\")\n\t\tsentdealerkey = temp.Get(\"dealerkey\")\n\t\tbsvkey = temp.Get(\"bsvkey\")\n\t} else {\n\t\taccountnumber = req.FormValue(\"accountnumber\")\n\t\tsentdealerkey = req.FormValue(\"dealerkey\")\n\t\tbsvkey = req.FormValue(\"bsvkey\")\n\t}\n\n\n\t//if we don't get back a BSV key then we need to bail as\n\t//its a requirement. \n\tif bsvkey == \"\" {\n\t\terr = errors.New(\"Missing BSV Key In Package\")\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//if we didn't get an account number for the customer then we need to\n\t//also bail\n\tif accountnumber == \"\" {\n\t\terr = errors.New(\"Missing account number\")\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.03.2013 naj - validate the BSVKey to make sure the the BSV has been certified for MerX\n\terr = db.QueryRow(`select BSVKeyID from AuthorizedBSVKeys \n\t\t\t\t\t\t\twhere BSVKey = '?'`, bsvkey).Scan(&bsvkeyid)\n\n\t//default to having a valid bsvkey\n\tvalidbsvkey := 1\n\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\t//08.06.2015 ghh - before we send back an invalid BSV key we're going to instead\n\t\t\t//flag us to look again after validating the dealer. If the dealer ends up getting\n\t\t\t//validated then we're going to go ahead and insert this BSVKey into our accepted\n\t\t\t//list for this vendor.\n\t\t\tvalidbsvkey = 0\n\n\t\t\t//err = errors.New(\"Invalid BSV Key\")\n\t\t\t//code = http.StatusUnauthorized\n\t\t\t//return\n\t\tcase err != nil:\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t\t}\n\n\t//05.29.2013 naj - check to see if the supplied credentials are correct.\n\t//06.24.2014 naj - new format of request allows for the dealer to submit a request without a dealerkey on the first request to merX.\n\terr = db.QueryRow(`select DealerID, ifnull(DealerKey, '') as DealerKey,\n\t\t\t\t\t\t\tIPAddress\n\t\t\t\t\t\t\tfrom DealerCredentials where AccountNumber = ? \n\t\t\t\t\t\t\tand Active = 1 `, \n\t\t\t\t\t\t\taccountnumber).Scan(&dealerid, &dealerkey, &ipadd )\n\n\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\terr = errors.New(\"Account not found\")\n\t\t\tcode = http.StatusUnauthorized\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t}\n\n\t//05.06.2015 ghh - now we check to see if we have a valid key for the dealer\n\t//already. If they don't match then we get out. Keep in mind they could send\n\t//a blank key on the second attempt after we've generated a key and we need\n\t//to not allow that.\n\tif sentdealerkey != dealerkey {\n\t\terr = errors.New(\"Access Key Is Not Valid\" )\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.03.2013 naj - parse the RemoteAddr and update the client credentials\n\taddress := strings.Split(req.RemoteAddr, \":\")\n\n\t//08.06.2015 ghh - added check to make sure they are coming from the\n\t//linked ipadd if it exists\n\tif ipadd != \"\" && ipadd != address[0] {\n\t\terr = errors.New(\"Invalid IPAddress\" )\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.24.2014 naj - If we got this far then we have a dealerid, now we need to see if \n\t//they dealerkey is empty, if so create a new key and update the dealer record.\n\tif dealerkey == \"\" {\n\t\tdealerkey = uuid.NewV1().String()\n\n\t\t_, err = db.Exec(`update DealerCredentials set DealerKey = ?,\n\t\t\t\t\t\t\t\tLastIPAddress = inet_aton(?),\n\t\t\t\t\t\t\t\tAccessedDateTime = now()\n\t\t\t\t\t\t\t\twhere DealerID = ?`, dealerkey, address[0], dealerid)\n\n\t\tif err != nil {\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t\t}\n\n\t\t//08.06.2015 ghh - if this is the first time the dealer has attempted an order\n\t\t//and we're also missing the bsvkey then we're going to go ahead and insert into\n\t\t//the bsvkey table. The thought is that to hack this you'd have to find a dealer\n\t\t//that themselves has not ever placed an order and then piggy back in to get a valid\n\t\t//key. \n\t\tvar result sql.Result\n\t\tif validbsvkey == 0 {\n\t\t\t//here we need to insert the key into the table so future correspondence will pass\n\t\t\t//without conflict.\n\t\t\tresult, err = db.Exec(`insert into AuthorizedBSVKeys values ( null,\n\t\t\t\t\t\t\t\t\t?, 'Unknown' )`, bsvkey)\n\n\t\t\tif err != nil {\n\t\t\t\treturn \n\t\t\t}\n\n\t\t\t//now grab the bsvkeyid we just generated so we can return it\n\t\t\ttempbsv, _ := result.LastInsertId()\n\t\t\tbsvkeyid = int( tempbsv )\n\t\t}\n\n\t} else {\n\t\t//08.06.2015 ghh - if we did not find a valid bsv key above and flipped this\n\t\t//flag then here we need to raise an error. We ONLY allow this to happen on the\n\t\t//very first communcation with the dealer where we're also pulling a new key for \n\t\t//them\n\t\tif validbsvkey == 0 {\n\t\t\terr = errors.New(\"Invalid BSV Key\")\n\t\t\tcode = http.StatusUnauthorized\n\t\t\treturn\n\t\t}\n\t}\n\n\t_, err = db.Exec(`update DealerCredentials set LastIPAddress = inet_aton(?), \n\t\t\t\t\t\tAccessedDateTime = now() \n\t\t\t\t\t\twhere DealerID = ?`, address[0], dealerid)\n\n\tif err != nil {\n\t\tcode = http.StatusInternalServerError\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Server) handleDashboardPayments() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"payments.html\")\n\t\t})\n\t\tctx, provider, data, _, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//setup the breadcrumbs\n\t\tbreadcrumbs := []breadcrumb{\n\t\t\t{\"Invoices\", \"\"},\n\t\t}\n\t\tdata[TplParamBreadcrumbs] = breadcrumbs\n\t\tdata[TplParamActiveNav] = provider.GetURLPayments()\n\t\tdata[TplParamFormAction] = provider.GetURLPayments()\n\n\t\t//read the form\n\t\tfilterStr := r.FormValue(URLParams.Filter)\n\n\t\t//prepare the data\n\t\tdata[TplParamFilter] = filterStr\n\n\t\t//validate the filter\n\t\tvar err error\n\t\tfilter := PaymentFilterAll\n\t\tif filterStr != \"\" {\n\t\t\tfilter, err = ParsePaymentFilter(filterStr)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"parse filter\", \"error\", err, \"filter\", filterStr)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t}\n\t\t}\n\n\t\t//load the payments\n\t\tctx, payments, err := ListPaymentsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, filter)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"load payments\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamPayments] = s.createPaymentUIs(payments)\n\n\t\t//load the count\n\t\tctx, countUnPaid, err := CountPaymentsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, PaymentFilterUnPaid)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"count payments unpaid\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamCountUnPaid] = countUnPaid\n\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t}\n}", "func (h *Host) ProcessPayment(stream siamux.Stream, bh types.BlockHeight) (modules.PaymentDetails, error) {\n\t// read the PaymentRequest\n\tvar pr modules.PaymentRequest\n\tif err := modules.RPCRead(stream, &pr); err != nil {\n\t\treturn nil, errors.AddContext(err, \"Could not read payment request\")\n\t}\n\n\t// process payment depending on the payment method\n\tif pr.Type == modules.PayByEphemeralAccount {\n\t\treturn h.staticPayByEphemeralAccount(stream, bh)\n\t}\n\tif pr.Type == modules.PayByContract {\n\t\treturn h.managedPayByContract(stream, bh)\n\t}\n\n\treturn nil, errors.Compose(fmt.Errorf(\"Could not handle payment method %v\", pr.Type), modules.ErrUnknownPaymentMethod)\n}", "func (s *Server) handleDashboardPayment() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"payment.html\")\n\t\t})\n\t\tctx, provider, data, errs, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamActiveNav] = provider.GetURLBookings()\n\n\t\t//load the booking\n\t\tidStr := r.FormValue(URLParams.BookID)\n\t\tctx, book, ok := s.loadTemplateBook(w, r.WithContext(ctx), tpl, data, errs, idStr, true, false)\n\t\tif !ok {\n\t\t\ts.SetCookieErr(w, Err)\n\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamFormAction] = book.GetURLPayment()\n\n\t\t//check if a payment is supported, otherwise view the order\n\t\tif !book.SupportsPayment() {\n\t\t\thttp.Redirect(w, r.WithContext(ctx), book.GetURLView(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\n\t\t//check if already paid, in which case just view the payment\n\t\tif book.IsPaid() {\n\t\t\thttp.Redirect(w, r.WithContext(ctx), book.GetURLPaymentView(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\n\t\t//load the service\n\t\tnow := data[TplParamCurrentTime].(time.Time)\n\t\tctx, _, ok = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, book.Service.ID, now)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//check the method\n\t\tif r.Method == http.MethodGet {\n\t\t\tdata[TplParamDesc] = \"\"\n\t\t\tdata[TplParamEmail] = book.Client.Email\n\t\t\tdata[TplParamName] = book.Client.Name\n\t\t\tdata[TplParamPhone] = book.Client.Phone\n\t\t\tdata[TplParamPrice] = book.ComputeServicePrice()\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//read the form\n\t\tdesc := r.FormValue(URLParams.Desc)\n\t\temail := r.FormValue(URLParams.Email)\n\t\tname := r.FormValue(URLParams.Name)\n\t\tphone := r.FormValue(URLParams.Phone)\n\t\tpriceStr := r.FormValue(URLParams.Price)\n\n\t\t//prepare the data\n\t\tdata[TplParamDesc] = desc\n\t\tdata[TplParamEmail] = email\n\t\tdata[TplParamName] = name\n\t\tdata[TplParamPhone] = phone\n\t\tdata[TplParamPrice] = priceStr\n\n\t\t//validate the form\n\t\tform := &PaymentForm{\n\t\t\tEmailForm: EmailForm{\n\t\t\t\tEmail: strings.TrimSpace(email),\n\t\t\t},\n\t\t\tNameForm: NameForm{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tPhone: FormatPhone(phone),\n\t\t\tPrice: priceStr,\n\t\t\tDescription: desc,\n\t\t\tClientInitiated: false,\n\t\t\tDirectCapture: false,\n\t\t}\n\t\tok = s.validateForm(w, r.WithContext(ctx), tpl, data, errs, form, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//save the payment\n\t\tctx, payment, err := s.savePaymentBooking(ctx, provider, book, form, now)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"save payment\", \"error\", err)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//queue the email\n\t\tpaymentUI := s.createPaymentUI(payment)\n\t\tctx, err = s.queueEmailInvoice(ctx, provider.Name, paymentUI)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"queue email invoice\", \"error\", err)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//success\n\t\ts.SetCookieMsg(w, MsgPaymentSuccess)\n\t\thttp.Redirect(w, r.WithContext(ctx), book.GetURLView(), http.StatusSeeOther)\n\t}\n}", "func (client *GremlinResourcesClient) getGremlinDatabaseHandleResponse(resp *http.Response) (GremlinResourcesClientGetGremlinDatabaseResponse, error) {\n\tresult := GremlinResourcesClientGetGremlinDatabaseResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.GremlinDatabaseGetResults); err != nil {\n\t\treturn GremlinResourcesClientGetGremlinDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func HandleGetDatabaseConnectionState(adminMan *admin.Manager, modules *modules.Modules) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Create a context of execution\n\t\tctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)\n\t\tdefer cancel()\n\n\t\tvars := mux.Vars(r)\n\t\tdbAlias := vars[\"dbAlias\"]\n\n\t\tcrud := modules.DB()\n\t\tconnState := crud.GetConnectionState(ctx, dbAlias)\n\n\t\t_ = utils.SendResponse(w, http.StatusOK, model.Response{Result: connState})\n\t}\n}", "func (c *Client) ProcessRequest(req [][]byte) (err error) {\n\tvar (\n\t\tcommand Command\n\t)\n\tlog.Debugf(\"req:%v,%s\", strings.ToUpper(string(req[0])), req[1:])\n\tif len(req) == 0 {\n\t\tc.cmd = \"\"\n\t\tc.args = nil\n\t} else {\n\t\tc.cmd = strings.ToUpper(string(req[0]))\n\t\tc.args = req[1:]\n\t}\n\tif c.cmd != \"AUTH\" {\n\t\tif !c.isAuth {\n\t\t\tc.FlushResp(qkverror.ErrorNoAuth)\n\t\t\treturn nil\n\t\t}\n\t}\n\tlog.Debugf(\"command: %s argc:%d\", c.cmd, len(c.args))\n\tswitch c.cmd {\n\tcase \"AUTH\":\n\t\tif len(c.args) != 1 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tif c.auth == \"\" {\n\t\t\tc.FlushResp(qkverror.ErrorServerNoAuthNeed)\n\t\t} else if string(c.args[0]) != c.auth {\n\t\t\tc.isAuth = false\n\t\t\tc.FlushResp(qkverror.ErrorAuthFailed)\n\t\t} else {\n\t\t\tc.isAuth = true\n\t\t\tc.w.FlushString(\"OK\")\n\t\t}\n\t\treturn nil\n\tcase \"MULTI\":\n\t\tlog.Debugf(\"client transaction\")\n\t\tc.txn, err = c.tdb.NewTxn()\n\t\tif err != nil {\n\t\t\tc.resetTxn()\n\t\t\tc.w.FlushBulk(nil)\n\t\t\treturn nil\n\t\t}\n\t\tc.isTxn = true\n\t\tc.cmds = []Command{}\n\t\tc.respTxn = []interface{}{}\n\t\tc.w.FlushString(\"OK\")\n\t\terr = nil\n\t\treturn\n\tcase \"EXEC\":\n\t\tlog.Debugf(\"command length : %d txn:%v\", len(c.cmds), c.isTxn)\n\t\tif len(c.cmds) == 0 || !c.isTxn {\n\t\t\tc.w.FlushBulk(nil)\n\t\t\tc.resetTxn()\n\t\t\treturn nil\n\t\t}\n\t\tfor _, cmd := range c.cmds {\n\t\t\tlog.Debugf(\"execute command: %s\", cmd.cmd)\n\t\t\tc.cmd = cmd.cmd\n\t\t\tc.args = cmd.args\n\t\t\tif err = c.execute(); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tc.txn.Rollback()\n\t\t\tc.w.FlushBulk(nil)\n\t\t} else {\n\t\t\terr = c.txn.Commit(context.Background())\n\t\t\tif err == nil {\n\t\t\t\tc.w.FlushArray(c.respTxn)\n\t\t\t} else {\n\t\t\t\tc.w.FlushBulk(nil)\n\t\t\t}\n\t\t}\n\t\tc.resetTxn()\n\t\treturn nil\n\tcase \"DISCARD\":\n\t\t// discard transactional commands\n\t\tif c.isTxn {\n\t\t\terr = c.txn.Rollback()\n\t\t}\n\t\tc.w.FlushString(\"OK\")\n\t\tc.resetTxn()\n\t\treturn err\n\tcase \"PING\":\n\t\tif len(c.args) != 0 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tc.w.FlushString(\"PONG\")\n\t\treturn nil\n\t}\n\tif c.isTxn {\n\t\tcommand = Command{cmd: c.cmd, args: c.args}\n\t\tc.cmds = append(c.cmds, command)\n\t\tlog.Debugf(\"command:%s added to transaction queue, queue size:%d\", c.cmd, len(c.cmds))\n\t\tc.w.FlushString(\"QUEUED\")\n\t} else {\n\t\tc.execute()\n\t}\n\treturn\n\n}", "func (cli *srvClient) processRequest(ctx context.Context, msgID int, pkt *Packet) error {\n\tctx, cancel := context.WithTimeout(ctx, cli.srv.processingTimeout)\n\tdefer cancel()\n\n\t// TODO: use context for deadlines and cancellations\n\tvar res Response\n\tswitch pkt.Tag {\n\tdefault:\n\t\t// _ = pkt.Format(os.Stdout)\n\t\treturn UnsupportedRequestTagError(pkt.Tag)\n\tcase ApplicationUnbindRequest:\n\t\treturn io.EOF\n\tcase ApplicationBindRequest:\n\t\t// TODO: SASL\n\t\treq, err := parseBindRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Bind(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationSearchRequest:\n\t\treq, err := parseSearchRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif req.BaseDN == \"\" && req.Scope == ScopeBaseObject { // TODO check filter\n\t\t\tres, err = cli.rootDSE(req)\n\t\t} else {\n\t\t\tres, err = cli.srv.Backend.Search(ctx, cli.state, req)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationAddRequest:\n\t\treq, err := parseAddRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Add(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationDelRequest:\n\t\treq, err := parseDeleteRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Delete(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyRequest:\n\t\treq, err := parseModifyRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Modify(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyDNRequest:\n\t\treq, err := parseModifyDNRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.ModifyDN(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationExtendedRequest:\n\t\treq, err := parseExtendedRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch req.Name {\n\t\tdefault:\n\t\t\tres, err = cli.srv.Backend.ExtendedRequest(ctx, cli.state, req)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase OIDStartTLS:\n\t\t\tif cli.srv.tlsConfig == nil {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tBaseResponse: BaseResponse{\n\t\t\t\t\t\tCode: ResultUnavailable,\n\t\t\t\t\t\tMessage: \"TLS not configured\",\n\t\t\t\t\t},\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := cli.wr.Flush(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcli.cn = tls.Server(cli.cn, cli.srv.tlsConfig)\n\t\t\t\tcli.wr.Reset(cli.cn)\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase OIDPasswordModify:\n\t\t\tvar r *PasswordModifyRequest\n\t\t\tif len(req.Value) != 0 {\n\t\t\t\tp, _, err := ParsePacket(req.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tr, err = parsePasswordModifyRequest(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr = &PasswordModifyRequest{}\n\t\t\t}\n\t\t\tgen, err := cli.srv.Backend.PasswordModify(ctx, cli.state, r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp := NewPacket(ClassUniversal, false, TagSequence, nil)\n\t\t\tif gen != nil {\n\t\t\t\tp.AddItem(NewPacket(ClassContext, true, 0, gen))\n\t\t\t}\n\t\t\tb, err := p.Encode()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: b,\n\t\t\t}\n\t\tcase OIDWhoAmI:\n\t\t\tv, err := cli.srv.Backend.Whoami(ctx, cli.state)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: []byte(v),\n\t\t\t}\n\t\t}\n\t}\n\tif err := cli.cn.SetWriteDeadline(time.Now().Add(cli.srv.responseTimeout)); err != nil {\n\t\treturn fmt.Errorf(\"failed to set deadline for write: %w\", err)\n\t}\n\tdefer func() {\n\t\tif err := cli.cn.SetWriteDeadline(time.Time{}); err != nil {\n\t\t\tlog.Printf(\"failed to clear deadline for write: %s\", err)\n\t\t}\n\t}()\n\tif res != nil {\n\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn cli.wr.Flush()\n}", "func validatePayment(c *gin.Context) {\n\t// swagger:operation POST /api/v1/payments/fraud-detection/ validatePaymentRequest\n\t//\n\t// validatePayment: Validate the Payment for possible Fraud\n\t//\n\t// Could be info for any Fraud-Detection...\n\t//\n\t// ---\n\t// consumes:\n\t// - application/x-www-form-urlencoded\n\t// responses:\n\t// '200':\n\t// description: \"returns statistics about bought, only ordered, and returned products\"\n\t// schema:\n\t// type: array\n\t// items:\n\t// type: object\n\t// properties:\n\t// status:\n\t// description: the respose status\n\t// type: string\n\t// message:\n\t// description: the response message\n\t// type: string\n\t// resourceId:\n\t// description: the id of the new\n\t// type: string\n\t// \"required\": [\"status\", \"message\"]\n\n\t// Read an Integer param (from POST)\n\t// Atoi is used to convert string to int.\n\tintParam1, err := strconv.Atoi(c.PostForm(\"intParam1\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": http.StatusBadRequest, \"message\": \"StatusBadRequest\"})\n\t\treturn\n\t}\n\n\t// Read a String param (from POST)\n\tstrParam1 := c.PostForm(\"strParam1\")\n\tif len(strParam1) == 0 {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": http.StatusBadRequest, \"message\": \"StatusBadRequest\"})\n\t\treturn\n\t}\n\n\t// Insert to Database:\n\t// ?\n\tdummy := strings.Join([]string{strconv.Itoa(intParam1), strParam1}, \":\")\n\n\t// Return a dummy created response.\n\tc.JSON(http.StatusCreated, gin.H{\n\t\t\"status\": http.StatusCreated,\n\t\t\"message\": \"Fraud-Detection item created successfully!\",\n\t\t\"resourceId\": strings.Join([]string{\"Just Kidding, it is not not implemented yet.\", dummy}, \"\")})\n}", "func (client *SQLResourcesClient) getSQLDatabaseHandleResponse(resp *http.Response) (SQLResourcesClientGetSQLDatabaseResponse, error) {\n\tresult := SQLResourcesClientGetSQLDatabaseResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SQLDatabaseGetResults); err != nil {\n\t\treturn SQLResourcesClientGetSQLDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func Db_access_list(w http.ResponseWriter, r *http.Request) {\n\n///\n/// show d.b. access list inf. on web\n///\n\n process3.Db_access_list(w , r )\n\n}", "func (p *politeiawww) processVerifyUserPayment(u *user.User, vupt www.VerifyUserPayment) (*www.VerifyUserPaymentReply, error) {\n\tvar reply www.VerifyUserPaymentReply\n\tif p.HasUserPaid(u) {\n\t\treply.HasPaid = true\n\t\treturn &reply, nil\n\t}\n\n\tif paywallHasExpired(u.NewUserPaywallPollExpiry) {\n\t\terr := p.GenerateNewUserPaywall(u)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treply.PaywallAddress = u.NewUserPaywallAddress\n\t\treply.PaywallAmount = u.NewUserPaywallAmount\n\t\treply.PaywallTxNotBefore = u.NewUserPaywallTxNotBefore\n\t\treturn &reply, nil\n\t}\n\n\ttx, _, err := util.FetchTxWithBlockExplorers(u.NewUserPaywallAddress,\n\t\tu.NewUserPaywallAmount, u.NewUserPaywallTxNotBefore,\n\t\tp.cfg.MinConfirmationsRequired, p.dcrdataHostHTTP())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tx != \"\" {\n\t\treply.HasPaid = true\n\n\t\terr = p.updateUserAsPaid(u, tx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// TODO: Add the user to the in-memory pool.\n\t}\n\n\treturn &reply, nil\n}", "func (s *Server) handleTransaction(client string, req *pb.Command) (err error) {\n\t// Get the transfer from the original command, will panic if nil\n\ttransfer := req.GetTransfer()\n\tmsg := fmt.Sprintf(\"starting transaction of %0.2f from %s to %s\", transfer.Amount, transfer.Account, transfer.Beneficiary)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Handle Demo UI errors before the account lookup\n\tif transfer.OriginatingVasp != \"\" && transfer.OriginatingVasp != s.vasp.Name {\n\t\tlog.Info().Str(\"requested\", transfer.OriginatingVasp).Str(\"local\", s.vasp.Name).Msg(\"requested originator does not match local VASP\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrWrongVASP, \"message sent to the wrong originator VASP\"),\n\t\t)\n\t}\n\n\t// Lookup the account associated with the transfer originator\n\tvar account Account\n\tif err = LookupAccount(s.db, transfer.Account).First(&account).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"account\", transfer.Account).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"account not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch account: %s\", err)\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"account %04d accessed successfully\", account.ID), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Lookup the wallet of the beneficiary\n\tvar beneficiary Wallet\n\tif err = LookupBeneficiary(s.db, transfer.Beneficiary).First(&beneficiary).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"beneficiary\", transfer.Beneficiary).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"beneficiary wallet not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch beneficiary wallet: %s\", err)\n\t}\n\n\tif transfer.CheckBeneficiary {\n\t\tif transfer.BeneficiaryVasp != beneficiary.Provider.Name {\n\t\t\tlog.Info().\n\t\t\t\tStr(\"expected\", transfer.BeneficiaryVasp).\n\t\t\t\tStr(\"actual\", beneficiary.Provider.Name).\n\t\t\t\tMsg(\"check beneficiary failed\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrWrongVASP, \"beneficiary wallet does not match beneficiary vasp\"),\n\t\t\t)\n\t\t}\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"wallet %s provided by %s\", beneficiary.Address, beneficiary.Provider.Name), pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// TODO: lookup peer from cache rather than always doing a directory service lookup\n\tvar peer *peers.Peer\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"search for %s in directory service\", beneficiary.Provider.Name), pb.MessageCategory_TRISADS)\n\tif peer, err = s.peers.Search(beneficiary.Provider.Name); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not search peer from directory service\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not search peer from directory service\"),\n\t\t)\n\t}\n\tinfo := peer.Info()\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"identified TRISA remote peer %s at %s via directory service\", info.ID, info.Endpoint), pb.MessageCategory_TRISADS)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\tvar signKey *rsa.PublicKey\n\ts.updates.Broadcast(req.Id, \"exchanging peer signing keys\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\tif signKey, err = peer.ExchangeKeys(true); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not exchange keys with remote peer\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not exchange keyrs with remote peer\"),\n\t\t)\n\t}\n\n\t// Prepare the transaction\n\t// Save the pending transaction and increment the accounts pending field\n\txfer := Transaction{\n\t\tEnvelope: uuid.New().String(),\n\t\tAccount: account,\n\t\tAmount: decimal.NewFromFloat32(transfer.Amount),\n\t\tDebit: true,\n\t\tCompleted: false,\n\t}\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save transaction\"),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending++\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save originator account\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"ready to execute transaction\", pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Create an identity and transaction payload for TRISA exchange\n\ttransaction := &generic.Transaction{\n\t\tTxid: fmt.Sprintf(\"%d\", xfer.ID),\n\t\tOriginator: account.WalletAddress,\n\t\tBeneficiary: beneficiary.Address,\n\t\tAmount: float64(transfer.Amount),\n\t\tNetwork: \"TestNet\",\n\t\tTimestamp: xfer.Timestamp.Format(time.RFC3339),\n\t}\n\tidentity := &ivms101.IdentityPayload{\n\t\tOriginator: &ivms101.Originator{},\n\t\tOriginatingVasp: &ivms101.OriginatingVasp{},\n\t}\n\tif identity.OriginatingVasp.OriginatingVasp, err = s.vasp.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator vasp\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator vasp\"),\n\t\t)\n\t}\n\n\tidentity.Originator = &ivms101.Originator{\n\t\tOriginatorPersons: make([]*ivms101.Person, 0, 1),\n\t\tAccountNumbers: []string{account.WalletAddress},\n\t}\n\tvar originator *ivms101.Person\n\tif originator, err = account.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator identity\"),\n\t\t)\n\t}\n\tidentity.Originator.OriginatorPersons = append(identity.Originator.OriginatorPersons, originator)\n\n\tpayload := &protocol.Payload{}\n\tif payload.Transaction, err = anypb.New(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize transaction payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize transaction payload\"),\n\t\t)\n\t}\n\tif payload.Identity, err = anypb.New(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize identity payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize identity payload\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"transaction and identity payload constructed\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Secure the envelope with the remote beneficiary's signing keys\n\tvar envelope *protocol.SecureEnvelope\n\tif envelope, err = handler.New(xfer.Envelope, payload, nil).Seal(signKey); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not create or sign secure envelope\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not create or sign secure envelope\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"secure envelope %s sealed: encrypted with AES-GCM and RSA - sending ...\", envelope.Id), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Conduct the TRISA transaction, handle errors and send back to user\n\tif envelope, err = peer.Transfer(envelope); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not perform TRISA exchange\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"received %s information exchange reply from %s\", envelope.Id, peer.String()), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Open the response envelope with local private keys\n\tvar opened *handler.Envelope\n\tif opened, err = handler.Open(envelope, s.trisa.sign); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unseal TRISA response\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Verify the contents of the response\n\tpayload = opened.Payload\n\tif payload.Identity.TypeUrl != \"type.googleapis.com/ivms101.IdentityPayload\" {\n\t\tlog.Warn().Str(\"type\", payload.Identity.TypeUrl).Msg(\"unsupported identity type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported identity type\", payload.Identity.TypeUrl),\n\t\t)\n\t}\n\n\tif payload.Transaction.TypeUrl != \"type.googleapis.com/trisa.data.generic.v1beta1.Transaction\" {\n\t\tlog.Warn().Str(\"type\", payload.Transaction.TypeUrl).Msg(\"unsupported transaction type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported transaction type\", payload.Transaction.TypeUrl),\n\t\t)\n\t}\n\n\tidentity = &ivms101.IdentityPayload{}\n\ttransaction = &generic.Transaction{}\n\tif err = payload.Identity.UnmarshalTo(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\tif err = payload.Transaction.UnmarshalTo(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"successfully decrypted and parsed secure envelope\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Update the completed transaction and save to disk\n\txfer.Beneficiary = Identity{\n\t\tWalletAddress: transaction.Beneficiary,\n\t}\n\txfer.Completed = true\n\txfer.Timestamp, _ = time.Parse(time.RFC3339, transaction.Timestamp)\n\n\t// Serialize the identity information as JSON data\n\tvar data []byte\n\tif data, err = json.Marshal(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not marshal IVMS 101 identity\"),\n\t\t)\n\t}\n\txfer.Identity = string(data)\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending--\n\taccount.Completed++\n\taccount.Balance.Sub(xfer.Amount)\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\tmsg = fmt.Sprintf(\"transaction %04d complete: %s transfered from %s to %s\", xfer.ID, xfer.Amount.String(), xfer.Originator.WalletAddress, xfer.Beneficiary.WalletAddress)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"%04d new account balance: %s\", account.ID, account.Balance), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\trep := &pb.Message{\n\t\tType: pb.RPC_TRANSFER,\n\t\tId: req.Id,\n\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t\tCategory: pb.MessageCategory_LEDGER,\n\t\tReply: &pb.Message_Transfer{Transfer: &pb.TransferReply{\n\t\t\tTransaction: xfer.Proto(),\n\t\t}},\n\t}\n\n\treturn s.updates.Send(client, rep)\n}", "func handleKVRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest) () {\n\tlog.Println(\"start handling request\")\n\tlog.Println(msgID)\n\tlog.Println(\"sender IP:\", net.IPv4(msgID[0], msgID[1], msgID[2], msgID[3]).String(), \":\", binary.LittleEndian.Uint16(msgID[4:6]))\n\tlog.Println(\"command:\", reqPay.Command)\n\tif reqPay.Addr == nil {\n\n\t\treqPay.Addr = []byte(clientAddr.String())\n\t}\n\n\t// Try to find the response in the cache\n\tif respMsgBytes, ok := GetCachedResponse(msgID); ok {\n\t\t// Send the message back to the client\n\t\t_, _ = conn.WriteToUDP(respMsgBytes, clientAddr)\n\t} else {\n\t\t// Handle the command\n\t\trespPay := pb.KVResponse{}\n\n\t\t/*\n\t\t\tIf the command is PUT, GET or REMOVE, check whether the key exists in\n\t\t\tthis node first. Otherwise,\n\t\t*/\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\t// respPay.ErrCode = Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase GET:\n\t\t\t// var version int32\n\t\t\t// respPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t// respPay.Version = &version\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\tvar version int32\n\t\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t\trespPay.Version = version\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay,msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\t//log.Println(\"############################################################################\")\n\t\t\t//log.Println(\"########################### SHUT DOWN ! ####################################\")\n\t\t\t//log.Println(\"############################################################################\")\n\n\t\t\tshutdown <- true\n\t\t\treturn\n\t\tcase WIPEOUT:\n\t\t\trespPay.ErrCode = RemoveAll()\n\t\t\tnormalReplicate(WIPEOUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := int32(1) // Unused, return 1 for now\n\t\t\trespPay.MembershipCount = members\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_LIST:\n\t\t\tGetMemberShipList(clientAddr, msgID, respPay)\n\t\t\treturn\n\t\t//forward request\n\t\tcase PUT_FORWARD:\n\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase GET_FORWARD:\n\t\t\tvar version int32\n\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\trespPay.Version = version\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase REMOVE_FORWARD:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase PUT_REPLICATE_SON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 0)\n\t\t\treturn\n\t\tcase PUT_REPLICATE_GRANDSON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 1)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_SON:\n\t\t\tRemoveReplicate(reqPay.Key, 0)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_GRANDSON:\n\t\t\tRemoveReplicate(reqPay.Key, 1)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_SON:\n\t\t\tWipeoutReplicate(0)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_GRANDSON:\n\t\t\tWipeoutReplicate(1)\n\t\t\treturn\n\n\t\tcase GRANDSON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(FATHER_DIED, KVStore, addr)\n\t\t\treturn\n\t\tcase SON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(GRANDFATHER_DIED_1, KVStore, addr)\n\t\t\treturn\n\n\t\tcase HELLO:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\t\t\treceiveHello(addr, msgID)\n\t\t\treturn\n\t\tdefault:\n\t\t\trespPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t}\n\n\t\t// Send the response\n\t\tsendResponse(clientAddr, msgID, respPay)\n\t}\n}", "func addPayment(c *gin.Context) {\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"addPayment\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tvar p storage.Payments\n\terr = c.BindJSON(&p)\n\n\terr = paymentsDB.CreatePayment(&p)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Could not add a payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"success\", \"message\": \"Payment created\"})\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\thelper.SetupResponse(&w, r)\n\ti := invoice.Invoice{}\n\tif (*r).Method == \"OPTIONS\" {\n\t\treturn\n\t}\n\tif (*r).Method == \"GET\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tuserID := r.FormValue(\"userID\")\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tlessonID := r.FormValue(\"lessonID\")\n\t\tmode := r.FormValue(\"mode\")\n\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.Read(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"2\" {\n\t\t\tlogs := i.ReadItemLineItem(invoiceID, lessonID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"3\" {\n\t\t\tlogs := i.GetUnpaidInvoice(userID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"4\" {\n\t\t\tlogs := i.GetInvoiceLineItemByInvoiceID(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.GetAllInvoice()\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\t} else if (*r).Method == \"POST\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\t// Invoice\n\t\tuserID := r.FormValue(\"userID\")\n\t\tcreateDate := r.FormValue(\"createDate\")\n\t\ttotal := r.FormValue(\"total\")\n\t\tdetail := r.FormValue(\"detail\")\n\t\tstatus := r.FormValue(\"status\")\n\n\t\t// Line item\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tlessonID := r.FormValue(\"lessonID\")\n\t\tquantityDay := r.FormValue(\"quantityDay\")\n\t\tamountTotal := r.FormValue(\"amountTotal\")\n\n\t\tmode := r.FormValue(\"mode\")\n\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.AddItemToLineItem(invoiceID, lessonID, quantityDay, amountTotal)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.Create(userID, createDate, total, detail, status)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\n\t} else if (*r).Method == \"PUT\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\t// Invoice\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tuserID := r.FormValue(\"userID\")\n\t\tcreateDate := r.FormValue(\"createDate\")\n\t\ttotal := r.FormValue(\"total\")\n\t\tdetail := r.FormValue(\"detail\")\n\t\tstatus := r.FormValue(\"status\")\n\n\t\t// Line item\n\t\tlessonID := r.FormValue(\"lessonID\")\n\t\tquantityDay := r.FormValue(\"quantityDay\")\n\t\tamountTotal := r.FormValue(\"amountTotal\")\n\n\t\tmode := r.FormValue(\"mode\")\n\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.UpdateItemLineItem(invoiceID, lessonID, quantityDay, amountTotal)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"2\" {\n\t\t\tlogs := i.UpdateStatusInvoice(invoiceID, status)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.Update(invoiceID, userID, createDate, total, detail, status)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\n\t} else if (*r).Method == \"DELETE\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tlessonID := r.FormValue(\"lessonID\")\n\n\t\tmode := r.FormValue(\"mode\")\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.DeleteItemLineItem(invoiceID, lessonID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"2\" {\n\t\t\tlogs := i.CancelInvoice(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.Delete(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\n\t} else {\n\t\tfmt.Fprintf(w, \"Please use get medthod\")\n\t}\n}", "func getPaymentByID(c *gin.Context) {\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"getPaymentsByID\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tpayments, err := paymentsDB.GetPayment(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\"status\": \"error\", \"message\": \"Could not find a payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, payments)\n\n}", "func (c *BsnCommitTxHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {\n\t//txnID := requestContext.Response.TransactionID\n\t//GatewayLog.Logs( \"CommitTxHandler Handle TXID 发送交易\",txnID)\n\t//Register Tx event\n\n\t//reg, statusNotifier, err := clientContext.EventService.RegisterTxStatusEvent(string(txnID)) // TODO: Change func to use TransactionID instead of string\n\t//if err != nil {\n\t//\trequestContext.Error = errors.Wrap(err, \"error registering for TxStatus event\")\n\t//\treturn\n\t//}\n\t//defer clientContext.EventService.Unregister(reg)\n\n\tres, err := createAndSendBsnTransaction(clientContext.Transactor, requestContext.Response.Proposal, requestContext.Response.Responses)\n\n\t//GatewayLog.Logs( \"CommitTxHandler Handle 交易结束\")\n\tif err != nil {\n\t\trequestContext.Error = errors.Wrap(err, \"CreateAndSendTransaction failed\")\n\t\treturn\n\t}\n\t//requestContext.Response.TxValidationCode = 0\n\t//GatewayLog.Logs( \"requestContext.Response.Payload :\",string(requestContext.Response.Payload))\n\t//GatewayLog.Logs( \"requestContext.Response.BlockNumber :\",string(requestContext.Response.BlockNumber))\n\t//GatewayLog.Logs( \"requestContext.Response.ChaincodeStatus :\",string(requestContext.Response.ChaincodeStatus))\n\t//select {\n\t//case txStatus := <-statusNotifier:\n\t//\t//GatewayLog.Logs(\"statusNotifier 结果接收 \",&txStatus)\n\t//\trequestContext.Response.TxValidationCode = txStatus.TxValidationCode\n\t//\trequestContext.Response.BlockNumber=txStatus.BlockNumber\n\t//\tif txStatus.TxValidationCode != pb.TxValidationCode_VALID {\n\t//\t\trequestContext.Error = status.New(status.EventServerStatus, int32(txStatus.TxValidationCode),\n\t//\t\t\t\"received invalid transaction\", nil)\n\t//\t\treturn\n\t//\t}\n\t//case <-requestContext.Ctx.Done():\n\t//\trequestContext.Error = status.New(status.ClientStatus, status.Timeout.ToInt32(),\n\t//\t\t\"Execute didn't receive block event\", nil)\n\t//\treturn\n\t//}\n\n\t//Delegate to next step if any\n\tif res != nil {\n\t\trequestContext.Response.OrderDataLen = res.DataLen\n\t}\n\n\tif c.next != nil {\n\t\tc.next.Handle(requestContext, clientContext)\n\t}\n}", "func Process(inputFile string, outputFile string, db *Store) error {\n\tin, err := os.Open(inputFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout, err := os.Create(outputFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\tdefer out.Close()\n\n\tscanner := bufio.NewScanner(in)\n\twriter := bufio.NewWriter(out)\n\tfor scanner.Scan() {\n\t\t// Parse the request\n\t\treq, err := NewRequest(scanner.Text())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Check if it's already processed\n\t\tif db.IsDupTxn(req.ID, req.CustID) {\n\t\t\tlog.Println(\"Ignoring duplicate txn: \", req.ID)\n\t\t\tcontinue\n\t\t}\n\t\t// Fetch the account from DB\n\t\taccount := db.GetAccount(req.CustID)\n\t\t// Act on the request (if velocity limits agree)\n\t\taccepted := account.LoadFunds(req)\n\t\tresponse := NewResponse(req.ID, req.CustID, accepted)\n\t\tresBytes, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Record the response\n\t\tif _, err = writer.WriteString(string(resBytes) + \"\\n\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Record the transaction in DB\n\t\tdb.AddTxn(req.ID, req.CustID)\n\t}\n\t// Check if there were any errors while reading the input file\n\tif err := scanner.Err(); err != nil {\n\t\treturn err\n\t}\n\t// Flush any pending writes\n\twriter.Flush()\n\treturn nil\n}", "func (_obj *Apipayments) Payments_sendPaymentForm(params *TLpayments_sendPaymentForm, _opt ...map[string]string) (ret Payments_PaymentResult, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"payments_sendPaymentForm\", _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 = ret.ReadBlock(_is, 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 HandleInsert(w http.ResponseWriter, r *http.Request) {\n\n\t// Decode the request body into RequestDetails\n\trequestDetails := &queue.RequestDetails{}\n\tif err := json.NewDecoder(r.Body).Decode(requestDetails); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Set the queueDetails\n\tqueueDetails := &queue.Details{}\n\tqueueDetails.Name = requestDetails.Name\n\tqueueDetails.Type = requestDetails.Type\n\tqueueDetails.Depth = requestDetails.Depth\n\tqueueDetails.Rate = requestDetails.Rate\n\tqueueDetails.LastProcessed = requestDetails.LastProcessed\n\tqueueDetails.LastReported = time.Now()\n\n\t// Get the dbsession and insert into the database\n\tdbsession := context.Get(r, \"dbsession\")\n\tinsertFunction := insertQueueDetails(queueDetails)\n\tif err := executeOperation(dbsession, insertFunction); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error occured while saving queue details: %q\", err.Error()), 100)\n\t\treturn\n\t}\n\n\t// Send response\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write([]byte(`{\"result\":\"success\"}`))\n}", "func (e *BsnEndorsementHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {\n\t//GatewayLog.Logs( \"BSNEndorsementHandler Handle 开始交易提案\",)\n\tif len(requestContext.Opts.Targets) == 0 {\n\t\trequestContext.Error = status.New(status.ClientStatus, status.NoPeersFound.ToInt32(), \"targets were not provided\", nil)\n\t\treturn\n\t}\n\n\t// Endorse Tx\n\tvar TxnHeaderOpts []fab.TxnHeaderOpt\n\tif e.headerOptsProvider != nil {\n\t\tTxnHeaderOpts = e.headerOptsProvider()\n\t}\n\t//GatewayLog.Logs( \"createAndSendTransactionProposal 开始发送交易提案\",)\n\n\ttransactionProposalResponses, proposal, err := createAndSendBsnTransactionProposal(\n\t\tclientContext.Transactor,\n\t\t&requestContext.Request,\n\t\tpeer.PeersToTxnProcessors(requestContext.Opts.Targets),\n\t\tTxnHeaderOpts...,\n\t)\n\t//GatewayLog.Logs( \"Query createAndSendTransactionProposal END\",)\n\trequestContext.Response.Proposal = proposal\n\trequestContext.Response.TransactionID = proposal.TxnID // TODO: still needed?\n\n\tif err != nil {\n\t\trequestContext.Error = err\n\t\treturn\n\t}\n\n\trequestContext.Response.Responses = transactionProposalResponses\n\tif len(transactionProposalResponses) > 0 {\n\t\trequestContext.Response.Payload = transactionProposalResponses[0].ProposalResponse.GetResponse().Payload\n\t\trequestContext.Response.ChaincodeStatus = transactionProposalResponses[0].ChaincodeStatus\n\t}\n\t//GatewayLog.Logs( \"Query EndorsementHandler Handle END\",)\n\t//Delegate to next step if any\n\tif e.next != nil {\n\t\te.next.Handle(requestContext, clientContext)\n\t}\n}", "func (p *POSend) ProcessPackage(dealerid int, dealerkey string) ([]byte, error) {\n\tdb := p.db\n\t//10.04.2013 naj - start a transaction\n\ttransaction, err := db.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//06.02.2013 naj - make a slice to hold the purchase orders\n\tr := make([]AcceptedOrder, 0, len(p.PurchaseOrders))\n\n\t//06.05.2015 ghh -because the system has the ability to push more than one purchase\n\t//order through at the same time it will loop through our array and process each\n\t//one separately\n\tfor i := 0; i < len(p.PurchaseOrders); i++ {\n\t\t//06.02.2013 naj - stick the current PO into a new variable to keep the name short.\n\t\tc := p.PurchaseOrders[i]\n\n\n\t\t//06.02.2013 naj - put the current PONumber into the response\n\t\tr = r[0 : len(r)+1]\n\t\tr[i].DealerPO = c.DealerPONumber\n\n\t\t//06.10.2014 naj - check to see if the po is already in the system.\n\t\t//If it is and it's not processed yet, delete the the po and re-enter it.\n\t\t//If it is and it's processed return an error.\n\t\tvar result sql.Result\n\t\tvar temppoid int\n\t\tvar tempstatus int\n\n\t\t//06.02.2015 ghh - first we grab the Ponumber that is being sent to use and we're going to see\n\t\t//if it has already been processed by the vendor\n\t\terr = transaction.QueryRow(`select ifnull(POID, 0 ), ifnull( Status, 0 ) \n\t\t\t\t\t\t\t\t\t\t\tfrom PurchaseOrders \n\t\t\t\t\t\t\t\t\t\t\twhere DealerID = ? and DealerPONumber = ?`,\n\t\t\t\t\tdealerid, c.DealerPONumber).Scan(&temppoid, &tempstatus)\n\n\t\t//case err == sql.ErrNoRows:\n\t\t//if we have a PO already there and its not been processed yet by the vendor then we're going\n\t\t//to delete it as we're uploading it a second time.\n\t\tif temppoid > 0 { \n\t\t\tif tempstatus == 0 { //has it been processed by vendor yet?\n\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrders \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere DealerID=? \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tand DealerPONumber=? `, dealerid, c.DealerPONumber )\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t//now delete the items from the old $_POST[\n\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrderItems \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere POID=? `, temppoid )\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\n\t\t\t\t\t//08.06.2015 ghh - delete units from linked units table\n\t\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrderUnits \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere POID=? `, temppoid )\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//if we get here then we must have found an existing PO so lets log it and return\n\t\t\tif tempstatus > 0 {\n\t\t\t\terr = errors.New(\"Error: 16207 Purchase order already sent and pulled by vendor.\")\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif err != sql.ErrNoRows {\n\t\t\t\t//if there was an error then return it\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t//06.02.2013 naj - create the PO record in the database.\n\t\t\tresult, err = transaction.Exec(`insert into PurchaseOrders (\n\t\t\t\tDealerID, BSVKeyID, DealerPONumber, POReceivedDate, BillToFirstName, BillToLastName, BillToCompanyName, \n\t\t\t\tBillToAddress1, BillToAddress2, BillToCity, BillToState, BillToZip, \n\t\t\t\tBillToCountry, BillToPhone, BillToEmail, \n\t\t\t\tShipToFirstName, ShipToLastName, ShipToCompanyName, ShipToAddress1,\n\t\t\t\tShipToAddress2, ShipToCity, ShipToState, ShipToZip, ShipToCountry, \n\t\t\t\tShipToPhone, ShipToEmail, \n\t\t\t\tPaymentMethod, LastFour, ShipMethod) values \n\t\t\t\t(?, ?, curdate(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t?, ?, ?, ?, ?, ?, ? )`, \n\t\t\t\tdealerid, c.BSVKeyID, c.DealerPONumber,\n\t\t\t\tc.BillToFirstName, c.BillToLastName, c.BillToCompanyName, c.BillToAddress1, \n\t\t\t\tc.BillToAddress2, c.BillToCity, c.BillToState, c.BillToZip, c.BillToCountry, \n\t\t\t\tc.BillToPhone, c.BillToEmail,\n\t\t\t\tc.ShipToFirstName, c.ShipToLastName, c.ShipToCompanyName, c.ShipToAddress1, \n\t\t\t\tc.ShipToAddress2, c.ShipToCity, c.ShipToState, c.ShipToZip, c.ShipToCountry, \n\t\t\t\tc.ShipToPhone, c.ShipToEmail, c.PaymentMethod, c.LastFour, c.ShipMethod )\n\n\t\t\tif err != nil {\n\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t_ = transaction.Rollback()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//06.02.2013 naj - get the POID assigned to the PO\n\t\t\tpoid, err := result.LastInsertId()\n\n\t\t\t//06.02.2013 naj - format the POID and put the assigned POID into the response\n\t\t\ttemp := strconv.FormatInt(poid, 10)\n\n\t\t\tr[i].InternalID = temp\n\t\t\tr[i].DealerKey = dealerkey\n\n\t\t\tif err != nil {\n\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t_ = transaction.Rollback()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//06.05.2015 ghh - now loop through the items array and insert all the parts for\n\t\t\t//the order\n\t\t\tfor j := 0; j < len(c.Items); j++ {\n\t\t\t\t//06.02.2013 naj - attach the parts to the current PO.\n\t\t\t\t_, err := transaction.Exec(`insert into PurchaseOrderItems (POID, PartNumber, VendorID, \n\t\t\t\t\t\t\t\t\t\t\t\t\tQuantity) value (?, ?, ?, ?)`, \n\t\t\t\t\t\t\t\t\t\t\t\t\tpoid, c.Items[j].PartNumber, c.Items[j].VendorID, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Items[j].Qty)\n\t\t\t\tif err != nil {\n\t\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t\t_ = transaction.Rollback()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t\t//08.06.2015 ghh - ( now that we've written the line into the table we need to\n\t\t\t\t\t//query a few things in order to build a proper response to send back. Things\n\t\t\t\t\t//we want to know are how many will ship, any supersession or other known info\n\t\t\t\t\t//current cost...\n\n\t\t\t}\n\n\n\t\t\t//07.21.2015 ghh - now loop through the list of units and add them to the PO\n\t\t\tfor j := 0; j < len(c.Units); j++ {\n\t\t\t\t//06.02.2013 naj - attach the parts to the current PO.\n\t\t\t\t_, err := transaction.Exec(`insert into PurchaseOrderUnits (POID, ModelNumber, Year,\n\t\t\t\t\t\t\t\t\t\t\t\t\tVendorID, OrderCode, Colors, Details \n\t\t\t\t\t\t\t\t\t\t\t\t\tQuantity) value (?, ?, ?, ?, ?, ?, ?, ?)`, \n\t\t\t\t\t\t\t\t\t\t\t\t\tpoid, c.Units[j].ModelNumber, c.Units[j].Year, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].VendorID, c.Units[j].OrderCode,\n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].Colors, c.Units[j].Details,\n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].Qty)\n\t\t\t\tif err != nil {\n\t\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t\t_ = transaction.Rollback()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//06.05.2015 ghh - now we'll take the array and marshal it back into a json\n\t//array to be returned to client\n\tif len(r) > 0 {\n\t\t//06.02.2013 naj - JSON Encode the response data.\n\t\tresp, err := json.Marshal(r)\n\n\t\tif err != nil {\n\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t_ = transaction.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t//10.04.2013 naj - commit the transaction\n\t\terr = transaction.Commit()\n\t\tif err != nil {\n\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t_ = transaction.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn resp, nil\n\t} else {\n\t\t//10.04.2013 naj - rollback transaction\n\t\t_ = transaction.Rollback()\n\t\treturn nil, errors.New(\"No valid parts were in the purchase order\")\n\t\t}\n\n}", "func (r *analyticsDeferredResultHandle) executeHandle(req *gocbcore.HttpRequest, valuePtr interface{}) error {\n\tresp, err := r.provider.DoHttpRequest(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjsonDec := json.NewDecoder(resp.Body)\n\terr = jsonDec.Decode(valuePtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\tlogDebugf(\"Failed to close socket (%s)\", err)\n\t}\n\n\treturn nil\n}", "func HandleRequest(query []byte, conn *DatabaseConnection) {\n\tlog.Printf(\"Handling raw query: %s\", query)\n\tlog.Printf(\"Parsing request...\")\n\trequest, err := grammar.ParseRequest(query)\n\tlog.Printf(\"Parsed request\")\n\tvar response grammar.Response\n\n\tif err != nil {\n\t\tlog.Printf(\"Error in request parsing! %s\", err.Error())\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_INVALID_QUERY\n\t\tresponse.Data = err.Error()\n\t\tconn.Write(grammar.GetBufferFromResponse(response))\n\t}\n\n\tswitch request.Type {\n\tcase grammar.AUTH_REQUEST:\n\t\t// AUTH {username} {password}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_AUTH_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in AUTH request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\t// bucketname := tokens[2]\n\t\tlog.Printf(\"Client wants to authenticate.<username>:<password> %s:%s\", username, password)\n\n\t\tauthRequest := AuthRequest{Username: username, Password: password, Conn: conn}\n\t\tresponse = processAuthRequest(authRequest)\n\tcase grammar.SET_REQUEST:\n\t\t// SET {key} {value} [ttl] [nooverride]\n\t\trequest.Type = grammar.SET_RESPONSE\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_SET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in SET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tvalue := request.RequestData[1]\n\t\tlog.Printf(\"Setting %s:%s\", key, value)\n\t\tsetRequest := SetRequest{Key: key, Value: value, Conn: conn}\n\t\tresponse = processSetRequest(setRequest)\n\n\tcase grammar.GET_REQUEST:\n\t\t// GET {key}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_GET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in GET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tlog.Printf(\"Client wants to get key '%s'\", key)\n\t\tgetRequest := GetRequest{Key: key, Conn: conn}\n\t\tresponse = processGetRequest(getRequest)\n\n\tcase grammar.DELETE_REQUEST:\n\t\t// DELETE {key}\n\t\tlog.Println(\"Client wants to delete a bucket/key\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_DELETE_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in DELETE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\t// TODO implement\n\tcase grammar.CREATE_BUCKET_REQUEST:\n\t\tlog.Println(\"Client wants to create a bucket\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_BUCKET_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE bucket request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketName := request.RequestData[0]\n\t\tcreateBucketRequest := CreateBucketRequest{BucketName: bucketName, Conn: conn}\n\n\t\tresponse = processCreateBucketRequest(createBucketRequest)\n\tcase grammar.CREATE_USER_REQUEST:\n\t\tlog.Printf(\"Client wants to create a user\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_USER_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE user request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\tcreateUserRequest := CreateUserRequest{Username: username, Password: password, Conn: conn}\n\n\t\tresponse = processCreateUserRequest(createUserRequest)\n\tcase grammar.USE_REQUEST:\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_USE_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in USE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketname := request.RequestData[0]\n\t\tif bucketname == SALTS_BUCKET || bucketname == USERS_BUCKET {\n\t\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNAUTHORIZED\n\t\t\tbreak\n\t\t}\n\n\t\tuseRequest := UseRequest{BucketName: bucketname, Conn: conn}\n\t\tresponse = processUseRequest(useRequest)\n\tdefault:\n\t\tlog.Printf(illegalRequestTemplate, request.Type)\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNKNOWN_COMMAND\n\t}\n\tif response.Status != 0 {\n\t\tlog.Printf(\"Error in request. status: %d\", response.Status)\n\t}\n\tconn.Write(grammar.GetBufferFromResponse(response))\n\tlog.Printf(\"Wrote buffer: %s to client\", grammar.GetBufferFromResponse(response))\n\n}", "func HandleGetPreparedQuery(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t_ = json.NewEncoder(w).Encode(map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)\n\t\tdefer cancel()\n\t\t// get project id and dbType from url\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\t\tdbAlias := \"\"\n\t\tdbAliasQuery, exists := r.URL.Query()[\"dbAlias\"]\n\t\tif exists {\n\t\t\tdbAlias = dbAliasQuery[0]\n\t\t}\n\t\tidQuery, exists := r.URL.Query()[\"id\"]\n\t\tid := \"\"\n\t\tif exists {\n\t\t\tid = idQuery[0]\n\t\t}\n\t\tresult, err := syncMan.GetPreparedQuery(ctx, projectID, dbAlias, id)\n\t\tif err != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t_ = json.NewEncoder(w).Encode(map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_ = json.NewEncoder(w).Encode(model.Response{Result: result})\n\t}\n}", "func (q queryManager) processQueryWithSignature(txEncoded []byte, signature []byte, executeifallowed bool) (*structures.Transaction, error) {\n\ttx, err := structures.DeserializeTransaction(txEncoded)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tq.Logger.Trace.Printf(\"Complete SQL TX\")\n\terr = tx.CompleteTransaction(signature)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tq.Logger.Trace.Printf(\"Completed with ID: %x\", tx.GetID())\n\t// verify\n\t// TODO\n\n\tq.Logger.Trace.Printf(\"Adding TX to pool\")\n\t//return nil, errors.New(\"Temp err \")\n\t// add to pool\n\t// if fails , execute rollback ???\n\t// query wil be executed inside transactions manager before adding to a pool\n\terr = q.getTransactionsManager().ReceivedNewTransaction(tx, executeifallowed)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}", "func HandlerMessage(aResponseWriter http.ResponseWriter, aRequest *http.Request) {\n\taRequest.ParseForm()\n\n\tbody := aRequest.Form\n\tlog.Printf(\"aRequest.Form=%s\", body)\n\tbytesBody, err := ioutil.ReadAll(aRequest.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading body, err=%s\", err.Error())\n\t}\n\t//\tlog.Printf(\"bytesBody=%s\", string(bytesBody))\n\n\t//check Header Token\n\t//\theaderAuthentication := aRequest.Header.Get(STR_Authorization)\n\t//\tisValid, userId := DbIsTokenValid(headerAuthentication, nil)\n\t//\tlog.Printf(\"HandlerMessage, headerAuthentication=%s, isValid=%t, userId=%d\", headerAuthentication, isValid, userId)\n\t//\tif !isValid {\n\t//\t\tresult := new(objects.Result)\n\t//\t\tresult.ErrorMessage = STR_MSG_login\n\t//\t\tresult.ResultCode = http.StatusOK\n\t//\t\tServeResult(aResponseWriter, result, STR_template_result)\n\t//\t\treturn\n\t//\t}\n\n\treport := new(objects.Report)\n\tjson.Unmarshal(bytesBody, report)\n\tlog.Printf(\"HandlerMessage, report.ApiKey=%s, report.ClientId=%s, report.Message=%s, report.Sequence=%d, report.Time=%d\",\n\t\treport.ApiKey, report.ClientId, report.Message, report.Sequence, report.Time)\n\tvar isApiKeyValid = false\n\tif report.ApiKey != STR_EMPTY {\n\t\tisApiKeyValid, _ = IsApiKeyValid(report.ApiKey)\n\t}\n\tif !isApiKeyValid {\n\t\tresult := new(objects.Result)\n\t\tresult.ErrorMessage = STR_MSG_invalidapikey\n\t\tresult.ResultCode = http.StatusOK\n\t\tServeResult(aResponseWriter, result, STR_template_result)\n\t\treturn\n\t}\n\n\tDbAddReport(report.ApiKey, report.ClientId, report.Time, report.Sequence, report.Message, report.FilePath, nil)\n\n\tresult := new(objects.Result)\n\tresult.ErrorMessage = STR_EMPTY\n\tresult.ResultCode = http.StatusOK\n\tServeResult(aResponseWriter, result, STR_template_result)\n}", "func (cm *commonMiddlware) traceDB(ctx context.Context) trace.Span {\n\tif cm.ot == nil {\n\t\treturn nil\n\t}\n\tif span := trace.SpanFromContext(ctx); span != nil {\n\t\t_, sp := cm.ot.Start(ctx, \"Postgres Database Call\")\n\t\treturn sp\n\t}\n\t_, sp := cm.ot.Start(ctx, \"Asynchronous Postgres Database Call\")\n\treturn sp\n}", "func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// Initiialize a connection to Sentry to capture errors and traces\n\tsentry.Init(sentry.ClientOptions{\n\t\tDsn: os.Getenv(\"SENTRY_DSN\"),\n\t\tTransport: &sentry.HTTPSyncTransport{\n\t\t\tTimeout: time.Second * 3,\n\t\t},\n\t\tServerName: os.Getenv(\"FUNCTION_NAME\"),\n\t\tRelease: os.Getenv(\"VERSION\"),\n\t\tEnvironment: os.Getenv(\"STAGE\"),\n\t})\n\n\t// Create headers if they don't exist and add\n\t// the CORS required headers, otherwise the response\n\t// will not be accepted by browsers.\n\theaders := request.Headers\n\tif headers == nil {\n\t\theaders = make(map[string]string)\n\t}\n\theaders[\"Access-Control-Allow-Origin\"] = \"*\"\n\n\t// Update the order with an OrderID\n\tord, err := acmeserverless.UnmarshalOrder(request.Body)\n\tif err != nil {\n\t\treturn handleError(\"unmarshal\", headers, err)\n\t}\n\tord.OrderID = uuid.Must(uuid.NewV4()).String()\n\n\tdynamoStore := dynamodb.New()\n\tord, err = dynamoStore.AddOrder(ord)\n\tif err != nil {\n\t\treturn handleError(\"store\", headers, err)\n\t}\n\n\tprEvent := acmeserverless.PaymentRequestedEvent{\n\t\tMetadata: acmeserverless.Metadata{\n\t\t\tDomain: acmeserverless.OrderDomain,\n\t\t\tSource: \"AddOrder\",\n\t\t\tType: acmeserverless.PaymentRequestedEventName,\n\t\t\tStatus: acmeserverless.DefaultSuccessStatus,\n\t\t},\n\t\tData: acmeserverless.PaymentRequestDetails{\n\t\t\tOrderID: ord.OrderID,\n\t\t\tCard: ord.Card,\n\t\t\tTotal: ord.Total,\n\t\t},\n\t}\n\n\t// Send a breadcrumb to Sentry with the payment request\n\tsentry.AddBreadcrumb(&sentry.Breadcrumb{\n\t\tCategory: acmeserverless.PaymentRequestedEventName,\n\t\tTimestamp: time.Now(),\n\t\tLevel: sentry.LevelInfo,\n\t\tData: acmeserverless.ToSentryMap(prEvent.Data),\n\t})\n\n\tem := sqs.New()\n\terr = em.SendPaymentRequestedEvent(prEvent)\n\tif err != nil {\n\t\treturn handleError(\"request payment\", headers, err)\n\t}\n\n\tstatus := acmeserverless.OrderStatus{\n\t\tOrderID: ord.OrderID,\n\t\tUserID: ord.UserID,\n\t\tPayment: acmeserverless.CreditCardValidationDetails{\n\t\t\tMessage: \"pending payment\",\n\t\t\tSuccess: false,\n\t\t},\n\t}\n\n\t// Send a breadcrumb to Sentry with the shipment request\n\tsentry.AddBreadcrumb(&sentry.Breadcrumb{\n\t\tCategory: acmeserverless.PaymentRequestedEventName,\n\t\tTimestamp: time.Now(),\n\t\tLevel: sentry.LevelInfo,\n\t\tData: acmeserverless.ToSentryMap(status.Payment),\n\t})\n\n\tpayload, err := status.Marshal()\n\tif err != nil {\n\t\treturn handleError(\"response\", headers, err)\n\t}\n\n\tresponse := events.APIGatewayProxyResponse{\n\t\tStatusCode: http.StatusOK,\n\t\tBody: string(payload),\n\t\tHeaders: headers,\n\t}\n\n\treturn response, nil\n}", "func (kvs *keyValueServer) handleRequest(req *Request) {\n\tvar request []string\n\trequest = kvs.parseRequest(req.input)\n\tif request[0] == \"get\" {\n\t\tclient := kvs.clienter[req.cid]\n\t\tkvs.getFromDB(request, client)\n\t}\n\tif request[0] == \"put\" {\n\t\tkvs.putIntoDB(request)\n\t}\n}", "func handleGetData(request []byte, bc *Blockchain) {\n\tvar buff bytes.Buffer\n\tvar payload getdata\n\n\tbuff.Write(request[commandLength:])\n\tdec := gob.NewDecoder(&buff)\n\terr := dec.Decode(&payload)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif payload.Type == \"block\" {\n\t\tblock, err := bc.GetBlock([]byte(payload.ID))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tsendBlock(payload.AddrFrom, &block)\n\t}\n\n\tif payload.Type == \"tx\" {\n\t\ttxID := hex.EncodeToString(payload.ID)\n\t\ttx := mempool[txID]\n\n\t\tsendTx(payload.AddrFrom, &tx)\n\t\t// delete(mempool, txID)\n\t}\n}", "func (app *JSONStoreApplication) DeliverTx(tx types.RequestDeliverTx) types.ResponseDeliverTx {\n\t return types.ResponseDeliverTx{Code: code.CodeTypeOK}\n\n\t var temp interface{}\n\t err := json.Unmarshal(tx.Tx, &temp)\n\n\t if err != nil {\n\t\t return types.ResponseDeliverTx{Code: code.CodeTypeEncodingError,Log: fmt.Sprint(err)}\n\t }\n\n\t message := temp.(map[string]interface{})\n\n\t PublicKey := message[\"publicKey\"].(string)\n\n\t count := checkUserPublic(db,PublicKey)\n \n\t if count != 0 {\n //var temp2 interface{}\n\t\t//userInfo := message[\"userInfo\"].(map[string]interface{})\n\t\t// err2 := json.Unmarshal([]byte(message[\"userInfo\"].(string)), &temp2)\n // message2 := temp2.(map[string]interface{})\n\t\t//if err2 != nil {\n\t\t//\tpanic(err.Error)\n\t\t//}\n \n\t\tvar user User\n\t\tuser.ID = message[\"id\"].(int)\n\t\tuser.PublicKey = message[\"public_key\"].(string)\n\t\tuser.Role = message[\"role\"].(int)\n\n\t\tfmt.Printf(user.PublicKey)\n \n\t\t// log.PrintIn(\"id: \", user.ID, \"public_key: \", user.PublicKey, \"role: \", user.Role)\n\n\t\tstmt, err := db.Prepare(\"INSERT INTO user(id, public_key, role) VALUES(?,?,?)\")\n\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\t\t\n\t\tstmt.Exec(user.ID, user.PublicKey, user.Role)\n\n\t\t// log.PrintIn(\"insert result: \", res.LastInsertId())\n\n\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeOK}\n\t } else {\n\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData}\n\t }\n\t \n\t// var types interface{}\n\t// errType := json.Unmarshall(message[\"types\"].(string), &types)\n\t \n\t// if errType != nil {\n\t// \t panic(err.Error)\n\t// }\n\n\t// switch types[\"types\"] {\n\t// \tcase \"createUser\":\n\t// \t\tentity := types[\"entity\"].(map[string]interface{})\n\n\t// \t\tvar user User\n\t// \t\tuser.ID = entity[\"id\"].(int)\n\t// \t\tuser.PublicKey = entity[\"publicKey\"].(string)\n\t// \t\tuser.Role = entity[\"role\"].(int)\n\t// }\n}", "func Deposito(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"Application-json\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tdefer r.Body.Close()\n\tdeposit := models.Transaccion{}\n\n\tjson.NewDecoder(r.Body).Decode(&deposit)\n\tlog.Println(deposit)\n\n\ttsql := fmt.Sprintf(\"exec SP_DEPOSITO '%d', '%s', %f\", deposit.NoCuenta, deposit.TipoTran, deposit.Monto)\n\tQuery, err := db.Query(tsql)\n\n\tif err == nil {\n\t\tnotification := models.Notification{\n\t\t\tNoCuenta: deposit.NoCuenta,\n\t\t\tMonto: deposit.Monto,\n\t\t\tRazon: \"Transaccion realizada exitosamente\",\n\t\t\tStatus: true,\n\t\t}\n\n\t\tjsonresult, _ := json.Marshal(notification)\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write(jsonresult)\n\t\treturn\n\t}\n\n\tif err.Error() == help.ErrorCuentaNotFound {\n\t\tnotification := models.Notification{\n\t\t\tNoCuenta: deposit.NoCuenta,\n\t\t\tMonto: deposit.Monto,\n\t\t\tRazon: \"El numero de cuenta proporcionado no es válido\",\n\t\t\tStatus: false,\n\t\t}\n\n\t\tjsonresult, _ := json.Marshal(notification)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write(jsonresult)\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tlog.Println(\"+++ Error no controlado: \", err.Error(), \"+++\")\n\t\treturn\n\t}\n\n\tdefer Query.Close()\n}", "func (p *Proxy) handleShowCreateDatabase(session *driver.Session, query string, node sqlparser.Statement) (*sqltypes.Result, error) {\n\treturn p.ExecuteSingle(query)\n}", "func paymentCreate(service payment.UseCase) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer r.Body.Close()\n\t\tvar p *entity.Payment\n\t\terr := json.NewDecoder(r.Body).Decode(&p)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request payload\")\n\t\t\treturn\n\t\t}\n\t\tp.ID, err = service.Store(p)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\trespondWithJSON(w, http.StatusCreated, p)\n\t})\n}", "func (p *pbft) handleCommit(content []byte) {\n\t//The Request structure is parsed using JSON\n\tc := new(Commit)\n\terr := json.Unmarshal(content, c)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Printf(\"This node has received Commit message from %s. \\n\", c.NodeID)\n\t\n\tMessageNodePubKey := p.getPubKey(c.NodeID)\n\tdigestByte, _ := hex.DecodeString(c.Digest)\n\tif _, ok := p.prePareConfirmCount[c.Digest]; !ok {\n\t\tfmt.Println(\"The current temporary message pool does not have this digest. Deny storing into local message pool.\")\n\t} else if p.sequenceID != c.SequenceID {\n\t\tfmt.Println(\"ID is not correct. Deny storing into local message pool.\")\n\t} else if !p.RsaVerySignWithSha256(digestByte, c.Sign, MessageNodePubKey) {\n\t\tfmt.Println(\"The signiture is not valid! Deny storing into local message pool.\")\n\t} else {\n\t\tp.setCommitConfirmMap(c.Digest, c.NodeID, true) \n\t\tcount := 0\n\t\tfor range p.commitConfirmCount[c.Digest] {\n\t\t\tcount++\n\t\t}\n\t\t\n\t\tp.lock.Lock()\n\t\tif count >= nodeCount/3*2 && !p.isReply[c.Digest] && p.isCommitBordcast[c.Digest] {\n\t\t\tfmt.Println(\"This node has received at least 2f+1 (including itself) Commit messages.\")\n\t\t\t\n\t\t\tlocalMessagePool = append(localMessagePool, p.messagePool[c.Digest].Message)\n\t\t\tinfo := p.node.nodeID + \" has stored the message with msgid:\" + strconv.Itoa(p.messagePool[c.Digest].ID) + \" into the local message pool successfully. The message is \" + p.messagePool[c.Digest].Content\n\t\t\t\n\t\t\tfmt.Println(info)\n\t\t\tfmt.Println(\"sending Reply message to the client ...\")\n\t\t\ttcpDial([]byte(info), p.messagePool[c.Digest].ClientAddr)\n\t\t\tp.isReply[c.Digest] = true\n\t\t\tfmt.Println(\"Reply is done.\")\n\t\t}\n\t\tp.lock.Unlock()\n\t}\n}", "func (_obj *Apipayments) Payments_getPaymentForm(params *TLpayments_getPaymentForm, _opt ...map[string]string) (ret Payments_PaymentForm, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"payments_getPaymentForm\", _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 = ret.ReadBlock(_is, 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 (p *pbft) handlePrepare(content []byte) {\n\t//The Request structure is parsed using JSON\n\tpre := new(Prepare)\n\terr := json.Unmarshal(content, pre)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Printf(\"This node has received the Prepare message from %s ... \\n\", pre.NodeID)\n\t//\n\tMessageNodePubKey := p.getPubKey(pre.NodeID)\n\tdigestByte, _ := hex.DecodeString(pre.Digest)\n\tif _, ok := p.messagePool[pre.Digest]; !ok {\n\t\tfmt.Println(\"The current temporary message pool does not have this digest. Deny sending Commit message.\")\n\t} else if p.sequenceID != pre.SequenceID {\n\t\tfmt.Println(\"ID is not correct. Deny sending Commit message.\")\n\t} else if !p.RsaVerySignWithSha256(digestByte, pre.Sign, MessageNodePubKey) {\n\t\tfmt.Println(\"The signiture is not valid! Deny sending Commit message.\")\n\t} else {\n\t\tp.setPrePareConfirmMap(pre.Digest, pre.NodeID, true)\n\t\tcount := 0\n\t\tfor range p.prePareConfirmCount[pre.Digest] {\n\t\t\tcount++\n\t\t}\n\t\t//Since the primary node does not send Prepare message, so it does not include itself.\n\t\tspecifiedCount := 0\n\t\tif p.node.nodeID == \"N0\" {\n\t\t\tspecifiedCount = nodeCount / 3 * 2\n\t\t} else {\n\t\t\tspecifiedCount = (nodeCount / 3 * 2) - 1\n\t\t}\n\t\t\n\t\tp.lock.Lock()\n\t\t\n\t\tif count >= specifiedCount && !p.isCommitBordcast[pre.Digest] {\n\t\t\tfmt.Println(\"This node has received at least 2f (including itself) Prepare messages.\")\n\t\t\t\n\t\t\tsign := p.RsaSignWithSha256(digestByte, p.node.rsaPrivKey)\n\t\t\tc := Commit{pre.Digest, pre.SequenceID, p.node.nodeID, sign}\n\t\t\tbc, err := json.Marshal(c)\n\t\t\tif err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t\t\n\t\t\tfmt.Println(\"sending Commit message to other nodes...\")\n\t\t\tp.broadcast(cCommit, bc)\n\t\t\tp.isCommitBordcast[pre.Digest] = true\n\t\t\tfmt.Println(\"Commit is done.\")\n\t\t}\n\t\tp.lock.Unlock()\n\t}\n}", "func (api *Api) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\thandler(api.DB, w, r)\n\t}\n}", "func (pm *DPoSProtocolManager) handleMsg(msg *p2p.Msg, p *peer) error {\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\t// Handle the message depending on its contents\n\tswitch {\n\tcase msg.Code == SYNC_BIGPERIOD_REQUEST:\n\t\tvar request SyncBigPeriodRequest;\n\t\tif err := msg.Decode(&request); err != nil {\n\t\t\treturn errResp(DPOSErrDecode, \"%v: %v\", msg, err);\n\t\t}\n\t\tif SignCandidates(request.DelegatedTable) != request.DelegatedTableSign {\n\t\t\treturn errResp(DPOSErroDelegatorSign, \"\");\n\t\t}\n\t\tif DelegatorsTable == nil || len(DelegatorsTable) == 0 {\n\t\t\t// i am not ready.\n\t\t\tlog.Info(\"I am not ready!!!\")\n\t\t\treturn nil;\n\t\t}\n\t\tif request.Round == NextGigPeriodInstance.round {\n\t\t\tif NextGigPeriodInstance.state == STATE_CONFIRMED {\n\t\t\t\tlog.Debug(fmt.Sprintf(\"I am in the agreed round %v\", NextGigPeriodInstance.round));\n\t\t\t\t// if i have already confirmed this round. send this round to peer.\n\t\t\t\tif TestMode {\n\t\t\t\t\treturn nil;\n\t\t\t\t}\n\t\t\t\treturn p.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\t\tSTATE_CONFIRMED,\n\t\t\t\t\tcurrNodeIdHash});\n\t\t\t} else {\n\t\t\t\tif !reflect.DeepEqual(DelegatorsTable, request.DelegatedTable) {\n\t\t\t\t\tif len(DelegatorsTable) < len(request.DelegatedTable) {\n\t\t\t\t\t\t// refresh table if mismatch.\n\t\t\t\t\t\tDelegatorsTable, DelegatorNodeInfo, _ = VotingAccessor.Refresh()\n\t\t\t\t\t}\n\t\t\t\t\tif !reflect.DeepEqual(DelegatorsTable, request.DelegatedTable) {\n\t\t\t\t\t\tlog.Debug(\"Delegators are mismatched in two tables.\");\n\t\t\t\t\t\tif TestMode {\n\t\t\t\t\t\t\treturn nil;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// both delegators are not matched, both lose the election power of this round.\n\t\t\t\t\t\treturn p.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\t\t\t\tSTATE_MISMATCHED_DNUMBER,\n\t\t\t\t\t\t\tcurrNodeIdHash});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tNextGigPeriodInstance.state = STATE_CONFIRMED;\n\t\t\t\tNextGigPeriodInstance.delegatedNodes = request.DelegatedTable;\n\t\t\t\tNextGigPeriodInstance.delegatedNodesSign = request.DelegatedTableSign;\n\t\t\t\tNextGigPeriodInstance.activeTime = request.ActiveTime;\n\n\t\t\t\tpm.setNextRoundTimer();//sync the timer.\n\t\t\t\tlog.Debug(fmt.Sprintf(\"Agreed this table %v as %v round\", NextGigPeriodInstance.delegatedNodes, NextGigPeriodInstance.round));\n\t\t\t\tif TestMode {\n\t\t\t\t\treturn nil;\n\t\t\t\t}\n\t\t\t\t// broadcast it to all peers again.\n\t\t\t\tfor _, peer := range pm.ethManager.peers.peers {\n\t\t\t\t\terr := peer.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\t\t\tSTATE_CONFIRMED,\n\t\t\t\t\t\tcurrNodeIdHash})\n\t\t\t\t\tif (err != nil) {\n\t\t\t\t\t\tlog.Warn(\"Error occurred while sending VoteElectionRequest: \" + err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if request.Round < NextGigPeriodInstance.round {\n\t\t\tlog.Debug(fmt.Sprintf(\"Mismatched request.round %v, CurrRound %v: \", request.Round, NextGigPeriodInstance.round))\n\t\t\tif TestMode {\n\t\t\t\treturn nil;\n\t\t\t}\n\t\t\treturn p.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\tSTATE_MISMATCHED_ROUND,\n\t\t\t\tcurrNodeIdHash});\n\t\t} else if request.Round > NextGigPeriodInstance.round {\n\t\t\tif (request.Round - NextElectionInfo.round) == 1 {\n\t\t\t\t// the most reason could be the round timeframe switching later than this request.\n\t\t\t\t// but we are continue switching as regular.\n\t\t\t} else {\n\t\t\t\t// attack happens.\n\t\t\t}\n\t\t}\n\tcase msg.Code == SYNC_BIGPERIOD_RESPONSE:\n\t\tvar response SyncBigPeriodResponse;\n\t\tif err := msg.Decode(&response); err != nil {\n\t\t\treturn errResp(DPOSErrDecode, \"%v: %v\", msg, err);\n\t\t}\n\t\tif response.Round != NextGigPeriodInstance.round {\n\t\t\treturn nil;\n\t\t}\n\t\tif SignCandidates(response.DelegatedTable) != response.DelegatedTableSign {\n\t\t\treturn errResp(DPOSErroDelegatorSign, \"\");\n\t\t}\n\t\tnodeId := common.Bytes2Hex(response.NodeId)\n\t\tlog.Debug(\"Received SYNC Big Period response: \" + nodeId);\n\t\tNextGigPeriodInstance.confirmedTickets[nodeId] ++;\n\t\tNextGigPeriodInstance.confirmedBestNode[nodeId] = &GigPeriodTable{\n\t\t\tresponse.Round,\n\t\t\tSTATE_CONFIRMED,\n\t\t\tresponse.DelegatedTable,\n\t\t\tresponse.DelegatedTableSign,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tresponse.ActiveTime,\n\t\t};\n\n\t\tmaxTickets, bestNodeId := uint32(0), \"\";\n\t\tfor key, value := range NextGigPeriodInstance.confirmedTickets {\n\t\t\tif maxTickets < value {\n\t\t\t\tmaxTickets = value;\n\t\t\t\tbestNodeId = key;\n\t\t\t}\n\t\t}\n\t\tif NextGigPeriodInstance.state == STATE_CONFIRMED {\n\t\t\t// set the best node as the final state.\n\t\t\tbestNode := NextGigPeriodInstance.confirmedBestNode[bestNodeId];\n\t\t\tNextGigPeriodInstance.delegatedNodes = bestNode.delegatedNodes;\n\t\t\tNextGigPeriodInstance.delegatedNodesSign = bestNode.delegatedNodesSign;\n\t\t\tNextGigPeriodInstance.activeTime = bestNode.activeTime;\n\t\t\tlog.Debug(fmt.Sprintf(\"Updated the best table: %v\", bestNode.delegatedNodes));\n\t\t\tpm.setNextRoundTimer();\n\t\t} else if NextGigPeriodInstance.state == STATE_LOOKING && uint32(NextGigPeriodInstance.confirmedTickets[bestNodeId]) > uint32(len(NextGigPeriodInstance.delegatedNodes)) {\n\t\t\tNextGigPeriodInstance.state = STATE_CONFIRMED;\n\t\t\tNextGigPeriodInstance.delegatedNodes = response.DelegatedTable;\n\t\t\tNextGigPeriodInstance.delegatedNodesSign = response.DelegatedTableSign;\n\t\t\tNextGigPeriodInstance.activeTime = response.ActiveTime;\n\n\t\t\tpm.setNextRoundTimer();\n\t\t} else if response.State == STATE_MISMATCHED_ROUND {\n\t\t\t// force to create new round\n\t\t\tNextGigPeriodInstance = &GigPeriodTable{\n\t\t\t\tresponse.Round,\n\t\t\t\tSTATE_LOOKING,\n\t\t\t\tresponse.DelegatedTable,\n\t\t\t\tresponse.DelegatedTableSign,\n\t\t\t\tmake(map[string]uint32),\n\t\t\t\tmake(map[string]*GigPeriodTable),\n\t\t\t\tresponse.ActiveTime,\n\t\t\t};\n\t\t\tpm.trySyncAllDelegators()\n\t\t} else if response.State == STATE_MISMATCHED_DNUMBER {\n\t\t\t// refresh table only, and this node loses the election power of this round.\n\t\t\tDelegatorsTable, DelegatorNodeInfo, _ = VotingAccessor.Refresh()\n\t\t}\n\t\treturn nil;\n\tdefault:\n\t\treturn errResp(ErrInvalidMsgCode, \"%v\", msg.Code)\n\t}\n\treturn nil\n}", "func (p *pbft) handleClientRequest(content []byte) {\n\tfmt.Println(\"The primary node has received the request from the client.\")\n\t//The Request structure is parsed using JSON\n\tr := new(Request)\n\terr := json.Unmarshal(content, r)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t//to add infoID\n\tp.sequenceIDAdd()\n\t//to get the digest\n\tdigest := getDigest(*r)\n\tfmt.Println(\"The request has been stored into the temporary message pool.\")\n\t//to store into the temp message pool\n\tp.messagePool[digest] = *r\n\t//to sign the digest by the primary node\n\tdigestByte, _ := hex.DecodeString(digest)\n\tsignInfo := p.RsaSignWithSha256(digestByte, p.node.rsaPrivKey)\n\t//setup PrePrepare message and send to other nodes\n\tpp := PrePrepare{*r, digest, p.sequenceID, signInfo}\n\tb, err := json.Marshal(pp)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Println(\"sending PrePrepare messsage to all the other nodes...\")\n\t//to send PrePrepare message to other nodes\n\tp.broadcast(cPrePrepare, b)\n\tfmt.Println(\"PrePrepare is done.\")\n}", "func generateHandler(db *sqlx.DB, mongodb *mongo.Database) func(w http.ResponseWriter, r *http.Request) {\n\t// prepare once in the beginning.\n\tloc, err := time.LoadLocation(\"Australia/Brisbane\")\n\tif err != nil {\n\t\tlog.Errorln(err)\n\t}\n\n\treturn (func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// req params\n\t\tpage := r.FormValue(\"page\")\n\t\tperPage := r.FormValue(\"per_page\")\n\t\tfilter := r.FormValue(\"filter\")\n\t\tstartDate := r.FormValue(\"start_date\")\n\t\tendDate := r.FormValue(\"end_date\")\n\n\t\toffset, pageInt, perPageInt := 0, 0, 10\n\t\tvar err error\n\t\tif page != \"\" && perPage != \"\" {\n\t\t\tpageInt, err = strconv.Atoi(page)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\t\t\tperPageInt, err = strconv.Atoi(perPage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\t\t\toffset = (pageInt - 1) * perPageInt\n\t\t}\n\t\tlog.Infoln(page, perPage, offset)\n\n\t\tvar filters []string\n\t\tvar args []interface{}\n\t\tidx := 1 // query placeholder for $n; to prevent sql injection.\n\t\tif filter != \"\" {\n\t\t\tfilters = append(filters, fmt.Sprintf(\"order_name ilike $%d\", idx))\n\t\t\targs = append(args, \"%\"+filter+\"%\")\n\t\t\tidx++\n\t\t}\n\t\tif startDate != \"\" {\n\t\t\tfilters = append(filters, fmt.Sprintf(\"DATE(created_at) >= $%d\", idx))\n\t\t\targs = append(args, startDate)\n\t\t\tidx++\n\t\t}\n\t\tif endDate != \"\" {\n\t\t\tfilters = append(filters, fmt.Sprintf(\"DATE(created_at) <= $%d\", idx))\n\t\t\targs = append(args, endDate)\n\t\t\tidx++\n\t\t}\n\n\t\t// TODO: use prepared statement.\n\t\tquery, where := buildQuery(filters, idx)\n\t\tlog.Infoln(query)\n\n\t\tvar orders []Order\n\t\terr = db.Select(&orders, query, append(args, perPage, offset)...)\n\t\tif err != nil {\n\t\t\tlog.Errorln(err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t// count query; use count(1) for efficiency.\n\t\tquery = \"select count(1) from orders \" + where\n\t\tlog.Infoln(query)\n\n\t\tvar total int\n\t\terr = db.Get(&total, query, args...)\n\t\tif err != nil {\n\t\t\tlog.Errorln(err)\n\t\t}\n\t\tlastPage := total / perPageInt\n\n\t\tcustomerColl := mongodb.Collection(\"customers\")\n\t\tcompaniesColl := mongodb.Collection(\"customer_companies\")\n\n\t\tvar data []Order\n\t\tfor _, o := range orders {\n\t\t\tlog.Infoln(o)\n\n\t\t\tvar customer Customer\n\t\t\tfilterCustomer := bson.D{{\"user_id\", o.CustomerID}}\n\t\t\terr = customerColl.FindOne(context.TODO(), filterCustomer).Decode(&customer)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\n\t\t\tvar company Company\n\t\t\tfilterCompany := bson.D{{\"company_id\", customer.CompanyID}}\n\t\t\terr = companiesColl.FindOne(context.TODO(), filterCompany).Decode(&company)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\n\t\t\tparsedTime, err := time.Parse(layoutFrom, o.OrderDate)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\n\t\t\to.CustomerCompany = company.CompanyName\n\t\t\to.CustomerName = customer.Name\n\t\t\to.OrderDate = parsedTime.In(loc).Format(layoutTo)\n\t\t\to.TotalAmountStr = fmt.Sprintf(\"$%.2f\", o.TotalAmount)\n\n\t\t\to.DeliveredAmountStr = \"-\"\n\t\t\tif o.DeliveredAmount > 0 {\n\t\t\t\to.DeliveredAmountStr = fmt.Sprintf(\"$%.2f\", o.DeliveredAmount)\n\t\t\t}\n\n\t\t\tdata = append(data, o)\n\t\t}\n\n\t\tresp := HTTPResponse{\n\t\t\tCurrentPage: pageInt,\n\t\t\tTotal: total,\n\t\t\tFrom: offset + 1,\n\t\t\tTo: offset + perPageInt,\n\t\t\tPerPage: perPageInt,\n\t\t\tLastPage: lastPage,\n\t\t\tData: data,\n\t\t}\n\n\t\t// TODO: move to separate config file.\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"http://localhost:8080\")\n\t\tencoded, err := json.Marshal(resp)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t_, err = w.Write(encoded)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t})\n}", "func (r *relay) handleRequest(reqId uint64, req []byte) {\n\trep := r.handler.HandleRequest(req)\n\tif err := r.sendReply(reqId, rep); err != nil {\n\t\tlog.Printf(\"iris: failed to send reply: %v.\", err)\n\t}\n}", "func (d *deliveryRepository) handlePendingApprovalToProposed(tx *gorm.DB, p *delivery.RequestUpdateDelivery) error {\n\tbalanceCheck, err := d.getBalanceCheck(tx, p)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tif balanceCheck.ServiceFee > balanceCheck.CoinAmount {\n\t\treturn errors.New(\"insufficient service_fee\")\n\t}\n\n\t// Add credit to coin transaction to admin\n\tvar adminId int\n\terr = tx.Raw(`\n\t\tSELECT \n\t\t\tu.id\n\t\tFROM ` + utils.EncloseString(\"user\", \"`\") + ` u\n\t\tWHERE 1 = 1\n\t\t\tAND u.email = (\n\t\t\t\tSELECT\n\t\t\t\t\t` + utils.EncloseString(\"value\", \"`\") + `\t\n\t\t\t\tFROM sysparam\n\t\t\t\tWHERE 1 = 1\n\t\t\t\t\tAND ` + utils.EncloseString(\"key\", \"`\") + ` = \"HANDLER_ADMIN\"\n\t\t\t)\n\t`).Scan(&adminId).Error\n\n\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\treturn errors.New(\"HANDLER_ADMIN not found\")\n\t}\n\tif err != nil {\n\t\treturn errors.New(\"error trying to fetch the HANDLER_ADMIN\")\n\t}\n\n\t// Add seller coin transaction\n\terr = d.addCoinTransaction(\n\t\ttx,\n\t\tadminId,\n\t\tbalanceCheck.SellerId,\n\t\t\"D\",\n\t\tbalanceCheck.ServiceFee,\n\t\tp.DeliveryId,\n\t)\n\tif err != nil {\n\t\treturn errors.New(\"error adding a new coin transaction for the seller: \" + err.Error())\n\t}\n\n\t// Add admin coin transaction\n\terr = d.addCoinTransaction(\n\t\ttx,\n\t\tadminId,\n\t\tadminId,\n\t\t\"D\",\n\t\tbalanceCheck.ServiceFee,\n\t\tp.DeliveryId,\n\t)\n\tif err != nil {\n\t\treturn errors.New(\"error adding a new coin transaction for the admin: \" + err.Error())\n\t}\n\n\t// Update totals seller\n\terr = d.updateCoinTotals(tx, adminId, balanceCheck.SellerId, balanceCheck.ServiceFee*-1)\n\tif err != nil {\n\t\treturn errors.New(\"error updating coin transaction for seller: \" + err.Error())\n\t}\n\n\t// Update totals admin\n\terr = d.updateCoinTotals(tx, adminId, adminId, balanceCheck.ServiceFee)\n\tif err != nil {\n\t\treturn errors.New(\"error updating coin transaction for seller: \" + err.Error())\n\t}\n\n\t// Also, update information of depending\n\t/**\n\tPolicyNumber\n\tName\n\tContactNo\n\tNote\n\tAddress\n\tDescription\n\t*/\n\n\thasLastMinuteUpdates := false\n\n\tif p.PolicyNumber != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.Name != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.ContactNo != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.Note != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.Address != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.ItemDescription != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\n\tif hasLastMinuteUpdates {\n\t\t// Do update\n\t\tsqlLastMinuteUpdate := `\n\t\t\tUPDATE delivery\n\t\t\t\tSET policy_number = ` + utils.GetSQLValue(\"policy_number\", p.PolicyNumber) + `,\n\t\t\t\t\tname = ` + utils.GetSQLValue(\"name\", p.Name) + `,\n\t\t\t\t\tcontact_number = ` + utils.GetSQLValue(\"contact_number\", p.ContactNo) + `,\n\t\t\t\t\tnote = ` + utils.GetSQLValue(\"note\", p.Note) + `,\n\t\t\t\t\taddress = ` + utils.GetSQLValue(\"address\", p.Address) + `,\n\t\t\t\t\titem_description = ` + utils.GetSQLValue(\"item_description\", p.ItemDescription) + `\n\t\t\tWHERE id = ?\n\t\t`\n\t\terr = tx.Exec(sqlLastMinuteUpdate, p.DeliveryId).Error\n\t\tif err != nil {\n\t\t\treturn errors.New(\"error executing last minute updates before moving delivery to 'Proposed': \" + err.Error())\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Has no last minute updates\")\n\t}\n\n\treturn nil\n}", "func (trd *trxDispatcher) process(evt *eventTrx) {\n\t// send the transaction out for burns processing\n\tselect {\n\tcase trd.outTransaction <- evt:\n\tcase <-trd.sigStop:\n\t\treturn\n\t}\n\n\t// process transaction accounts; exit if terminated\n\tvar wg sync.WaitGroup\n\tif !trd.pushAccounts(evt, &wg) {\n\t\treturn\n\t}\n\n\t// process transaction logs; exit if terminated\n\tfor _, lg := range evt.trx.Logs {\n\t\tif !trd.pushLog(lg, evt.blk, evt.trx, &wg) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// store the transaction into the database once the processing is done\n\t// we spawn a lot of go-routines here, so we should test the optimal queue length above\n\tgo trd.waitAndStore(evt, &wg)\n\n\t// broadcast new transaction; if it can not be broadcast quickly, skip\n\tselect {\n\tcase trd.onTransaction <- evt.trx:\n\tcase <-time.After(200 * time.Millisecond):\n\tcase <-trd.sigStop:\n\t}\n}", "func (d *Dao) doHTTPRequest(c context.Context, uri, ip string, params url.Values, res interface{}) (err error) {\n\tenc, err := d.sign(params)\n\tif err != nil {\n\t\terr = pkgerr.Wrapf(err, \"uri:%s,params:%v\", uri, params)\n\t\treturn\n\t}\n\tif enc != \"\" {\n\t\turi = uri + \"?\" + enc\n\t}\n\n\treq, err := xhttp.NewRequest(xhttp.MethodGet, uri, nil)\n\tif err != nil {\n\t\terr = pkgerr.Wrapf(err, \"method:%s,uri:%s\", xhttp.MethodGet, uri)\n\t\treturn\n\t}\n\treq.Header.Set(_userAgent, \"changxuanran@bilibili.com \"+env.AppID)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn d.client.Do(c, req, res)\n}", "func PurchasedRewardsAPIHandler(response http.ResponseWriter, request *http.Request) {\n\tt := time.Now()\n\tlogRequest := t.Format(\"2006/01/02 15:04:05\") + \" | Request:\" + request.Method + \" | Endpoint: purchasedrewards | \" //Connect to database\n\tfmt.Println(logRequest)\n\tdb, e := sql.Open(\"mysql\", dbConnectionURL)\n\tif e != nil {\n\t\tfmt.Print(e)\n\t}\n\n\t//set mime type to JSON\n\tresponse.Header().Set(\"Content-type\", \"application/json\")\n\n\terr := request.ParseForm()\n\tif err != nil {\n\t\thttp.Error(response, fmt.Sprintf(\"error parsing url %v\", err), 500)\n\t}\n\n\t//can't define dynamic slice in golang\n\tvar result = make([]string, 1000)\n\n\tswitch request.Method {\n\tcase GET:\n\t\tGroupId := strings.Replace(request.URL.Path, \"/api/purchasedrewards/\", \"\", -1)\n\n\t\t//fmt.Println(GroupId)\n\t\tst, getErr := db.Prepare(\"select * from PurchasedRewards where GroupId=?\")\n\t\tif err != nil {\n\t\t\tfmt.Print(getErr)\n\t\t}\n\t\trows, getErr := st.Query(GroupId)\n\t\tif getErr != nil {\n\t\t\tfmt.Print(getErr)\n\t\t}\n\t\ti := 0\n\t\tfor rows.Next() {\n\t\t\tvar RequestId int\n\t\t\tvar GroupId int\n\t\t\tvar RewardName string\n\t\t\tvar PointCost int\n\t\t\tvar RewardDescription string\n\t\t\tvar RewardedUser string\n\n\t\t\tgetErr := rows.Scan(&RequestId, &GroupId, &RewardName, &PointCost, &RewardDescription, &RewardedUser)\n\t\t\treward := &PurchasedReward{RequestId: RequestId, GroupId: GroupId, RewardName: RewardName, PointCost: PointCost, RewardDescription: RewardDescription, RewardedUser: RewardedUser}\n\t\t\tb, getErr := json.Marshal(reward)\n\t\t\tif getErr != nil {\n\t\t\t\tfmt.Println(getErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresult[i] = fmt.Sprintf(\"%s\", string(b))\n\t\t\ti++\n\t\t}\n\t\tresult = result[:i]\n\n\tcase POST:\n\n\t\tGroupId := request.PostFormValue(\"GroupId\")\n\t\tRewardName := request.PostFormValue(\"RewardName\")\n\t\tPointCost := request.PostFormValue(\"PointCost\")\n\t\tRewardDescription := request.PostFormValue(\"RewardDescription\")\n\t\tRewardedUser := request.PostFormValue(\"RewardedUser\")\n\n\t\tvar UserBalance int\n\t\tuserBalanceQueryErr := db.QueryRow(\"SELECT TotalPoints FROM `Points` WHERE `EmailAddress`=? AND `GroupId`=?\", RewardedUser, GroupId).Scan(&UserBalance)\n\t\tswitch {\n\t\tcase userBalanceQueryErr == sql.ErrNoRows:\n\t\t\tlog.Printf(logRequest, \"Unable to find user and group: \\n\", RewardedUser, GroupId)\n\t\tcase userBalanceQueryErr != nil:\n\t\t\tlog.Fatal(userBalanceQueryErr)\n\t\tdefault:\n\t\t}\n\t\tcostInt, err := strconv.Atoi(PointCost)\n\t\tif UserBalance > costInt {\n\t\t\t// Update user's points\n\t\t\tUserBalance -= costInt\n\n\t\t\t// Update database row\n\t\t\tstBalanceUpdate, postBalanceUpdateErr := db.Prepare(\"UPDATE Points SET `totalpoints`=?, `emailaddress`=? WHERE `groupid`=?\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Print(err)\n\t\t\t}\n\t\t\tresBalanceUpdate, postBalanceUpdateErr := stBalanceUpdate.Exec(UserBalance, RewardedUser, GroupId)\n\t\t\tif postBalanceUpdateErr != nil {\n\t\t\t\tfmt.Print(postBalanceUpdateErr)\n\t\t\t}\n\t\t\tif resBalanceUpdate != nil {\n\t\t\t\tresult[0] = \"Points Subtracted\"\n\t\t\t}\n\t\t\tresult = result[:1]\n\n\t\t\t// Add purchase to record\n\t\t\tstPurchase, postPurchaseErr := db.Prepare(\"INSERT INTO PurchasedRewards(`requestid`, `groupid`, `rewardname`, `pointcost`, `rewarddescription`, `rewardeduser`) VALUES(NULL,?,?,?,?,?)\")\n\t\t\tif postPurchaseErr != nil {\n\t\t\t\tfmt.Print(postPurchaseErr)\n\t\t\t}\n\t\t\tresPurchase, postPurchaseErr := stPurchase.Exec(GroupId, RewardName, PointCost, RewardDescription, RewardedUser)\n\t\t\tif postPurchaseErr != nil {\n\t\t\t\tfmt.Print(postPurchaseErr)\n\t\t\t}\n\n\t\t\tif resPurchase != nil {\n\t\t\t\tresult[0] = \"Purchase Added\"\n\t\t\t}\n\n\t\t\tresult = result[:1]\n\t\t} else {\n\t\t\tresult[0] = \"Purchase Rejected\"\n\t\t\tresult = result[:1]\n\t\t}\n\n\tcase PUT:\n\t\tRequestId := request.PostFormValue(\"RequestId\")\n\t\tGroupId := request.PostFormValue(\"GroupId\")\n\t\tRewardName := request.PostFormValue(\"RewardName\")\n\t\tPointCost := request.PostFormValue(\"PointCost\")\n\t\tRewardDescription := request.PostFormValue(\"RewardDescription\")\n\t\tRewardedUser := request.PostFormValue(\"RewardedUser\")\n\n\t\tst, putErr := db.Prepare(\"UPDATE PurchasedRewards SET GroupId=?, RewardName=?, PointCost=?, RewardDescription=?, RewardedUser=? WHERE RequestId=?\")\n\t\tif err != nil {\n\t\t\tfmt.Print(putErr)\n\t\t}\n\t\tres, putErr := st.Exec(GroupId, RewardName, PointCost, RewardDescription, RewardedUser, RequestId)\n\t\tif putErr != nil {\n\t\t\tfmt.Print(putErr)\n\t\t}\n\n\t\tif res != nil {\n\t\t\tresult[0] = \"Reward Modified\"\n\t\t}\n\t\tresult = result[:1]\n\n\tcase DELETE:\n\t\tRequestId := strings.Replace(request.URL.Path, \"/api/purchasedrewards/\", \"\", -1)\n\t\tst, deleteErr := db.Prepare(\"DELETE FROM PurchasedRewards where RequestId=?\")\n\t\tif deleteErr != nil {\n\t\t\tfmt.Print(deleteErr)\n\t\t}\n\t\tres, deleteErr := st.Exec(RequestId)\n\t\tif deleteErr != nil {\n\t\t\tfmt.Print(deleteErr)\n\t\t}\n\n\t\tif res != nil {\n\t\t\tresult[0] = \"Reward Deleted\"\n\t\t}\n\t\tresult = result[:1]\n\n\tdefault:\n\t}\n\n\tjson, err := json.Marshal(result)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t// Send the text diagnostics to the client. Clean backslashes from json\n\tfmt.Fprintf(response, \"%v\", CleanJSON(string(json)))\n\t//fmt.Fprintf(response, \" request.URL.Path '%v'\\n\", request.Method)\n\tdb.Close()\n}", "func updatePaymentByID(c *gin.Context) {\n\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"updatePaymentByID\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tvar p storage.Payments\n\terr = c.BindJSON(&p)\n\n\terr = paymentsDB.UpdatePayment(c.Param(\"id\"), &p)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": \"error\", \"message\": \"Could not update the payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"success\", \"message\": \"Payment updated\"})\n\n}", "func (h RequestPPMPaymentHandler) Handle(params ppmop.RequestPPMPaymentParams) middleware.Responder {\n\treturn h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,\n\t\tfunc(appCtx appcontext.AppContext) (middleware.Responder, error) {\n\t\t\tppmID, err := uuid.FromString(params.PersonallyProcuredMoveID.String())\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\tppm, err := models.FetchPersonallyProcuredMove(appCtx.DB(), appCtx.Session(), ppmID)\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\terr = ppm.RequestPayment()\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\tverrs, err := models.SavePersonallyProcuredMove(appCtx.DB(), ppm)\n\t\t\tif err != nil || verrs.HasAny() {\n\t\t\t\treturn handlers.ResponseForVErrors(appCtx.Logger(), verrs, err), err\n\t\t\t}\n\n\t\t\tppmPayload, err := payloadForPPMModel(h.FileStorer(), *ppm)\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\t\t\treturn ppmop.NewRequestPPMPaymentOK().WithPayload(ppmPayload), nil\n\t\t})\n}", "func createOrderHandle(response http.ResponseWriter, request *http.Request) {\n\tlog.Println(\"Create new Order in System\")\n\tcreateOrderCommand := commands.CreateOrder{}\n\torderId := <-orderHandler.CreateOrder(createOrderCommand)\n\twriteResponse(response, orderId)\n}", "func paymentDelete(service payment.UseCase) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\tpaymentID, ok := vars[\"paymentID\"]\n\t\tif !ok {\n\t\t\trespondWithError(w, http.StatusNotFound, \"Missing route parameter 'paymentID'\")\n\t\t\treturn\n\t\t}\n\t\tif entity.IsValidID(paymentID) {\n\t\t\terr := service.Delete(entity.StringToID(paymentID))\n\t\t\tif err != nil {\n\t\t\t\trespondWithError(w, http.StatusNotFound, \"Payment ID does not exist\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespondWithJSON(w, http.StatusNoContent, nil)\n\t\t} else {\n\t\t\trespondWithError(w, http.StatusBadRequest, \"Invalid Payment ID\")\n\t\t\treturn\n\t\t}\n\t})\n}", "func (r *Responder) PaymentRequired() { r.write(http.StatusPaymentRequired) }", "func QueryHandler(w http.ResponseWriter, r *http.Request) {\n\tdb := Connect()\n\tdefer db.Close()\n\n\tcanAccess, account := ValidateAuth(db, r, w)\n\tif !canAccess {\n\t\treturn\n\t}\n\n\tconnection, err := GetConnection(db, account.Id)\n\tif err != nil {\n\t\tif isBadConn(err, false) {\n\t\t\tpanic(err);\n\t\t\treturn;\n\t\t}\n\t\tstateResponse := &StateResponse{\n\t\t\tPeerId: 0,\n\t\t\tStatus: \"\",\n\t\t\tShouldFetch: false,\n\t\t\tShouldPeerFetch: false,\n\t\t}\n\t\tif err := json.NewEncoder(w).Encode(stateResponse); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn;\n\t}\n\n\tpeerId := connection.GetPeerId(account.Id)\n\tstatus := \"\"\n\tif connection.Status == PENDING {\n\t\tif connection.InviteeId == account.Id {\n\t\t\tstatus = \"pendingWithMe\"\n\t\t} else {\n\t\t\tstatus = \"pendingWithPeer\"\n\t\t}\n\t} else {\n\t\tstatus = \"connected\"\n\t}\n\n\tstateResponse := &StateResponse{\n\t\tPeerId: peerId,\n\t\tStatus: status,\n\t}\n\terr = CompleteFetchResponse(stateResponse, db, connection, account)\n\tif err != nil {\n\t\tlog.Printf(\"QueryPayload failed: %s\", err)\n\t\thttp.Error(w, \"could not query payload\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := json.NewEncoder(w).Encode(stateResponse); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (t *Procure2Pay) CreatePurchaseOrder(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n var objpurchaseOrder purchaseOrder\n\tvar objitem item\n\tvar err error\n\t\n\tfmt.Println(\"Entering CreatePurchaseOrder\")\n\n\tif len(args) < 1 {\n\t\tfmt.Println(\"Invalid number of args\")\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"Args [0] is : %v\\n\", args[0])\n\n\t//unmarshal customerInfo data from UI to \"customerInfo\" struct\n\terr = json.Unmarshal([]byte(args[0]), &objpurchaseOrder)\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to unmarshal CreatePurchaseOrder input purchaseOrder: %s\\n\", err)\n\t\treturn shim.Error(err.Error())\n\t\t}\n\n\tfmt.Println(\"purchase order object PO ID variable value is : %s\\n\", objpurchaseOrder.POID)\n\tfmt.Println(\"purchase order object PO ID variable value is : %s\\n\", objpurchaseOrder.Quantity)\n\n\t// Data insertion for Couch DB starts here \n\ttransJSONasBytes, err := json.Marshal(objpurchaseOrder)\n\terr = stub.PutState(objpurchaseOrder.POID, transJSONasBytes)\n\t// Data insertion for Couch DB ends here\n\n\t//unmarshal LoanTransactions data from UI to \"LoanTransactions\" struct\n\terr = json.Unmarshal([]byte(args[0]), &objitem)\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to unmarshal CreatePurchaseOrder input purchaseOrder: %s\\n\", err)\n\t\treturn shim.Error(err.Error())\n\t\t}\n\n\tfmt.Println(\"item object Item ID variable value is : %s\\n\", objitem.ItemID)\n\n\t// Data insertion for Couch DB starts here \n\ttransJSONasBytesLoan, err := json.Marshal(objitem)\n\terr = stub.PutState(objitem.ItemID, transJSONasBytesLoan)\n\t// Data insertion for Couch DB ends here\n\n\tfmt.Println(\"Create Purchase Order Successfully Done\")\n\n\tif err != nil {\n\t\tfmt.Printf(\"\\nUnable to make transevent inputs : %v \", err)\n\t\treturn shim.Error(err.Error())\n\t\t//return nil,nil\n\t}\n\treturn shim.Success(nil)\n}", "func processCommand(db models.DataStore, command []string) (models.StoreyResponse, error) {\n\tswitch command[0] {\n\tcase models.CmdCreateParkingLot:\n\t\tmaxSlots, err := strToInt(command[1])\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn db.AddStorey(maxSlots)\n\tcase models.CmdPark:\n\t\treturn db.Park(command[1], command[2])\n\tcase models.CmdCreateParkingLot:\n\tcase models.CmdStatus:\n\t\treturn db.All()\n\tcase models.CmdLeave:\n\t\tslotPosition, err := strToInt(command[1])\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn db.LeaveByPosition(slotPosition)\n\tcase models.CmdRegistrationNumberByColor:\n\t\treturn db.FindAllByColor(command[1], models.CmdRegistrationNumberByColor)\n\tcase models.CmdSlotnoByCarColor:\n\t\treturn db.FindAllByColor(command[1], models.CmdSlotnoByCarColor)\n\tcase models.CmdSlotnoByRegNumber:\n\t\treturn db.FindByRegistrationNumber(command[1])\n\tdefault:\n\t}\n\n\treturn models.StoreyResponse{}, nil\n}", "func main() {\n\tr := mux.NewRouter()\n\n\tvar err error\n\n\tpsqlInfo := fmt.Sprintf(\n\t\t\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\",\n\t\thost, port, user, password, dbname)\n\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer db.Close()\n\n\tsqlDB := domain.NewSQLDatabase(db)\n\n\thandler := handlers.NewRequestHandler(sqlDB)\n\n\tr.HandleFunc(\"/pay_user\", handler.PayUser).Methods(http.MethodPost)\n\tr.HandleFunc(\"/get_transactions\", handler.GetTransactions).Methods(http.MethodPost)\n\n\tlog.Print(\"Listening on port 80\")\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", 80), r))\n\n}", "func (h *handler) invoke(method handlerMethod) error {\n\t// exp vars used for reading request counts\n\trestExpvars.Add(\"requests_total\", 1)\n\trestExpvars.Add(\"requests_active\", 1)\n\tdefer restExpvars.Add(\"requests_active\", -1)\n\n\tswitch h.rq.Header.Get(\"Content-Encoding\") {\n\tcase \"\":\n\t\th.requestBody = h.rq.Body\n\tdefault:\n\t\treturn base.HTTPErrorf(http.StatusUnsupportedMediaType, \"Unsupported Content-Encoding;\")\n\t}\n\n\th.setHeader(\"Server\", VersionString)\n\n\t//To Do: If there is a \"db\" path variable, look up the database context:\n\tvar dbc *db.DatabaseContext\n dbc, err := h.server.GetDatabase();\n\n\tif err != nil {\n\t\t\th.logRequestLine()\n\t\t\treturn err\n\t}\n\t\n\t\n\t// Authenticate, if not on admin port:\n\tif h.privs != adminPrivs {\n\t\tif err := h.checkAuth(dbc); err != nil { \n\t\t\th.logRequestLine()\n\t\t\treturn err\n\t\t}\n\t}\n\t\n\th.logRequestLine()\n\n\t//assign db to handler h\n\n\treturn method(h) // Call the actual handler code\n\t\n}", "func (httpServer *HttpServer) handleGetRewardAmount(params interface{}, closeChan <-chan struct{}) (interface{}, *rpcservice.RPCError) {\n\tarrayParams := common.InterfaceSlice(params)\n\tif arrayParams == nil || len(arrayParams) != 1 {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"param must be an array at least 1 element\"))\n\t}\n\n\tpaymentAddress, ok := arrayParams[0].(string)\n\tif !ok{\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"payment address is invalid\"))\n\t}\n\n\treturn httpServer.blockService.GetRewardAmount(paymentAddress)\n}", "func handleRequest(pc net.PacketConn, addr net.Addr, pr *PacketRequest, connectionSvc *ConnectionService) {\n\tif pr.Op == OpRRQ { // Read Request\n\t\tLogReadRequest(pr.Filename)\n\t\tdata, err := connectionSvc.openRead(addr.String(), pr.Filename)\n\t\tif err != nil {\n\t\t\tLogFileNotFound(pr.Filename)\n\t\t\tsendResponse(pc, addr, &PacketError{0x1, \"File not found (error opening file read)\"})\n\t\t} else {\n\t\t\tsendResponse(pc, addr, &PacketData{0x1, data})\n\t\t}\n\t} else if pr.Op == OpWRQ { // Write Request\n\t\tLogWriteRequest(pr.Filename)\n\t\tconnectionSvc.openWrite(addr.String(), pr.Filename)\n\t\tsendResponse(pc, addr, &PacketAck{0})\n\t}\n}", "func DoPaymentWithOVO(req paymentRequest) error {\n\t//1. get user Data (saldo OVO)\n\tuserData, err := getUserData(req.userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(userData)\n\t//2. validate\n\t//3. reduce saldo\n\t//4. return sucess\n\treturn nil\n}", "func GetTransactionHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\t// retrieve the parameters\n\tparam := make(map[string]uint64)\n\tfor _, key := range []string{\"blockId\", \"txId\"} {\n\t\tparam[key], _ = strconv.ParseUint(vars[\"blockId\"], 10, 64)\n\t}\n\n\ttmp := atomic.LoadUint64(&lastBlock)\n\tif param[\"blockId\"] > tmp {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terr := fmt.Errorf(\"requested id %d latest %d\", param[\"blockId\"], lastBlock)\n\t\tlog.Println(err.Error())\n\t\t_, _ = w.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\t// retuning anything in the body regardless of any error code\n\t// it may contain\n\t_, _, body, _ := dataCollection.GetTransaction(param[\"blockId\"], param[\"txId\"], config.DefaultRequestsTimeout)\n\twriteResponse(body, &w)\n}", "func (app *Application) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {\n\tvar method, key, value []byte\n\tparts := bytes.Split(req.Tx, []byte(\"=\"))\n\tif len(parts) == 3 {\n\t\tmethod, key, value = parts[0], parts[1], parts[2]\n\t} else {\n\t\tmethod, key, value = req.Tx, req.Tx, req.Tx\n\t}\n\n lib.Log.Notice(string(method))\n\tlib.Log.Notice(string(key))\n lib.Log.Notice(string(value))\n\n switch string(method) {\n case \"add\":\n // 此处修改 app.state.db.Set(prefixKey(key), value)\n app.state.db.Set(key, value)\n app.state.Size++\n case \"modify\":\n exist, e := app.state.db.Has(key)\n lib.Log.Notice(exist)\n if e == nil {\n app.state.db.Delete(key)\n app.state.db.Set(key, value)\n }\n case \"delete\":\n exist, e := app.state.db.Has(key)\n lib.Log.Notice(exist)\n if e == nil {\n app.state.db.Delete(key)\n }\n }\n\n\tevents := []types.Event{\n\t\t{\n\t\t\tType: \"app\",\n\t\t\tAttributes: []kv.Pair{\n\t\t\t\t{Key: []byte(\"creator\"), Value: []byte(\"Cosmoshi Netowoko\")},\n\t\t\t\t{Key: []byte(\"key\"), Value: key},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn types.ResponseDeliverTx{Code: code.CodeTypeOK, Events: events}\n}", "func (self *Client) process(url *url.URL, method string, data interface{}) ([]byte, error) {\n\tjsonb, err := json.Marshal(&data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn self.send(url, method, jsonb)\n}", "func (s *Server) handleGetData(request []byte) {\n\tvar payload serverutil.MsgGetData\n\tif err := getPayload(request, &payload); err != nil {\n\t\tlog.Panic(err)\n\t}\n\taddr := payload.AddrSender.String()\n\tp, _ := s.GetPeer(addr)\n\tp.IncreaseBytesReceived(uint64(len(request)))\n\ts.AddPeer(p)\n\ts.Log(true, fmt.Sprintf(\"GetData kind: %s, with ID:%s received from %s\", payload.Kind, hex.EncodeToString(payload.ID), addr))\n\n\tif payload.Kind == \"block\" {\n\t\t//block\n\t\t//on recupère le block si il existe\n\t\tblock, _ := s.chain.GetBlockByHash(payload.ID)\n\t\tif block != nil {\n\t\t\t//envoie le block au noeud créateur de la requete\n\t\t\ts.sendBlock(payload.AddrSender, block)\n\t\t} else {\n\t\t\tfmt.Println(\"block is nil :( handleGetData\")\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\ttime.Sleep(time.Millisecond * 50)\n\t\t\t\t\tblock, _ := s.chain.GetBlockByHash(payload.ID)\n\t\t\t\t\tif block != nil {\n\t\t\t\t\t\ts.sendBlock(payload.AddrSender, block)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t} else {\n\t\ttx := mempool.Mempool.GetTx(hex.EncodeToString(payload.ID))\n\t\tif tx != nil {\n\t\t\ts.SendTx(payload.AddrSender, tx)\n\t\t}\n\t}\n}", "func (srv *Server) DB(r *http.Request) (*DB, error) {\n\treturn srv.db(r)\n}", "func (c *Connection) processRequest(ch *api.Channel, chMeta *channelMetadata, req *api.VppRequest) error {\n\t// check whether we are connected to VPP\n\tif atomic.LoadUint32(&c.connected) == 0 {\n\t\terr := ErrNotConnected\n\t\tlog.Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\t// retrieve message ID\n\tmsgID, err := c.GetMessageID(req.Message)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to retrieve message ID: %v\", err)\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"msg_name\": req.Message.GetMessageName(),\n\t\t\t\"msg_crc\": req.Message.GetCrcString(),\n\t\t}).Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\t// encode the message into binary\n\tdata, err := c.codec.EncodeMsg(req.Message, msgID)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to encode the messge: %v\", err)\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": msgID,\n\t\t}).Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\tif log.Level == logger.DebugLevel { // for performance reasons - logrus does some processing even if debugs are disabled\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": msgID,\n\t\t\t\"msg_size\": len(data),\n\t\t\t\"msg_name\": req.Message.GetMessageName(),\n\t\t}).Debug(\"Sending a message to VPP.\")\n\t}\n\n\t// send the message\n\tif req.Multipart {\n\t\t// expect multipart response\n\t\tatomic.StoreUint32(&chMeta.multipart, 1)\n\t}\n\n\t// send the request to VPP\n\terr = c.vpp.SendMsg(chMeta.id, data)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to send the messge: %v\", err)\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": msgID,\n\t\t}).Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\tif req.Multipart {\n\t\t// send a control ping to determine end of the multipart response\n\t\tpingData, _ := c.codec.EncodeMsg(msgControlPing, c.pingReqID)\n\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": c.pingReqID,\n\t\t\t\"msg_size\": len(pingData),\n\t\t}).Debug(\"Sending a control ping to VPP.\")\n\n\t\tc.vpp.SendMsg(chMeta.id, pingData)\n\t}\n\n\treturn nil\n}", "func (b *backend) ProcessVerifyUserPayment(user *database.User, vupt v1.VerifyUserPayment) (*v1.VerifyUserPaymentReply, error) {\n\tvar reply v1.VerifyUserPaymentReply\n\tif b.HasUserPaid(user) {\n\t\treply.HasPaid = true\n\t\treturn &reply, nil\n\t}\n\n\tif paywallHasExpired(user.NewUserPaywallPollExpiry) {\n\t\tb.GenerateNewUserPaywall(user)\n\n\t\treply.PaywallAddress = user.NewUserPaywallAddress\n\t\treply.PaywallAmount = user.NewUserPaywallAmount\n\t\treply.PaywallTxNotBefore = user.NewUserPaywallTxNotBefore\n\t\treturn &reply, nil\n\t}\n\n\ttx, _, err := util.FetchTxWithBlockExplorers(user.NewUserPaywallAddress,\n\t\tuser.NewUserPaywallAmount, user.NewUserPaywallTxNotBefore,\n\t\tb.cfg.MinConfirmationsRequired)\n\tif err != nil {\n\t\tif err == util.ErrCannotVerifyPayment {\n\t\t\treturn nil, v1.UserError{\n\t\t\t\tErrorCode: v1.ErrorStatusCannotVerifyPayment,\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif tx != \"\" {\n\t\treply.HasPaid = true\n\n\t\terr = b.updateUserAsPaid(user, tx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// TODO: Add the user to the in-memory pool.\n\t}\n\n\treturn &reply, nil\n}", "func (q queryManager) processQuery(sql string, pubKey []byte, executeifallowed bool) (uint, []byte, []byte, *structures.Transaction, error) {\n\tlocalError := func(err error) (uint, []byte, []byte, *structures.Transaction, error) {\n\t\treturn SQLProcessingResultError, nil, nil, nil, err\n\t}\n\tqp := q.getQueryParser()\n\t// this will get sql type and data from comments. data can be pubkey, txBytes, signature\n\tqparsed, err := qp.ParseQuery(sql)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\t// maybe this query contains signature and txData from previous calls\n\tif len(qparsed.Signature) > 0 && len(qparsed.TransactionBytes) > 0 {\n\t\t// this is a case when signature and txdata were part of SQL comments.\n\t\ttx, err := q.processQueryWithSignature(qparsed.TransactionBytes, qparsed.Signature, executeifallowed)\n\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\treturn SQLProcessingResultTranactionComplete, nil, nil, tx, nil\n\t}\n\n\tneedsTX, err := q.checkQueryNeedsTransaction(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif !needsTX {\n\t\tif !executeifallowed {\n\t\t\t// no need to execute query. just return\n\t\t\treturn SQLProcessingResultExecuted, nil, nil, nil, nil\n\t\t}\n\t\t// no need to have TX\n\t\tif qparsed.IsUpdate() {\n\t\t\t_, err := qp.ExecuteQuery(qparsed.SQL)\n\t\t\tif err != nil {\n\t\t\t\treturn localError(err)\n\t\t\t}\n\t\t}\n\t\treturn SQLProcessingResultExecuted, nil, nil, nil, nil\n\t}\n\t// decide which pubkey to use.\n\n\t// first priority for a key posted as argument, next is the key in SQL comment (parsed) and final is the key\n\t// provided to thi module\n\tif len(pubKey) == 0 {\n\t\tif len(qparsed.PubKey) > 0 {\n\t\t\tpubKey = qparsed.PubKey\n\t\t} else if len(q.pubKey) > 0 {\n\t\t\tpubKey = q.pubKey\n\t\t} else {\n\t\t\t// no pubkey to use. return notice about pubkey required\n\t\t\treturn SQLProcessingResultPubKeyRequired, nil, nil, nil, nil\n\t\t}\n\t}\n\n\t// check if the key has permissions to execute this query\n\thasPerm, err := q.checkExecutePermissions(qparsed, pubKey)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif !hasPerm {\n\t\treturn localError(errors.New(\"No permissions to execute this query\"))\n\t}\n\n\tamount, err := q.checkQueryNeedsPayment(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\t// prepare SQL part of a TX\n\t// this builds RefID for a TX update\n\tsqlUpdate, err := qp.MakeSQLUpdateStructure(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\t// prepare curency TX and add SQL part\n\n\ttxBytes, datatosign, err := q.getTransactionsManager().PrepareNewSQLTransaction(pubKey, sqlUpdate, amount, \"MINTER\")\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\ttx, err := structures.DeserializeTransaction(txBytes)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif len(q.pubKey) > 0 && bytes.Compare(q.pubKey, pubKey) == 0 {\n\t\t// transaction was created by internal pubkey. we have private key for it\n\t\tsignature, err := utils.SignDataByPubKey(q.pubKey, q.privKey, datatosign)\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\ttx, err = q.processQueryWithSignature(txBytes, signature, executeifallowed)\n\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\treturn SQLProcessingResultTranactionCompleteInternally, nil, nil, tx, nil\n\t}\n\treturn SQLProcessingResultSignatureRequired, txBytes, datatosign, nil, nil\n}", "func (b *backend) ProcessProposalPaywallPayment(user *database.User) (*v1.ProposalPaywallPaymentReply, error) {\n\tlog.Tracef(\"ProcessProposalPaywallPayment\")\n\n\tvar (\n\t\ttxID string\n\t\ttxAmount uint64\n\t\tconfirmations uint64\n\t)\n\n\tb.RLock()\n\tdefer b.RUnlock()\n\n\tpoolMember, ok := b.userPaywallPool[user.ID]\n\tif ok {\n\t\ttxID = poolMember.txID\n\t\ttxAmount = poolMember.txAmount\n\t\tconfirmations = poolMember.txConfirmations\n\t}\n\n\treturn &v1.ProposalPaywallPaymentReply{\n\t\tTxID: txID,\n\t\tTxAmount: txAmount,\n\t\tConfirmations: confirmations,\n\t}, nil\n}", "func (_obj *Apipayments) Payments_getPaymentReceipt(params *TLpayments_getPaymentReceipt, _opt ...map[string]string) (ret Payments_PaymentReceipt, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"payments_getPaymentReceipt\", _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 = ret.ReadBlock(_is, 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 handleQuery(schema *graphql.Schema, w http.ResponseWriter, r *http.Request, db database.DB) {\n\tif r.Body == nil {\n\t\thttp.Error(w, \"Must provide graphql query in request body\", 400)\n\t\treturn\n\t}\n\n\t// Read and close JSON request body\n\tbody, err := ioutil.ReadAll(r.Body)\n\n\tdefer func() {\n\t\t_ = r.Body.Close()\n\t}()\n\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"%d error request: %v\", http.StatusBadRequest, err)\n\t\tlog.Error(msg)\n\t\thttp.Error(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar req data\n\tif err := json.Unmarshal(body, &req); err != nil {\n\t\tmsg := fmt.Sprintf(\"Unmarshal request: %v\", err)\n\t\tlog.Error(msg)\n\t\thttp.Error(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Execute graphql query\n\tresult := graphql.Do(graphql.Params{\n\t\tSchema: *schema,\n\t\tRequestString: req.Query,\n\t\tVariableValues: req.Variables,\n\t\tOperationName: req.Operation,\n\t\tContext: context.WithValue(context.Background(), \"database\", db), //nolint\n\t})\n\n\t//// Error check\n\t//if len(result.Errors) > 0 {\n\t//\tlog.\n\t//\t\tWithField(\"query\", req.Query).\n\t//\t\tWithField(\"variables\", req.Variables).\n\t//\t\tWithField(\"operation\", req.Operation).\n\t//\t\tWithField(\"errors\", result.Errors).Error(\"Execute query error(s)\")\n\t//}\n\n\trender.JSON(w, r, result)\n}", "func (d *deliveryAgent) process(message string) {\n\tpb := &postback.Postback{}\n\tif err := json.Unmarshal([]byte(message), pb); err != nil {\n\t\tlog.Println(\"ERROR: \", err)\n\t\treturn\n\t}\n\tpb.MountURL()\n\n\treq := request.NewRequest(pb.Endpoint.Url, pb.Endpoint.Method)\n\n\tswitch strings.ToLower(pb.Endpoint.Method) {\n\tcase \"get\":\n\t\tres, err := req.Get()\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR: \", err)\n\t\t\treturn\n\t\t}\n\t\td.logResponse(res)\n\tcase \"post\":\n\t\tbody, err := json.Marshal(pb.Data[0])\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR: \", err)\n\t\t\treturn\n\t\t}\n\t\treq.Body = body\n\t\tres, err := req.Post()\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR: \", err)\n\t\t\treturn\n\t\t}\n\t\td.logResponse(res)\n\t}\n\n}", "func addProductHandle(response http.ResponseWriter, request *http.Request) {\n\torderId := strings.Split(request.URL.Path, \"/\")[3]\n\tlog.Printf(\"Add product for order %s!\", orderId)\n\tdecoder := json.NewDecoder(request.Body)\n\taddProductCommand := commands.AddProduct{}\n\terr := decoder.Decode(&addProductCommand)\n\tif err != nil {\n\t\twriteErrorResponse(response, err)\n\t}\n\torder := <-orderHandler.AddProductInOrder(OrderId{Id: orderId}, addProductCommand)\n\twriteResponse(response, order)\n}", "func handleConnection(conn net.Conn) {\n\tencoder := json.NewEncoder(conn)\n\tdecoder := json.NewDecoder(conn)\n\n\tvar incomingMsg BackendPayload\n\t// recieveing the response from the backend through the json decoder\n\terr := decoder.Decode(&incomingMsg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tswitch incomingMsg.Mode { // choose function based on the mode sent by front end server\n\tcase \"getTasks\":\n\t\tgetTasks(encoder)\n\tcase \"createTask\":\n\t\tcreateTask(incomingMsg)\n\tcase \"updateTask\":\n\t\tupdateTask(incomingMsg)\n\tcase \"deleteTask\":\n\t\tdeleteTask(incomingMsg)\n\t}\n}" ]
[ "0.8299379", "0.6380844", "0.60654527", "0.5884241", "0.58363223", "0.579999", "0.57807887", "0.5764955", "0.5746082", "0.5651478", "0.5642665", "0.56156886", "0.5587672", "0.5553257", "0.54693264", "0.5430645", "0.5390535", "0.53442734", "0.5306043", "0.5254643", "0.525085", "0.52487946", "0.52435887", "0.52413744", "0.5230424", "0.5229829", "0.5211351", "0.5209689", "0.52031773", "0.51839054", "0.5167543", "0.51625574", "0.5159435", "0.51527596", "0.5144115", "0.51321775", "0.50975204", "0.50891745", "0.50873715", "0.5076915", "0.5064339", "0.50605005", "0.5055608", "0.50482553", "0.5031727", "0.5027052", "0.50172055", "0.5000191", "0.4999502", "0.49962765", "0.4985317", "0.4984395", "0.4972419", "0.49660006", "0.4957933", "0.4943998", "0.49424154", "0.49197236", "0.4916711", "0.4915879", "0.49135098", "0.4910217", "0.49101272", "0.49080944", "0.4883978", "0.48746285", "0.48700133", "0.4868434", "0.4864155", "0.48629084", "0.48565868", "0.48378715", "0.48372182", "0.48254955", "0.4814635", "0.4814586", "0.48123503", "0.48079392", "0.48028904", "0.47994104", "0.47949877", "0.47917205", "0.47882786", "0.47868595", "0.47810903", "0.4778975", "0.4777509", "0.47749197", "0.47690448", "0.47645596", "0.47642747", "0.47636613", "0.47613585", "0.47582126", "0.47566402", "0.47472852", "0.47449476", "0.473718", "0.47363535", "0.4732667" ]
0.80649585
1
/////////////////////////////v4 /////////////////////////////v4 v4handleDBProcesspayment receive and handle the request from client, access DB
/////////////////////////////v4 /////////////////////////////v4 v4handleDBProcesspayment получает и обрабатывает запрос от клиента, обращается к БД
func v4handleDBProcesspayment(w http.ResponseWriter, r *http.Request) { defer func() { db.Connection.Close(nil) }() var errorGeneral string var errorGeneralNbr string var requestData modelito.RequestPayment errorGeneral="" requestData,errorGeneral =obtainParmsProcessPayment(r,errorGeneral) ////////////////////////////////////////////////validate parms /// START if errorGeneral=="" { errorGeneral,errorGeneralNbr= v4ProcessProcessPayment(w , requestData) //logicbusiness.go } if errorGeneral!=""{ //send error response if any //prepare an error JSON Response, if any log.Print("CZ STEP Get the ERROR response JSON ready") /// START fieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr) ////////// write the response (ERROR) w.Header().Set("Content-Type", "application/json") w.Write(fieldDataBytesJson) if(err!=nil){ } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func v4handleDBPostProcesspayment(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var errorGeneral string\n var errorGeneralNbr string\n var requestData modelito.RequestPayment\n \n errorGeneral=\"\"\nrequestData,errorGeneral =obtainPostParmsProcessPayment(r,errorGeneral) //logicrequest_post.go\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= v4ProcessProcessPayment(w , requestData) //logicbusiness.go \n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleDBPostGettokenizedcards(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var errorGeneral string\n var errorGeneralNbr string\n \n \tvar requestData modelito.RequestTokenizedCards\n\n errorGeneral=\"\"\n requestData, errorGeneral=obtainPostParmsGettokenizedcards(r,errorGeneral) //logicrequest_post.go\n\n\t////////////////////////////////////////////////process business rules\n\t/// START\n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGettokenizedcards(w , requestData)\n\t}\n\t/// END\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleDBGeneratetokenized(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var requestData modelito.RequestTokenized\n var errorGeneral string\n var errorGeneralNbr string\n \n errorGeneral=\"\"\n requestData,errorGeneral =obtainParmsGeneratetokenized(r,errorGeneral)\n\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGeneratetokenized(w , requestData)\n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func handleDBPostGeneratetokenized(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tdb.Connection.Close(nil)\n\t}()\n var requestData modelito.RequestTokenized\n var errorGeneral string\n var errorGeneralNbr string\n \n errorGeneral=\"\"\n\n\n requestData,errorGeneral =obtainPostParmsGeneratetokenized(r,errorGeneral) //logicrequest_post.go\n\n\n\n\t////////////////////////////////////////////////validate parms\n\t/// START\n \n if errorGeneral==\"\" {\n\n\t\terrorGeneral,errorGeneralNbr= ProcessGeneratetokenized(w , requestData)\n\t}\n\n if errorGeneral!=\"\"{\n \t//send error response if any\n \t//prepare an error JSON Response, if any\n\t\tlog.Print(\"CZ STEP Get the ERROR response JSON ready\")\n\t\t\n\t\t\t/// START\n\t\tfieldDataBytesJson,err := getJsonResponseError(errorGeneral, errorGeneralNbr)\n\t\t////////// write the response (ERROR)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(fieldDataBytesJson)\t\n\t\tif(err!=nil){\n\t\t\t\n\t\t}\n\t\n } \n\t\t\t\t\t\n}", "func logicDBMysqlProcessDash01Grafica01(requestData modelito.RequestDash01Grafica01, errorGeneral string) ([]modelito.Card,string) {\n\t////////////////////////////////////////////////obtain parms in JSON\n //START \nvar resultCards []modelito.Card\nvar errCards error\n\n\t\t\t\t// START fetchFromDB\n\t\t\t\t var errdb error\n\t\t\t\t var db *sql.DB\n\t\t\t\t // Create connection string\n\t\t\t\t\tconnString := fmt.Sprintf(\"host=%s dbname=%s user=%s password=%s port=%d sslmode=disable\",\n\t\t\t\t\t\tConfig_DB_server,Config_DB_name, Config_DB_user, Config_DB_pass, Config_DB_port)\n\t\t\t\t\n\t\t\t\t if (connString !=\"si\"){\n\n }\n//\"mysql\", \"root:password1@tcp(127.0.0.1:3306)/test\"\n\n\t\t\t\t\t // Create connection pool\n//\t\t\t\t\tdb, errdb = sql.Open(\"postgres\", connString)\n//this use the values set up in the configuration.go\n log.Print(\"Usando para conectar : \" + Config_dbStringType)\n\t\t\t\t\tdb, errdb = sql.Open(Config_dbStringType, Config_connString)\n \n\n\t\t\t\t\tif errdb != nil {\n\t\t\t\t\t\tlog.Print(\"Error creating connection pool: \" + errdb.Error())\n\t\t\t\t\t\terrorGeneral=errdb.Error()\n\t\t\t\t\t}\n\t\t\t\t\t// Close the database connection pool after program executes\n\t\t\t\t\t defer db.Close()\n\t\t\t\t\tif errdb == nil {\n\t\t\t\t\t\tlog.Print(\"Connected!\\n\")\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\terrPing := db.Ping()\n\t\t\t\t\t\tif errPing != nil {\n\t\t\t\t\t\t log.Print(\"Error: Could not establish a connection with the database:\"+ errPing.Error())\n\t\t\t\t\t\t\t errorGeneral=errPing.Error()\n\t\t\t\t\t\t}else{\n\t\t\t\t\t log.Print(\"Ping ok!\\n\")\n//\t\t\t\t\t var misCards modelito.Card\n\t\t\t\t\t \n\t\t\t\t\t resultCards,errCards =modelito.GetCardsByCustomer(db,requestData.Dash0101reference)\n\t\t\t\t\t \t\t\t\t\t log.Print(\"regresa func getCardsByCustomer ok!\\n\")\n\t\t\t\t\t\t\tif errCards != nil {\n\t\t\t\t\t\t\t log.Print(\"Error: :\"+ errCards.Error())\n\t\t\t\t\t\t\t errorGeneral=errCards.Error()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvar cuantos int\n\t\t\t\t\t\t\tcuantos = 0\n\t\t\t\t \tfor _, d := range resultCards {\n\t\t\t\t \t\tlog.Print(\"el registor trae:\"+d.Token+\" \"+d.Bin)\n\t\t\t\t\t\t\t cuantos =1\n\t\t\t \t\t}\n\t\t\t\t\t\t\tif cuantos == 0 {\n\t\t\t\t\t\t\t log.Print(\"DB: records not found\")\n\t\t\t\t\t\t\t errorGeneral=\"Not cards found for the customer reference received\"\n\t\t\t\t\t\t\t}\t\t\n\n\t\t\t\t\t }\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t \n\t\t\t\t// END fetchFromDB\n \n //END\n \t return resultCards, errorGeneral\n }", "func (ctx *Context) PaymentDB(ros ...dbRequestReadOnly) *sql.DB {\n\tvar ro bool\n\tif len(ros) > 0 {\n\t\tfor _, r := range ros {\n\t\t\tif r {\n\t\t\t\tro = true\n\t\t\t}\n\t\t}\n\t}\n\tif !ro {\n\t\treturn ctx.paymentDBWrite\n\t}\n\tif ctx.paymentDBReadOnly == nil {\n\t\treturn ctx.paymentDBWrite\n\t}\n\treturn ctx.paymentDBReadOnly\n}", "func (s *Server) sqlHandler(w http.ResponseWriter, req *http.Request) {\n if(s.block) {\n time.Sleep(1000000* time.Second)\n }\n\n\tquery, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't read body: %s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\n\tif s.leader != s.listen {\n\n\t\tcs, errLeader := transport.Encode(s.leader)\n\t\t\n\t\tif errLeader != nil {\n\t\t\thttp.Error(w, \"Only the primary can service queries, but this is a secondary\", http.StatusBadRequest)\t\n\t\t\tlog.Printf(\"Leader ain't present?: %s\", errLeader)\n\t\t\treturn\n\t\t}\n\n\t\t//_, errLeaderHealthCheck := s.client.SafeGet(cs, \"/healthcheck\") \n\n //if errLeaderHealthCheck != nil {\n // http.Error(w, \"Primary is down\", http.StatusBadRequest)\t\n // return\n //}\n\n\t\tbody, errLResp := s.client.SafePost(cs, \"/sql\", bytes.NewBufferString(string(query)))\n\t\tif errLResp != nil {\n s.block = true\n http.Error(w, \"Can't forward request to primary, gotta block now\", http.StatusBadRequest)\t\n return \n\t//\t log.Printf(\"Didn't get reply from leader: %s\", errLResp)\n\t\t}\n\n formatted := fmt.Sprintf(\"%s\", body)\n resp := []byte(formatted)\n\n\t\tw.Write(resp)\n\t\treturn\n\n\t} else {\n\n\t\tlog.Debugf(\"Primary Received query: %#v\", string(query))\n\t\tresp, err := s.execute(query)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\tw.Write(resp)\n\t\treturn\n\t}\n}", "func (requestHandler *RequestHandler) handler(request events.APIGatewayProxyRequest) {\n\t//Initialize DB if requestHandler.Db = nil\n\tif errResponse := requestHandler.InitializeDB(); errResponse != (structs.ErrorResponse{}) {\n\t\tlog.Fatalf(\"Could not connect to DB when creating AOD/AODICE/QOD/QODICE\")\n\t}\n\tyear, month, day := time.Now().Date()\n\ttoday := fmt.Sprintf(\"%d-%d-%d\", year, month, day)\n\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\tgo func() { defer wg.Done(); requestHandler.insertEnglishQOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertIcelandicQOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertEnglishAOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertIcelandicAOD(today) }()\n\tgo func() { defer wg.Done(); requestHandler.insertTopicsQOD(today) }()\n\twg.Wait()\n}", "func cmdHandler(cmd string, db *sql.DB) (retVal int) {\n // cmd : the string of the user input\n // db : connection to the database\n\n cmd_tkn := strings.Split(strings.Trim(cmd, \"\\n\"), \" \") // tokenize command for easy parsing\n\n // check the balance of an account\n if cmd_tkn[0] == \"balance\" { // balance acctId\n if len(cmd_tkn) == 2 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n dispBalance(acctId, db)\n retVal = 0\n } else {\n dispError(\"Incorrect parameters supplied for balance request.\")\n }\n\n // deposit an amount into an account\n } else if cmd_tkn[0] == \"deposit\" { // deposit acctId amt interestRate\n if len(cmd_tkn) == 4 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n amt, _ := strconv.ParseFloat(cmd_tkn[2], 64)\n intRate, _ := strconv.ParseFloat(cmd_tkn[3], 64)\n retVal = deposit(acctId, db, amt, time.Now(), intRate)\n } else {\n dispError(\"Incorrect parameters supplied for deposit request.\")\n }\n\n // withdraw an amount from an account\n } else if cmd_tkn[0] == \"withdraw\" { // withdraw acctId amt\n if len(cmd_tkn) == 3 {\n acctId, _ := strconv.Atoi(cmd_tkn[1])\n amt, _ := strconv.ParseFloat(cmd_tkn[2], 64)\n err := withdraw(acctId, db, amt, time.Now())\n if err != nil {\n dispError(err.Error())\n }\n } else {\n dispError(\"Incorrect parameters supplied for withdraw request.\")\n }\n\n // display the information on a transaction\n } else if cmd_tkn[0] == \"xtn\" { // xtn xtnId\n if len(cmd_tkn) == 2 {\n xtnId, _ := strconv.Atoi(cmd_tkn[1])\n dispXtn(xtnId, db)\n } else {\n dispError(\"Incorrect parameters supplied for deposit request.\")\n }\n\n // end the program\n } else if cmd_tkn[0] == \"exit\" || cmd_tkn[0] == \"quit\" {\n retVal = 1\n\n // handle incorrect inputs\n } else {\n dispError(\"Invalid command. Try again.\")\n }\n\n return\n}", "func Handler(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// Log body and pass to the DAO\n\tfmt.Printf(\"Received body: %v\\n\", req)\n\n\trequest := new(vm.GeneralRequest)\n\tresponse := request.Validate(req.Body)\n\tif response.Code != 0 {\n\t\treturn events.APIGatewayProxyResponse{Body: response.Marshal(), StatusCode: 500}, nil\n\t}\n\n\trequest.Date = time.Now().Unix()\n\n\tvar mainTable = \"main\"\n\tif value, ok := os.LookupEnv(\"dynamodb_table_main\"); ok {\n\t\tmainTable = value\n\t}\n\n\t// insert data into the DB\n\tdal.Insert(mainTable, request)\n\n\t// Log and return result\n\tfmt.Println(\"Wrote item: \", request)\n\treturn events.APIGatewayProxyResponse{Body: response.Marshal(), StatusCode: 200}, nil\n}", "func DataRetrievalHandler(reader fcrserver.FCRServerRequestReader, writer fcrserver.FCRServerResponseWriter, request *fcrmessages.FCRReqMsg) error {\n\tlogging.Debug(\"Handle data retrieval\")\n\t// Get core structure\n\tc := core.GetSingleInstance()\n\tc.MsgSigningKeyLock.RLock()\n\tdefer c.MsgSigningKeyLock.RUnlock()\n\n\t// Message decoding\n\tnonce, senderID, offer, accountAddr, voucher, err := fcrmessages.DecodeDataRetrievalRequest(request)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in decoding payload: %v\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Verify signature\n\tif request.VerifyByID(senderID) != nil {\n\t\t// Verify by signing key\n\t\tgwInfo := c.PeerMgr.GetGWInfo(senderID)\n\t\tif gwInfo == nil {\n\t\t\t// Not found, try sync once\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil {\n\t\t\t\terr = fmt.Errorf(\"Error in obtaining information for gateway %v\", senderID)\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t\tif request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t// Try update\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil || request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t\terr = fmt.Errorf(\"Error in verifying request from gateway %v: %v\", senderID, err.Error())\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check payment\n\trefundVoucher := \"\"\n\treceived, lane, err := c.PaymentMgr.Receive(accountAddr, voucher)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in receiving voucher %v:\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tif lane != 1 {\n\t\terr = fmt.Errorf(\"Not correct lane received expect 1 got %v:\", lane)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\texpected := big.NewInt(0).Add(c.Settings.SearchPrice, offer.GetPrice())\n\tif received.Cmp(expected) < 0 {\n\t\t// Short payment\n\t\t// Refund money\n\t\tif received.Cmp(c.Settings.SearchPrice) <= 0 {\n\t\t\t// No refund\n\t\t} else {\n\t\t\tvar ierr error\n\t\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\t\tif ierr != nil {\n\t\t\t\t// This should never happen\n\t\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"Short payment received, expect %v got %v, refund voucher %v\", expected.String(), received.String(), refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Payment is fine, verify offer\n\tif offer.Verify(c.OfferSigningPubKey) != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer signature, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer merkle proof\n\tif offer.VerifyMerkleProof() != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer merkle proof, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer expiry\n\tif offer.HasExpired() {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Offer has expired, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Offer is verified. Respond\n\t// First get the tag\n\ttag := c.OfferMgr.GetTagByCID(offer.GetSubCID())\n\t// Second read the data\n\tdata, err := ioutil.ReadFile(filepath.Join(c.Settings.RetrievalDir, tag))\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in finding the content, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Third encoding response\n\tresponse, err := fcrmessages.EncodeDataRetrievalResponse(nonce, tag, data)\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in encoding the response, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tc.OfferMgr.IncrementCIDAccessCount(offer.GetSubCID())\n\n\treturn writer.Write(response, c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n}", "func (_BaseContent *BaseContentTransactor) ProcessRequestPayment(opts *bind.TransactOpts, request_ID *big.Int, payee common.Address, label string, amount *big.Int) (*types.Transaction, error) {\n\treturn _BaseContent.contract.Transact(opts, \"processRequestPayment\", request_ID, payee, label, amount)\n}", "func ProcessStripePayment(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"NOT IMPLEMENTED\"})\n}", "func (s *Server) handleDashboardPaymentView() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\n\t//steps on the page\n\tsteps := struct {\n\t\tStepDel string\n\t\tStepMarkPaid string\n\t}{\n\t\tStepDel: \"stepDel\",\n\t\tStepMarkPaid: \"stepMarkPaid\",\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"payment-view.html\")\n\t\t})\n\t\tctx, provider, data, errs, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamActiveNav] = provider.GetURLPayments()\n\t\tdata[TplParamSteps] = steps\n\n\t\t//load the booking\n\t\tnow := data[TplParamCurrentTime].(time.Time)\n\t\tvar paymentUI *paymentUI\n\t\tbookIDStr := r.FormValue(URLParams.BookID)\n\t\tif bookIDStr != \"\" {\n\t\t\tctx, book, ok := s.loadTemplateBook(w, r.WithContext(ctx), tpl, data, errs, bookIDStr, false, false)\n\t\t\tif !ok {\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata[TplParamFormAction] = book.GetURLPaymentView()\n\n\t\t\t//load the service\n\t\t\tctx, _, ok = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, book.Service.ID, now)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//probe for a payment\n\t\t\tctx, payment, err := LoadPaymentByProviderIDAndSecondaryIDAndType(ctx, s.getDB(), provider.ID, book.ID, PaymentTypeBooking)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"load payment\", \"error\", err, \"id\", book.ID)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif payment == nil {\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpaymentUI = s.createPaymentUI(payment)\n\t\t} else {\n\t\t\t//load the payment directly\n\t\t\tidStr := r.FormValue(URLParams.PaymentID)\n\t\t\tif idStr == \"\" {\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tid := uuid.FromStringOrNil(idStr)\n\t\t\tif id == uuid.Nil {\n\t\t\t\tlogger.Errorw(\"invalid uuid\", \"id\", idStr)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx, payment, err := LoadPaymentByID(ctx, s.getDB(), &id)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"load payment\", \"error\", err, \"id\", id)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpaymentUI = s.createPaymentUI(payment)\n\t\t\tdata[TplParamFormAction] = paymentUI.GetURLView()\n\n\t\t\t//probe for a booking\n\t\t\tctx, book, ok := s.loadTemplateBook(w, r.WithContext(ctx), tpl, data, errs, payment.SecondaryID.String(), false, false)\n\t\t\tif ok {\n\t\t\t\tctx, _, _ = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, book.Service.ID, now)\n\t\t\t} else if paymentUI.ServiceID != \"\" {\n\t\t\t\tsvcID := uuid.FromStringOrNil(paymentUI.ServiceID)\n\t\t\t\tif svcID == uuid.Nil {\n\t\t\t\t\tlogger.Errorw(\"invalid uuid\", \"id\", paymentUI.ServiceID)\n\t\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tctx, _, _ = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, &svcID, now)\n\t\t\t}\n\t\t}\n\t\tdata[TplParamPayment] = paymentUI\n\n\t\t//set-up the confirmation\n\t\tdata[TplParamConfirmMsg] = GetMsgText(MsgPaymentMarkPaid)\n\t\tdata[TplParamConfirmSubmitName] = URLParams.Step\n\t\tdata[TplParamConfirmSubmitValue] = steps.StepMarkPaid\n\n\t\t//check the method\n\t\tif r.Method == http.MethodGet {\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//process the step\n\t\tstep := r.FormValue(URLParams.Step)\n\t\tswitch step {\n\t\tcase steps.StepDel:\n\t\t\tctx, err := DeletePayment(ctx, s.getDB(), paymentUI.ID)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"delete payment\", \"error\", err, \"id\", paymentUI.ID)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase steps.StepMarkPaid:\n\t\t\tctx, err := UpdatePaymentDirectCapture(ctx, s.getDB(), paymentUI.ID, &now)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"update payment captured\", \"error\", err, \"id\", paymentUI.ID)\n\t\t\t\ts.SetCookieErr(w, Err)\n\t\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tlogger.Errorw(\"invalid step\", \"id\", paymentUI.ID, \"step\", step)\n\t\t\ts.SetCookieErr(w, Err)\n\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\ts.SetCookieMsg(w, MsgUpdateSuccess)\n\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLPayments(), http.StatusSeeOther)\n\t}\n}", "func paymentRequired(rw http.ResponseWriter, r *http.Request) {\n\n}", "func handleRequests(dbgorm *gorm.DB) {\n\n\t//\n\t// lets instantiate some simple things here\n\t//\n\text := echo.New() // This is the externally supported login API. It only exposes SignIn and Sign out\n\tinternal := echo.New() // This is the externally supported login API. It only exposes SignIn and Sign out\n\n\tdb := DAO{DB: dbgorm}\n\n\text.Use(middleware.Recover())\n\text.Use(middleware.Logger())\n\n\tinternal.Use(middleware.Recover())\n\tinternal.Use(middleware.Logger())\n\n\t// This is the only path that can be taken for the external\n\t// There is sign in.\n\t// TODO: Signout\n\text.POST(\"/signin\", signin(db)) // This validates the user, generates a jwt token, and shoves it in a cookie\n\t// This is the only path that can be taken for the external\n\t// There is sign in.\n\t// TODO: Signout\n\text.POST(\"/signout\", signout()) // Lets invalidate the cookie\n\n\t//\n\t// Restricted group\n\t// This is an internal call made by all other microservices\n\t//\n\tv := internal.Group(\"/validate\")\n\t// Configure middleware with the custom claims type\n\tconfig := middleware.JWTConfig{\n\t\tClaims: &m.Claims{},\n\t\tSigningKey: []byte(\"my_secret_key\"),\n\t\tTokenLookup: \"cookie:jwt\",\n\t}\n\tv.Use(validatetoken(db)) // Lets validate the Token to make sure its valid and user is still valid\n\tv.Use(middleware.JWTWithConfig(config)) // If we are good, lets unpack it\n\tv.GET(\"\", GeneratePayload) // lets place the payload\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(2)\n\n\t// Lets fire up the internal first\n\tgo func() {\n\t\tif Properties.InternalMS.IsHTTPS {\n\t\t\tinternal.Logger.Fatal(internal.StartTLS(fmt.Sprintf(\":%d\", Properties.InternalMS.Port), \"./keys/server.crt\",\"./keys/server.key\"))\n\t\t} else {\n\t\t\tinternal.Logger.Fatal(internal.Start(fmt.Sprintf(\":%d\", Properties.InternalMS.Port)))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\t// Lets fire up the external now\n\tgo func() {\n\t\tif Properties.ExternalMS.IsHTTPS {\n\t\t\text.Logger.Fatal(ext.StartTLS(fmt.Sprintf(\":%d\", Properties.ExternalMS.Port), \"./keys/server.crt\",\"./keys/server.key\"))\n\t\t} else {\n\t\t\text.Logger.Fatal(ext.Start(fmt.Sprintf(\":%d\", Properties.ExternalMS.Port)))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n}", "func Order(w http.ResponseWriter, r *http.Request, session *gocql.Session) {\n //Número da Order. Geralmente esse número representa o ID da Order em um sistema externo através da integração com parceiros.\n number := r.FormValue(\"number\")\n //Referência da Order. Usada para facilitar o acesso ou localização da mesma.\n reference := r.FormValue(\"reference\")\n //Status da Order. DRAFT | ENTERED | CANCELED | PAID | APPROVED | REJECTED | RE-ENTERED | CLOSED\n status := r.FormValue(\"status\")\n // Um texto livre usado pelo Merchant para comunicação.\n notes := r.FormValue(\"notes\")\n fmt.Printf(\"Chegou uma requisicoes de order: number %s, reference %s, status %s, notes %s \\n\", number, reference, status, notes)\n\n uuid := gocql.TimeUUID()\n statusInt := translateStatus(status)\n if statusInt == 99 {\n http.Error(w, \"Parametro status invalido\", http.StatusPreconditionFailed)\n return\n }\n\n // Gravar no banco e retornar o UUID gerado\n if err := session.Query(\"INSERT INTO neurorder (order_id, number, reference, status, notes) VALUES (?,?,?,?,?)\", uuid, number, reference, statusInt, notes).Exec(); err != nil {\n fmt.Println(err)\n http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n } else {\n // Retornar um JSON com o UUID (id da Order)\n w.WriteHeader(http.StatusCreated)\n orderResponse := OrderResponse { Uuid: uuid.String() }\n json.NewEncoder(w).Encode(orderResponse)\n }\n}", "func processTxHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/processTx/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif r.Method != \"POST\" { // expecting POST method\n\t\thttp.Error(w, \"Invalid request method.\", 405)\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar txIn TxInput\n\n\terr := decoder.Decode(&txIn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer r.Body.Close()\n\n\t// fmt.Printf(\"\\nTX input:\\n%+v\\n\", txIn)\n\n\ttxResultStr := processTx(&txIn)\n\n\tfmt.Fprintf(w, \"%s\", txResultStr)\n}", "func BobPurchaseDataAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tLog.Infof(\"start purchase data...\")\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_BOB_TX\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\trequestData := r.FormValue(\"request_data\")\n\tvar data RequestData\n\terr := json.Unmarshal([]byte(requestData), &data)\n\tif err != nil {\n\t\tLog.Warnf(\"invalid parameter. data=%v, err=%v\", requestData, err)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"success to parse request data. data=%v\", requestData)\n\n\tif data.MerkleRoot == \"\" || data.AliceIP == \"\" || data.AliceAddr == \"\" || data.BulletinFile == \"\" || data.PubPath == \"\" {\n\t\tLog.Warnf(\"invalid parameter. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"read parameters. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tplog.Detail = fmt.Sprintf(\"merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tbulletin, err := readBulletinFile(data.BulletinFile, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to read bulletin File. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tplog.Detail = fmt.Sprintf(\"%v, merkle root=%v,\", plog.Detail, bulletin.SigmaMKLRoot)\n\n\tLog.Debugf(\"step0: prepare for transaction...\")\n\tvar params = BobConnParam{data.AliceIP, data.AliceAddr, bulletin.Mode, data.SubMode, data.OT, data.UnitPrice, \"\", bulletin.SigmaMKLRoot}\n\tnode, conn, params, err := preBobConn(params, ETHKey, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to prepare net for transaction. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := node.Close(); err != nil {\n\t\t\tfmt.Errorf(\"failed to close client node: %v\", err)\n\t\t}\n\t\tif err := conn.Close(); err != nil {\n\t\t\tLog.Errorf(\"failed to close connection on client side: %v\", err)\n\t\t}\n\t}()\n\tLog.Debugf(\"[%v]step0: success to establish connecting session with Alice. Alice IP=%v, Alice address=%v\", params.SessionID, params.AliceIPAddr, params.AliceAddr)\n\tplog.Detail = fmt.Sprintf(\"%v, sessionID=%v,\", plog.Detail, params.SessionID)\n\tplog.SessionId = params.SessionID\n\n\tvar tx BobTransaction\n\ttx.SessionID = params.SessionID\n\ttx.Status = TRANSACTION_STATUS_START\n\ttx.Bulletin = bulletin\n\ttx.AliceIP = params.AliceIPAddr\n\ttx.AliceAddr = params.AliceAddr\n\ttx.Mode = params.Mode\n\ttx.SubMode = params.SubMode\n\ttx.OT = params.OT\n\ttx.UnitPrice = params.UnitPrice\n\ttx.BobAddr = fmt.Sprintf(\"%v\", ETHKey.Address.Hex())\n\n\tLog.Debugf(\"[%v]step0: success to prepare for transaction...\", params.SessionID)\n\ttx.Status = TRANSACTION_STATUS_START\n\terr = insertBobTxToDB(tx)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to save transaction to db for Bob. err=%v\", err)\n\t\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_TRANSACTION_FAILED, \"failed to save transaction to db for Bob.\"))\n\t\treturn\n\t}\n\n\tvar response string\n\tif tx.Mode == TRANSACTION_MODE_PLAIN_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForPOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForPC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForPAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t}\n\t} else if tx.Mode == TRANSACTION_MODE_TABLE_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForTAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\tcase TRANSACTION_SUB_MODE_VRF:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.PhantomKeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\t}\n\t}\n\tvar resp Response\n\terr = json.Unmarshal([]byte(response), &resp)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to parse response. response=%v, err=%v\", response, err)\n\t\tfmt.Fprintf(w, RESPONSE_FAILED_TO_RESPONSE)\n\t\treturn\n\t}\n\tif resp.Code == \"0\" {\n\t\tplog.Result = LOG_RESULT_SUCCESS\n\t}\n\tLog.Debugf(\"[%v]the transaction finish. merkel root=%v, response=%v\", params.SessionID, bulletin.SigmaMKLRoot, response)\n\tfmt.Fprintf(w, response)\n\treturn\n}", "func (g *gateway) ProcessRequest(ctx context.Context, rawRequest []byte) (rawResponse []byte, httpStatusCode int) {\n\t// decode\n\tmsg, err := g.codec.DecodeRequest(rawRequest)\n\tif err != nil {\n\t\treturn newError(g.codec, \"\", api.UserMessageParseError, err.Error())\n\t}\n\tif err = msg.Validate(); err != nil {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.UserMessageParseError, err.Error())\n\t}\n\t// find correct handler\n\thandler, ok := g.handlers[msg.Body.DonId]\n\tif !ok {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.UnsupportedDONIdError, \"unsupported DON ID\")\n\t}\n\t// send to the handler\n\tresponseCh := make(chan handlers.UserCallbackPayload, 1)\n\terr = handler.HandleUserMessage(ctx, msg, responseCh)\n\tif err != nil {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.InternalHandlerError, err.Error())\n\t}\n\t// await response\n\tvar response handlers.UserCallbackPayload\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn newError(g.codec, msg.Body.MessageId, api.RequestTimeoutError, \"handler timeout\")\n\tcase response = <-responseCh:\n\t\tbreak\n\t}\n\tif response.ErrCode != api.NoError {\n\t\treturn newError(g.codec, msg.Body.MessageId, response.ErrCode, response.ErrMsg)\n\t}\n\t// encode\n\trawResponse, err = g.codec.EncodeResponse(response.Msg)\n\tif err != nil {\n\t\treturn newError(g.codec, msg.Body.MessageId, api.NodeReponseEncodingError, \"\")\n\t}\n\treturn rawResponse, api.ToHttpErrorCode(api.NoError)\n}", "func(r *PaymentBDRepository)AddPayment(userIDHex string, payment models.Payment)(models.Payment,error){\n\n\tvar response models.Payment\n\tuser := models.User{}\n\n\tpayment.Status = core.StatusActive\n/*\n\tvar queryFind = bson.M{\n\t\t\"_id\": bson.ObjectId(userIDHex),\n\t\t\"payments\": bson.M{ \n\t\t\t\"$elemMatch\": bson.M{ \n\t\t\t\t\"card_number\": payment.CardNumber,\n\t\t\t\t},\n\t\t},\n\t}\n*/\n\tvar queryAdd = bson.M{ \n\t\t\t\"$addToSet\": bson.M{ \n\t\t\t\t\"payments\": payment,\n\t\t\t},\n\t}\n/*\n\tvar queryUpdate = bson.M{\n\t\t\"$set\":bson.M{\n\t\t\t\"payment\": bson.M{\n\t\t\t\t\"payment_type\":\"credit_card\",\n\t\t\t\t\"card_number\": \"xxxxxxxxxxxxxxxx\",\n\t\t\t\t\"cvv\":\"xxx\",\n\t\t\t\t\"end_date\": \"01/19\",\n\t\t\t\t\"user_name\": nil,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t*/\n\n\tsession ,err := mgo.Dial(core.DBUrl)\n\tif err!=nil{\n\t\tfmt.Printf(\"AddPayment error session %s \\n\",err)\n\t\treturn response,err\n\t}\n/*\n\t// Find user with payment in DB\n\terr = session.DB(core.DBName).C(user.GetDocumentName()).FindId(bson.ObjectId(userIDHex)).One(&user)\n\tif err != nil{\n\t\tfmt.Printf(\"AddPayment: Error Finding user %s \\n\",err.Error())\n\t\treturn response,err\n\t}\n\t*/\n\n\t// Appends payment in user model\n\terr = session.DB(core.DBName).C(user.GetDocumentName()).UpdateId(bson.ObjectIdHex(userIDHex),queryAdd)\n\tif err != nil{\n\t\tfmt.Printf(\"AddPayment: Error updating %s \\n\",err.Error())\n\t\treturn response,err\n\t}\n\n\tdefer session.Close()\n\n\treturn payment,nil\n}", "func handleRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte) {\n\tif respMsgBytes := responseCache.Get(msgID, getNetAddress(clientAddr)); respMsgBytes != nil {\n\t\tfmt.Println(\"Handle repeated request - 😡\", respMsgBytes, \"sending to \", clientAddr.Port)\n\n\t\t_, err := conn.WriteToUDP(respMsgBytes, clientAddr)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"handleRequest WriteToUDP\", err)\n\t\t}\n\t} else {\n\t\tincomingCache.Add(msgID, clientAddr)\n\n\t\trespPay := pb.KVResponse{}\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\tfmt.Println(\"+PUT request come in from\", clientAddr.Port)\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\n\t\t\t\tfmt.Println(\"who's sending responsee 🤡 \", self.Addr.String(), \" to \", clientAddr.Port)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second) {\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase GET:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tvar version int32\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[0].Get(reqPay.Key)\n\t\t\t\trespPay.Version = &version\n\t\t\t\t// TODO: check failure, then send request to other two nodes.\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Get(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Remove(reqPay.Key)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second){\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error (can't revert primary lol)\n\t\t\t\t\tfmt.Println(\"????? can't remove fully??\")\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Remove(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\tshutdown <- true\n\t\tcase WIPEOUT:\n\t\t\tif reqPay.ReplicaNum != nil {\n\t\t\t\tdataStorage.Replicas[*reqPay.ReplicaNum].RemoveAll()\n\t\t\t} else {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].RemoveAll()\n\t\t\t\tdataStorage.Replicas[1].RemoveAll()\n\t\t\t\tdataStorage.Replicas[2].RemoveAll()\n\t\t\t}\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = &pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := GetMembershipCount()\n\t\t\trespPay.MembershipCount = &members\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase NOTIFY_FAUILURE:\n\t\t\tfailedNode := GetNodeByIpPort(*reqPay.NodeIpPort)\n\t\t\tif failedNode != nil {\n\t\t\t\tfmt.Println(self.Addr.String(), \" STARTT CONTIUE GOSSSSSSIP 👻💩💩💩💩💩🤢🤢🤢🤢\", *reqPay.NodeIpPort, \"failed\")\n\t\t\t\tRemoveNode(failedNode)\n\t\t\t\tstartGossipFailure(failedNode)\n\t\t\t}\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase ADD_REPLICA:\n\t\t\tkv := dataStorage.decompressReplica(reqPay.Value)\n\t\t\tdataStorage.addReplica(kv, int(*reqPay.ReplicaNum))\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase SEND_REPLICA:\n\t\t\trespPay.Value = dataStorage.compressReplica(int(*reqPay.ReplicaNum))\n\t\t\trespPay.ReceiveData = true\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase RECOVER_PREV_NODE_KEYSPACE:\n\t\t\t// TODO: error handling on and internal failure\n\t\t\tRecoverDataStorage()\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase TEST_GOSSIP:\n\t\t\tfmt.Println(self.Addr.String(), \" TESTING GOSSIP 😡\", *reqPay.NodeIpPort, \"failed\")\n\t\t\tRemoveNode(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\t\tstartGossipFailure(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\tcase TEST_RECOVER_REPLICA:\n\t\t\treqPay := pb.KVRequest{Command: SHUTDOWN}\n\t\t\tsendRequestToNodeUUID(reqPay, self.prevNode())\n\t\t\tRemoveNode(self.prevNode())\n\n\t\t\tRecoverDataStorage()\n\t\tdefault:\n\t\t\t//respPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t\t//sendResponse(clientAddr, msgID, respPay)\n\t\t}\n\t}\n\tprintReplicas(self.Addr.String())\n}", "func (h CreatePaymentRequestHandler) Handle(params paymentrequestop.CreatePaymentRequestParams) middleware.Responder {\n\t// TODO: authorization to create payment request\n\n\treturn h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,\n\t\tfunc(appCtx appcontext.AppContext) (middleware.Responder, error) {\n\n\t\t\tpayload := params.Body\n\t\t\tif payload == nil {\n\t\t\t\terr := apperror.NewBadDataError(\"Invalid payment request: params Body is nil\")\n\t\t\t\terrPayload := payloads.ClientError(handlers.SQLErrMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\t\t\t\tappCtx.Logger().Error(err.Error(), zap.Any(\"payload\", errPayload))\n\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestBadRequest().WithPayload(errPayload), err\n\t\t\t}\n\n\t\t\tappCtx.Logger().Info(\"primeapi.CreatePaymentRequestHandler info\", zap.String(\"pointOfContact\", params.Body.PointOfContact))\n\n\t\t\tmoveTaskOrderIDString := payload.MoveTaskOrderID.String()\n\t\t\tmtoID, err := uuid.FromString(moveTaskOrderIDString)\n\t\t\tif err != nil {\n\t\t\t\tappCtx.Logger().Error(\"Invalid payment request: params MoveTaskOrderID cannot be converted to a UUID\",\n\t\t\t\t\tzap.String(\"MoveTaskOrderID\", moveTaskOrderIDString), zap.Error(err))\n\t\t\t\t// create a custom verrs for returning a 422\n\t\t\t\tverrs :=\n\t\t\t\t\t&validate.Errors{Errors: map[string][]string{\n\t\t\t\t\t\t\"move_id\": {\"id cannot be converted to UUID\"},\n\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\terrPayload := payloads.ValidationError(err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), verrs)\n\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(errPayload), err\n\t\t\t}\n\n\t\t\tisFinal := false\n\t\t\tif payload.IsFinal != nil {\n\t\t\t\tisFinal = *payload.IsFinal\n\t\t\t}\n\n\t\t\tpaymentRequest := models.PaymentRequest{\n\t\t\t\tIsFinal: isFinal,\n\t\t\t\tMoveTaskOrderID: mtoID,\n\t\t\t}\n\n\t\t\t// Build up the paymentRequest.PaymentServiceItems using the incoming payload to offload Swagger data coming\n\t\t\t// in from the API. These paymentRequest.PaymentServiceItems will be used as a temp holder to process the incoming API data\n\t\t\tvar verrs *validate.Errors\n\t\t\tpaymentRequest.PaymentServiceItems, verrs, err = h.buildPaymentServiceItems(appCtx, payload)\n\n\t\t\tif err != nil || verrs.HasAny() {\n\n\t\t\t\tappCtx.Logger().Error(\"could not build service items\", zap.Error(err))\n\t\t\t\t// TODO: do not bail out before creating the payment request, we need the failed record\n\t\t\t\t// we should create the failed record and store it as failed with a rejection\n\t\t\t\terrPayload := payloads.ValidationError(err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), verrs)\n\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(errPayload), err\n\t\t\t}\n\n\t\t\tcreatedPaymentRequest, err := h.PaymentRequestCreator.CreatePaymentRequestCheck(appCtx, &paymentRequest)\n\t\t\tif err != nil {\n\t\t\t\tappCtx.Logger().Error(\"Error creating payment request\", zap.Error(err))\n\t\t\t\tswitch e := err.(type) {\n\t\t\t\tcase apperror.InvalidCreateInputError:\n\t\t\t\t\tverrs := e.ValidationErrors\n\t\t\t\t\tdetail := err.Error()\n\t\t\t\t\tpayload := payloads.ValidationError(detail, h.GetTraceIDFromRequest(params.HTTPRequest), verrs)\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(payload), err\n\n\t\t\t\tcase apperror.NotFoundError:\n\t\t\t\t\tpayload := payloads.ClientError(handlers.NotFoundMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestNotFound().WithPayload(payload), err\n\t\t\t\tcase apperror.ConflictError:\n\t\t\t\t\tpayload := payloads.ClientError(handlers.ConflictErrMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestConflict().WithPayload(payload), err\n\t\t\t\tcase apperror.InvalidInputError:\n\t\t\t\t\tpayload := payloads.ValidationError(err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), &validate.Errors{})\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestUnprocessableEntity().WithPayload(payload), err\n\t\t\t\tcase apperror.QueryError:\n\t\t\t\t\tif e.Unwrap() != nil {\n\t\t\t\t\t\t// If you can unwrap, log the internal error (usually a pq error) for better debugging\n\t\t\t\t\t\tappCtx.Logger().Error(\"primeapi.CreatePaymentRequestHandler query error\", zap.Error(e.Unwrap()))\n\t\t\t\t\t}\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestInternalServerError().WithPayload(\n\t\t\t\t\t\tpayloads.InternalServerError(nil, h.GetTraceIDFromRequest(params.HTTPRequest))), err\n\n\t\t\t\tcase *apperror.BadDataError:\n\t\t\t\t\tpayload := payloads.ClientError(handlers.BadRequestErrMessage, err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest))\n\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestBadRequest().WithPayload(payload), err\n\t\t\t\tdefault:\n\t\t\t\t\tappCtx.Logger().Error(\"Payment Request\",\n\t\t\t\t\t\tzap.Any(\"payload\", payload))\n\t\t\t\t\treturn paymentrequestop.NewCreatePaymentRequestInternalServerError().WithPayload(\n\t\t\t\t\t\tpayloads.InternalServerError(nil, h.GetTraceIDFromRequest(params.HTTPRequest))), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturnPayload := payloads.PaymentRequest(createdPaymentRequest)\n\t\t\tappCtx.Logger().Info(\"Successful payment request creation for mto ID\", zap.String(\"moveID\", moveTaskOrderIDString))\n\t\t\treturn paymentrequestop.NewCreatePaymentRequestCreated().WithPayload(returnPayload), nil\n\t\t})\n}", "func getPayments(c *gin.Context) {\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"getPayments\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tpayments, err := paymentsDB.GetPayments()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem retrieving payments\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, payments)\n\n}", "func ProcessPaymentRequested(ctx fsm.Context, environment ClientDealEnvironment, deal rm.ClientDealState) error {\n\t// If the unseal payment hasn't been made, we need to send funds\n\tif deal.UnsealPrice.GreaterThan(deal.UnsealFundsPaid) {\n\t\tlog.Debugf(\"client: payment needed: unseal price %d > unseal paid %d\",\n\t\t\tdeal.UnsealPrice, deal.UnsealFundsPaid)\n\t\treturn ctx.Trigger(rm.ClientEventSendFunds)\n\t}\n\n\t// If all bytes received have been paid for, we don't need to send funds\n\tif deal.BytesPaidFor >= deal.TotalReceived {\n\t\tlog.Debugf(\"client: no payment needed: bytes paid for %d >= bytes received %d\",\n\t\t\tdeal.BytesPaidFor, deal.TotalReceived)\n\t\treturn nil\n\t}\n\n\t// Not all bytes received have been paid for\n\n\t// If all blocks have been received we need to send a final payment\n\tif deal.AllBlocksReceived {\n\t\tlog.Debugf(\"client: payment needed: all blocks received, bytes paid for %d < bytes received %d\",\n\t\t\tdeal.BytesPaidFor, deal.TotalReceived)\n\t\treturn ctx.Trigger(rm.ClientEventSendFunds)\n\t}\n\n\t// Payments are made in intervals, as bytes are received from the provider.\n\t// If the number of bytes received is at or above the size of the current\n\t// interval, we need to send a payment.\n\tif deal.TotalReceived >= deal.CurrentInterval {\n\t\tlog.Debugf(\"client: payment needed: bytes received %d >= interval %d, bytes paid for %d < bytes received %d\",\n\t\t\tdeal.TotalReceived, deal.CurrentInterval, deal.BytesPaidFor, deal.TotalReceived)\n\t\treturn ctx.Trigger(rm.ClientEventSendFunds)\n\t}\n\n\tlog.Debugf(\"client: no payment needed: received %d < interval %d (paid for %d)\",\n\t\tdeal.TotalReceived, deal.CurrentInterval, deal.BytesPaidFor)\n\treturn nil\n}", "func AuthenticateClient(db *sql.DB, \n\t\treq *http.Request) (code int, dealerkey string, \n\t\tdealerid int, bsvkeyid int, err error) {\n\t//06.03.2013 naj - initialize some variables\n\t//08.06.2015 ghh - added ipaddress\n\tvar accountnumber, sentdealerkey, bsvkey, ipadd string\n\tcode = http.StatusOK\n\n\t//05.29.2013 naj - first we grab the AccountNumber and DealerKey\n\tif req.Method == \"GET\" {\n\t\t//first we need to grab the query string from the url so\n\t\t//that we can retrieve our variables\n\t\ttemp := req.URL.Query()\n\t\taccountnumber = temp.Get(\"accountnumber\")\n\t\tsentdealerkey = temp.Get(\"dealerkey\")\n\t\tbsvkey = temp.Get(\"bsvkey\")\n\t} else {\n\t\taccountnumber = req.FormValue(\"accountnumber\")\n\t\tsentdealerkey = req.FormValue(\"dealerkey\")\n\t\tbsvkey = req.FormValue(\"bsvkey\")\n\t}\n\n\n\t//if we don't get back a BSV key then we need to bail as\n\t//its a requirement. \n\tif bsvkey == \"\" {\n\t\terr = errors.New(\"Missing BSV Key In Package\")\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//if we didn't get an account number for the customer then we need to\n\t//also bail\n\tif accountnumber == \"\" {\n\t\terr = errors.New(\"Missing account number\")\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.03.2013 naj - validate the BSVKey to make sure the the BSV has been certified for MerX\n\terr = db.QueryRow(`select BSVKeyID from AuthorizedBSVKeys \n\t\t\t\t\t\t\twhere BSVKey = '?'`, bsvkey).Scan(&bsvkeyid)\n\n\t//default to having a valid bsvkey\n\tvalidbsvkey := 1\n\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\t//08.06.2015 ghh - before we send back an invalid BSV key we're going to instead\n\t\t\t//flag us to look again after validating the dealer. If the dealer ends up getting\n\t\t\t//validated then we're going to go ahead and insert this BSVKey into our accepted\n\t\t\t//list for this vendor.\n\t\t\tvalidbsvkey = 0\n\n\t\t\t//err = errors.New(\"Invalid BSV Key\")\n\t\t\t//code = http.StatusUnauthorized\n\t\t\t//return\n\t\tcase err != nil:\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t\t}\n\n\t//05.29.2013 naj - check to see if the supplied credentials are correct.\n\t//06.24.2014 naj - new format of request allows for the dealer to submit a request without a dealerkey on the first request to merX.\n\terr = db.QueryRow(`select DealerID, ifnull(DealerKey, '') as DealerKey,\n\t\t\t\t\t\t\tIPAddress\n\t\t\t\t\t\t\tfrom DealerCredentials where AccountNumber = ? \n\t\t\t\t\t\t\tand Active = 1 `, \n\t\t\t\t\t\t\taccountnumber).Scan(&dealerid, &dealerkey, &ipadd )\n\n\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\terr = errors.New(\"Account not found\")\n\t\t\tcode = http.StatusUnauthorized\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t}\n\n\t//05.06.2015 ghh - now we check to see if we have a valid key for the dealer\n\t//already. If they don't match then we get out. Keep in mind they could send\n\t//a blank key on the second attempt after we've generated a key and we need\n\t//to not allow that.\n\tif sentdealerkey != dealerkey {\n\t\terr = errors.New(\"Access Key Is Not Valid\" )\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.03.2013 naj - parse the RemoteAddr and update the client credentials\n\taddress := strings.Split(req.RemoteAddr, \":\")\n\n\t//08.06.2015 ghh - added check to make sure they are coming from the\n\t//linked ipadd if it exists\n\tif ipadd != \"\" && ipadd != address[0] {\n\t\terr = errors.New(\"Invalid IPAddress\" )\n\t\tcode = http.StatusUnauthorized\n\t\treturn\n\t}\n\n\t//06.24.2014 naj - If we got this far then we have a dealerid, now we need to see if \n\t//they dealerkey is empty, if so create a new key and update the dealer record.\n\tif dealerkey == \"\" {\n\t\tdealerkey = uuid.NewV1().String()\n\n\t\t_, err = db.Exec(`update DealerCredentials set DealerKey = ?,\n\t\t\t\t\t\t\t\tLastIPAddress = inet_aton(?),\n\t\t\t\t\t\t\t\tAccessedDateTime = now()\n\t\t\t\t\t\t\t\twhere DealerID = ?`, dealerkey, address[0], dealerid)\n\n\t\tif err != nil {\n\t\t\tcode = http.StatusInternalServerError\n\t\t\treturn\n\t\t}\n\n\t\t//08.06.2015 ghh - if this is the first time the dealer has attempted an order\n\t\t//and we're also missing the bsvkey then we're going to go ahead and insert into\n\t\t//the bsvkey table. The thought is that to hack this you'd have to find a dealer\n\t\t//that themselves has not ever placed an order and then piggy back in to get a valid\n\t\t//key. \n\t\tvar result sql.Result\n\t\tif validbsvkey == 0 {\n\t\t\t//here we need to insert the key into the table so future correspondence will pass\n\t\t\t//without conflict.\n\t\t\tresult, err = db.Exec(`insert into AuthorizedBSVKeys values ( null,\n\t\t\t\t\t\t\t\t\t?, 'Unknown' )`, bsvkey)\n\n\t\t\tif err != nil {\n\t\t\t\treturn \n\t\t\t}\n\n\t\t\t//now grab the bsvkeyid we just generated so we can return it\n\t\t\ttempbsv, _ := result.LastInsertId()\n\t\t\tbsvkeyid = int( tempbsv )\n\t\t}\n\n\t} else {\n\t\t//08.06.2015 ghh - if we did not find a valid bsv key above and flipped this\n\t\t//flag then here we need to raise an error. We ONLY allow this to happen on the\n\t\t//very first communcation with the dealer where we're also pulling a new key for \n\t\t//them\n\t\tif validbsvkey == 0 {\n\t\t\terr = errors.New(\"Invalid BSV Key\")\n\t\t\tcode = http.StatusUnauthorized\n\t\t\treturn\n\t\t}\n\t}\n\n\t_, err = db.Exec(`update DealerCredentials set LastIPAddress = inet_aton(?), \n\t\t\t\t\t\tAccessedDateTime = now() \n\t\t\t\t\t\twhere DealerID = ?`, address[0], dealerid)\n\n\tif err != nil {\n\t\tcode = http.StatusInternalServerError\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Server) handleDashboardPayments() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"payments.html\")\n\t\t})\n\t\tctx, provider, data, _, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//setup the breadcrumbs\n\t\tbreadcrumbs := []breadcrumb{\n\t\t\t{\"Invoices\", \"\"},\n\t\t}\n\t\tdata[TplParamBreadcrumbs] = breadcrumbs\n\t\tdata[TplParamActiveNav] = provider.GetURLPayments()\n\t\tdata[TplParamFormAction] = provider.GetURLPayments()\n\n\t\t//read the form\n\t\tfilterStr := r.FormValue(URLParams.Filter)\n\n\t\t//prepare the data\n\t\tdata[TplParamFilter] = filterStr\n\n\t\t//validate the filter\n\t\tvar err error\n\t\tfilter := PaymentFilterAll\n\t\tif filterStr != \"\" {\n\t\t\tfilter, err = ParsePaymentFilter(filterStr)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"parse filter\", \"error\", err, \"filter\", filterStr)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t}\n\t\t}\n\n\t\t//load the payments\n\t\tctx, payments, err := ListPaymentsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, filter)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"load payments\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamPayments] = s.createPaymentUIs(payments)\n\n\t\t//load the count\n\t\tctx, countUnPaid, err := CountPaymentsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, PaymentFilterUnPaid)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"count payments unpaid\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamCountUnPaid] = countUnPaid\n\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t}\n}", "func (h *Host) ProcessPayment(stream siamux.Stream, bh types.BlockHeight) (modules.PaymentDetails, error) {\n\t// read the PaymentRequest\n\tvar pr modules.PaymentRequest\n\tif err := modules.RPCRead(stream, &pr); err != nil {\n\t\treturn nil, errors.AddContext(err, \"Could not read payment request\")\n\t}\n\n\t// process payment depending on the payment method\n\tif pr.Type == modules.PayByEphemeralAccount {\n\t\treturn h.staticPayByEphemeralAccount(stream, bh)\n\t}\n\tif pr.Type == modules.PayByContract {\n\t\treturn h.managedPayByContract(stream, bh)\n\t}\n\n\treturn nil, errors.Compose(fmt.Errorf(\"Could not handle payment method %v\", pr.Type), modules.ErrUnknownPaymentMethod)\n}", "func (s *Server) handleDashboardPayment() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"payment.html\")\n\t\t})\n\t\tctx, provider, data, errs, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamActiveNav] = provider.GetURLBookings()\n\n\t\t//load the booking\n\t\tidStr := r.FormValue(URLParams.BookID)\n\t\tctx, book, ok := s.loadTemplateBook(w, r.WithContext(ctx), tpl, data, errs, idStr, true, false)\n\t\tif !ok {\n\t\t\ts.SetCookieErr(w, Err)\n\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLBookings(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamFormAction] = book.GetURLPayment()\n\n\t\t//check if a payment is supported, otherwise view the order\n\t\tif !book.SupportsPayment() {\n\t\t\thttp.Redirect(w, r.WithContext(ctx), book.GetURLView(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\n\t\t//check if already paid, in which case just view the payment\n\t\tif book.IsPaid() {\n\t\t\thttp.Redirect(w, r.WithContext(ctx), book.GetURLPaymentView(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\n\t\t//load the service\n\t\tnow := data[TplParamCurrentTime].(time.Time)\n\t\tctx, _, ok = s.loadTemplateService(w, r.WithContext(ctx), tpl, data, provider, book.Service.ID, now)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//check the method\n\t\tif r.Method == http.MethodGet {\n\t\t\tdata[TplParamDesc] = \"\"\n\t\t\tdata[TplParamEmail] = book.Client.Email\n\t\t\tdata[TplParamName] = book.Client.Name\n\t\t\tdata[TplParamPhone] = book.Client.Phone\n\t\t\tdata[TplParamPrice] = book.ComputeServicePrice()\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//read the form\n\t\tdesc := r.FormValue(URLParams.Desc)\n\t\temail := r.FormValue(URLParams.Email)\n\t\tname := r.FormValue(URLParams.Name)\n\t\tphone := r.FormValue(URLParams.Phone)\n\t\tpriceStr := r.FormValue(URLParams.Price)\n\n\t\t//prepare the data\n\t\tdata[TplParamDesc] = desc\n\t\tdata[TplParamEmail] = email\n\t\tdata[TplParamName] = name\n\t\tdata[TplParamPhone] = phone\n\t\tdata[TplParamPrice] = priceStr\n\n\t\t//validate the form\n\t\tform := &PaymentForm{\n\t\t\tEmailForm: EmailForm{\n\t\t\t\tEmail: strings.TrimSpace(email),\n\t\t\t},\n\t\t\tNameForm: NameForm{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tPhone: FormatPhone(phone),\n\t\t\tPrice: priceStr,\n\t\t\tDescription: desc,\n\t\t\tClientInitiated: false,\n\t\t\tDirectCapture: false,\n\t\t}\n\t\tok = s.validateForm(w, r.WithContext(ctx), tpl, data, errs, form, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//save the payment\n\t\tctx, payment, err := s.savePaymentBooking(ctx, provider, book, form, now)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"save payment\", \"error\", err)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//queue the email\n\t\tpaymentUI := s.createPaymentUI(payment)\n\t\tctx, err = s.queueEmailInvoice(ctx, provider.Name, paymentUI)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"queue email invoice\", \"error\", err)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//success\n\t\ts.SetCookieMsg(w, MsgPaymentSuccess)\n\t\thttp.Redirect(w, r.WithContext(ctx), book.GetURLView(), http.StatusSeeOther)\n\t}\n}", "func (client *GremlinResourcesClient) getGremlinDatabaseHandleResponse(resp *http.Response) (GremlinResourcesClientGetGremlinDatabaseResponse, error) {\n\tresult := GremlinResourcesClientGetGremlinDatabaseResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.GremlinDatabaseGetResults); err != nil {\n\t\treturn GremlinResourcesClientGetGremlinDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func HandleGetDatabaseConnectionState(adminMan *admin.Manager, modules *modules.Modules) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Create a context of execution\n\t\tctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)\n\t\tdefer cancel()\n\n\t\tvars := mux.Vars(r)\n\t\tdbAlias := vars[\"dbAlias\"]\n\n\t\tcrud := modules.DB()\n\t\tconnState := crud.GetConnectionState(ctx, dbAlias)\n\n\t\t_ = utils.SendResponse(w, http.StatusOK, model.Response{Result: connState})\n\t}\n}", "func (c *Client) ProcessRequest(req [][]byte) (err error) {\n\tvar (\n\t\tcommand Command\n\t)\n\tlog.Debugf(\"req:%v,%s\", strings.ToUpper(string(req[0])), req[1:])\n\tif len(req) == 0 {\n\t\tc.cmd = \"\"\n\t\tc.args = nil\n\t} else {\n\t\tc.cmd = strings.ToUpper(string(req[0]))\n\t\tc.args = req[1:]\n\t}\n\tif c.cmd != \"AUTH\" {\n\t\tif !c.isAuth {\n\t\t\tc.FlushResp(qkverror.ErrorNoAuth)\n\t\t\treturn nil\n\t\t}\n\t}\n\tlog.Debugf(\"command: %s argc:%d\", c.cmd, len(c.args))\n\tswitch c.cmd {\n\tcase \"AUTH\":\n\t\tif len(c.args) != 1 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tif c.auth == \"\" {\n\t\t\tc.FlushResp(qkverror.ErrorServerNoAuthNeed)\n\t\t} else if string(c.args[0]) != c.auth {\n\t\t\tc.isAuth = false\n\t\t\tc.FlushResp(qkverror.ErrorAuthFailed)\n\t\t} else {\n\t\t\tc.isAuth = true\n\t\t\tc.w.FlushString(\"OK\")\n\t\t}\n\t\treturn nil\n\tcase \"MULTI\":\n\t\tlog.Debugf(\"client transaction\")\n\t\tc.txn, err = c.tdb.NewTxn()\n\t\tif err != nil {\n\t\t\tc.resetTxn()\n\t\t\tc.w.FlushBulk(nil)\n\t\t\treturn nil\n\t\t}\n\t\tc.isTxn = true\n\t\tc.cmds = []Command{}\n\t\tc.respTxn = []interface{}{}\n\t\tc.w.FlushString(\"OK\")\n\t\terr = nil\n\t\treturn\n\tcase \"EXEC\":\n\t\tlog.Debugf(\"command length : %d txn:%v\", len(c.cmds), c.isTxn)\n\t\tif len(c.cmds) == 0 || !c.isTxn {\n\t\t\tc.w.FlushBulk(nil)\n\t\t\tc.resetTxn()\n\t\t\treturn nil\n\t\t}\n\t\tfor _, cmd := range c.cmds {\n\t\t\tlog.Debugf(\"execute command: %s\", cmd.cmd)\n\t\t\tc.cmd = cmd.cmd\n\t\t\tc.args = cmd.args\n\t\t\tif err = c.execute(); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tc.txn.Rollback()\n\t\t\tc.w.FlushBulk(nil)\n\t\t} else {\n\t\t\terr = c.txn.Commit(context.Background())\n\t\t\tif err == nil {\n\t\t\t\tc.w.FlushArray(c.respTxn)\n\t\t\t} else {\n\t\t\t\tc.w.FlushBulk(nil)\n\t\t\t}\n\t\t}\n\t\tc.resetTxn()\n\t\treturn nil\n\tcase \"DISCARD\":\n\t\t// discard transactional commands\n\t\tif c.isTxn {\n\t\t\terr = c.txn.Rollback()\n\t\t}\n\t\tc.w.FlushString(\"OK\")\n\t\tc.resetTxn()\n\t\treturn err\n\tcase \"PING\":\n\t\tif len(c.args) != 0 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tc.w.FlushString(\"PONG\")\n\t\treturn nil\n\t}\n\tif c.isTxn {\n\t\tcommand = Command{cmd: c.cmd, args: c.args}\n\t\tc.cmds = append(c.cmds, command)\n\t\tlog.Debugf(\"command:%s added to transaction queue, queue size:%d\", c.cmd, len(c.cmds))\n\t\tc.w.FlushString(\"QUEUED\")\n\t} else {\n\t\tc.execute()\n\t}\n\treturn\n\n}", "func (cli *srvClient) processRequest(ctx context.Context, msgID int, pkt *Packet) error {\n\tctx, cancel := context.WithTimeout(ctx, cli.srv.processingTimeout)\n\tdefer cancel()\n\n\t// TODO: use context for deadlines and cancellations\n\tvar res Response\n\tswitch pkt.Tag {\n\tdefault:\n\t\t// _ = pkt.Format(os.Stdout)\n\t\treturn UnsupportedRequestTagError(pkt.Tag)\n\tcase ApplicationUnbindRequest:\n\t\treturn io.EOF\n\tcase ApplicationBindRequest:\n\t\t// TODO: SASL\n\t\treq, err := parseBindRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Bind(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationSearchRequest:\n\t\treq, err := parseSearchRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif req.BaseDN == \"\" && req.Scope == ScopeBaseObject { // TODO check filter\n\t\t\tres, err = cli.rootDSE(req)\n\t\t} else {\n\t\t\tres, err = cli.srv.Backend.Search(ctx, cli.state, req)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationAddRequest:\n\t\treq, err := parseAddRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Add(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationDelRequest:\n\t\treq, err := parseDeleteRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Delete(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyRequest:\n\t\treq, err := parseModifyRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Modify(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyDNRequest:\n\t\treq, err := parseModifyDNRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.ModifyDN(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationExtendedRequest:\n\t\treq, err := parseExtendedRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch req.Name {\n\t\tdefault:\n\t\t\tres, err = cli.srv.Backend.ExtendedRequest(ctx, cli.state, req)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase OIDStartTLS:\n\t\t\tif cli.srv.tlsConfig == nil {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tBaseResponse: BaseResponse{\n\t\t\t\t\t\tCode: ResultUnavailable,\n\t\t\t\t\t\tMessage: \"TLS not configured\",\n\t\t\t\t\t},\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := cli.wr.Flush(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcli.cn = tls.Server(cli.cn, cli.srv.tlsConfig)\n\t\t\t\tcli.wr.Reset(cli.cn)\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase OIDPasswordModify:\n\t\t\tvar r *PasswordModifyRequest\n\t\t\tif len(req.Value) != 0 {\n\t\t\t\tp, _, err := ParsePacket(req.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tr, err = parsePasswordModifyRequest(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr = &PasswordModifyRequest{}\n\t\t\t}\n\t\t\tgen, err := cli.srv.Backend.PasswordModify(ctx, cli.state, r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp := NewPacket(ClassUniversal, false, TagSequence, nil)\n\t\t\tif gen != nil {\n\t\t\t\tp.AddItem(NewPacket(ClassContext, true, 0, gen))\n\t\t\t}\n\t\t\tb, err := p.Encode()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: b,\n\t\t\t}\n\t\tcase OIDWhoAmI:\n\t\t\tv, err := cli.srv.Backend.Whoami(ctx, cli.state)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: []byte(v),\n\t\t\t}\n\t\t}\n\t}\n\tif err := cli.cn.SetWriteDeadline(time.Now().Add(cli.srv.responseTimeout)); err != nil {\n\t\treturn fmt.Errorf(\"failed to set deadline for write: %w\", err)\n\t}\n\tdefer func() {\n\t\tif err := cli.cn.SetWriteDeadline(time.Time{}); err != nil {\n\t\t\tlog.Printf(\"failed to clear deadline for write: %s\", err)\n\t\t}\n\t}()\n\tif res != nil {\n\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn cli.wr.Flush()\n}", "func validatePayment(c *gin.Context) {\n\t// swagger:operation POST /api/v1/payments/fraud-detection/ validatePaymentRequest\n\t//\n\t// validatePayment: Validate the Payment for possible Fraud\n\t//\n\t// Could be info for any Fraud-Detection...\n\t//\n\t// ---\n\t// consumes:\n\t// - application/x-www-form-urlencoded\n\t// responses:\n\t// '200':\n\t// description: \"returns statistics about bought, only ordered, and returned products\"\n\t// schema:\n\t// type: array\n\t// items:\n\t// type: object\n\t// properties:\n\t// status:\n\t// description: the respose status\n\t// type: string\n\t// message:\n\t// description: the response message\n\t// type: string\n\t// resourceId:\n\t// description: the id of the new\n\t// type: string\n\t// \"required\": [\"status\", \"message\"]\n\n\t// Read an Integer param (from POST)\n\t// Atoi is used to convert string to int.\n\tintParam1, err := strconv.Atoi(c.PostForm(\"intParam1\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": http.StatusBadRequest, \"message\": \"StatusBadRequest\"})\n\t\treturn\n\t}\n\n\t// Read a String param (from POST)\n\tstrParam1 := c.PostForm(\"strParam1\")\n\tif len(strParam1) == 0 {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": http.StatusBadRequest, \"message\": \"StatusBadRequest\"})\n\t\treturn\n\t}\n\n\t// Insert to Database:\n\t// ?\n\tdummy := strings.Join([]string{strconv.Itoa(intParam1), strParam1}, \":\")\n\n\t// Return a dummy created response.\n\tc.JSON(http.StatusCreated, gin.H{\n\t\t\"status\": http.StatusCreated,\n\t\t\"message\": \"Fraud-Detection item created successfully!\",\n\t\t\"resourceId\": strings.Join([]string{\"Just Kidding, it is not not implemented yet.\", dummy}, \"\")})\n}", "func (client *SQLResourcesClient) getSQLDatabaseHandleResponse(resp *http.Response) (SQLResourcesClientGetSQLDatabaseResponse, error) {\n\tresult := SQLResourcesClientGetSQLDatabaseResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SQLDatabaseGetResults); err != nil {\n\t\treturn SQLResourcesClientGetSQLDatabaseResponse{}, err\n\t}\n\treturn result, nil\n}", "func Db_access_list(w http.ResponseWriter, r *http.Request) {\n\n///\n/// show d.b. access list inf. on web\n///\n\n process3.Db_access_list(w , r )\n\n}", "func (p *politeiawww) processVerifyUserPayment(u *user.User, vupt www.VerifyUserPayment) (*www.VerifyUserPaymentReply, error) {\n\tvar reply www.VerifyUserPaymentReply\n\tif p.HasUserPaid(u) {\n\t\treply.HasPaid = true\n\t\treturn &reply, nil\n\t}\n\n\tif paywallHasExpired(u.NewUserPaywallPollExpiry) {\n\t\terr := p.GenerateNewUserPaywall(u)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treply.PaywallAddress = u.NewUserPaywallAddress\n\t\treply.PaywallAmount = u.NewUserPaywallAmount\n\t\treply.PaywallTxNotBefore = u.NewUserPaywallTxNotBefore\n\t\treturn &reply, nil\n\t}\n\n\ttx, _, err := util.FetchTxWithBlockExplorers(u.NewUserPaywallAddress,\n\t\tu.NewUserPaywallAmount, u.NewUserPaywallTxNotBefore,\n\t\tp.cfg.MinConfirmationsRequired, p.dcrdataHostHTTP())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tx != \"\" {\n\t\treply.HasPaid = true\n\n\t\terr = p.updateUserAsPaid(u, tx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// TODO: Add the user to the in-memory pool.\n\t}\n\n\treturn &reply, nil\n}", "func (s *Server) handleTransaction(client string, req *pb.Command) (err error) {\n\t// Get the transfer from the original command, will panic if nil\n\ttransfer := req.GetTransfer()\n\tmsg := fmt.Sprintf(\"starting transaction of %0.2f from %s to %s\", transfer.Amount, transfer.Account, transfer.Beneficiary)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Handle Demo UI errors before the account lookup\n\tif transfer.OriginatingVasp != \"\" && transfer.OriginatingVasp != s.vasp.Name {\n\t\tlog.Info().Str(\"requested\", transfer.OriginatingVasp).Str(\"local\", s.vasp.Name).Msg(\"requested originator does not match local VASP\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrWrongVASP, \"message sent to the wrong originator VASP\"),\n\t\t)\n\t}\n\n\t// Lookup the account associated with the transfer originator\n\tvar account Account\n\tif err = LookupAccount(s.db, transfer.Account).First(&account).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"account\", transfer.Account).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"account not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch account: %s\", err)\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"account %04d accessed successfully\", account.ID), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Lookup the wallet of the beneficiary\n\tvar beneficiary Wallet\n\tif err = LookupBeneficiary(s.db, transfer.Beneficiary).First(&beneficiary).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"beneficiary\", transfer.Beneficiary).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"beneficiary wallet not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch beneficiary wallet: %s\", err)\n\t}\n\n\tif transfer.CheckBeneficiary {\n\t\tif transfer.BeneficiaryVasp != beneficiary.Provider.Name {\n\t\t\tlog.Info().\n\t\t\t\tStr(\"expected\", transfer.BeneficiaryVasp).\n\t\t\t\tStr(\"actual\", beneficiary.Provider.Name).\n\t\t\t\tMsg(\"check beneficiary failed\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrWrongVASP, \"beneficiary wallet does not match beneficiary vasp\"),\n\t\t\t)\n\t\t}\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"wallet %s provided by %s\", beneficiary.Address, beneficiary.Provider.Name), pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// TODO: lookup peer from cache rather than always doing a directory service lookup\n\tvar peer *peers.Peer\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"search for %s in directory service\", beneficiary.Provider.Name), pb.MessageCategory_TRISADS)\n\tif peer, err = s.peers.Search(beneficiary.Provider.Name); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not search peer from directory service\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not search peer from directory service\"),\n\t\t)\n\t}\n\tinfo := peer.Info()\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"identified TRISA remote peer %s at %s via directory service\", info.ID, info.Endpoint), pb.MessageCategory_TRISADS)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\tvar signKey *rsa.PublicKey\n\ts.updates.Broadcast(req.Id, \"exchanging peer signing keys\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\tif signKey, err = peer.ExchangeKeys(true); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not exchange keys with remote peer\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not exchange keyrs with remote peer\"),\n\t\t)\n\t}\n\n\t// Prepare the transaction\n\t// Save the pending transaction and increment the accounts pending field\n\txfer := Transaction{\n\t\tEnvelope: uuid.New().String(),\n\t\tAccount: account,\n\t\tAmount: decimal.NewFromFloat32(transfer.Amount),\n\t\tDebit: true,\n\t\tCompleted: false,\n\t}\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save transaction\"),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending++\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save originator account\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"ready to execute transaction\", pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Create an identity and transaction payload for TRISA exchange\n\ttransaction := &generic.Transaction{\n\t\tTxid: fmt.Sprintf(\"%d\", xfer.ID),\n\t\tOriginator: account.WalletAddress,\n\t\tBeneficiary: beneficiary.Address,\n\t\tAmount: float64(transfer.Amount),\n\t\tNetwork: \"TestNet\",\n\t\tTimestamp: xfer.Timestamp.Format(time.RFC3339),\n\t}\n\tidentity := &ivms101.IdentityPayload{\n\t\tOriginator: &ivms101.Originator{},\n\t\tOriginatingVasp: &ivms101.OriginatingVasp{},\n\t}\n\tif identity.OriginatingVasp.OriginatingVasp, err = s.vasp.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator vasp\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator vasp\"),\n\t\t)\n\t}\n\n\tidentity.Originator = &ivms101.Originator{\n\t\tOriginatorPersons: make([]*ivms101.Person, 0, 1),\n\t\tAccountNumbers: []string{account.WalletAddress},\n\t}\n\tvar originator *ivms101.Person\n\tif originator, err = account.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator identity\"),\n\t\t)\n\t}\n\tidentity.Originator.OriginatorPersons = append(identity.Originator.OriginatorPersons, originator)\n\n\tpayload := &protocol.Payload{}\n\tif payload.Transaction, err = anypb.New(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize transaction payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize transaction payload\"),\n\t\t)\n\t}\n\tif payload.Identity, err = anypb.New(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize identity payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize identity payload\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"transaction and identity payload constructed\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Secure the envelope with the remote beneficiary's signing keys\n\tvar envelope *protocol.SecureEnvelope\n\tif envelope, err = handler.New(xfer.Envelope, payload, nil).Seal(signKey); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not create or sign secure envelope\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not create or sign secure envelope\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"secure envelope %s sealed: encrypted with AES-GCM and RSA - sending ...\", envelope.Id), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Conduct the TRISA transaction, handle errors and send back to user\n\tif envelope, err = peer.Transfer(envelope); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not perform TRISA exchange\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"received %s information exchange reply from %s\", envelope.Id, peer.String()), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Open the response envelope with local private keys\n\tvar opened *handler.Envelope\n\tif opened, err = handler.Open(envelope, s.trisa.sign); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unseal TRISA response\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Verify the contents of the response\n\tpayload = opened.Payload\n\tif payload.Identity.TypeUrl != \"type.googleapis.com/ivms101.IdentityPayload\" {\n\t\tlog.Warn().Str(\"type\", payload.Identity.TypeUrl).Msg(\"unsupported identity type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported identity type\", payload.Identity.TypeUrl),\n\t\t)\n\t}\n\n\tif payload.Transaction.TypeUrl != \"type.googleapis.com/trisa.data.generic.v1beta1.Transaction\" {\n\t\tlog.Warn().Str(\"type\", payload.Transaction.TypeUrl).Msg(\"unsupported transaction type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported transaction type\", payload.Transaction.TypeUrl),\n\t\t)\n\t}\n\n\tidentity = &ivms101.IdentityPayload{}\n\ttransaction = &generic.Transaction{}\n\tif err = payload.Identity.UnmarshalTo(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\tif err = payload.Transaction.UnmarshalTo(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"successfully decrypted and parsed secure envelope\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Update the completed transaction and save to disk\n\txfer.Beneficiary = Identity{\n\t\tWalletAddress: transaction.Beneficiary,\n\t}\n\txfer.Completed = true\n\txfer.Timestamp, _ = time.Parse(time.RFC3339, transaction.Timestamp)\n\n\t// Serialize the identity information as JSON data\n\tvar data []byte\n\tif data, err = json.Marshal(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not marshal IVMS 101 identity\"),\n\t\t)\n\t}\n\txfer.Identity = string(data)\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending--\n\taccount.Completed++\n\taccount.Balance.Sub(xfer.Amount)\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\tmsg = fmt.Sprintf(\"transaction %04d complete: %s transfered from %s to %s\", xfer.ID, xfer.Amount.String(), xfer.Originator.WalletAddress, xfer.Beneficiary.WalletAddress)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"%04d new account balance: %s\", account.ID, account.Balance), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\trep := &pb.Message{\n\t\tType: pb.RPC_TRANSFER,\n\t\tId: req.Id,\n\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t\tCategory: pb.MessageCategory_LEDGER,\n\t\tReply: &pb.Message_Transfer{Transfer: &pb.TransferReply{\n\t\t\tTransaction: xfer.Proto(),\n\t\t}},\n\t}\n\n\treturn s.updates.Send(client, rep)\n}", "func handleKVRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest) () {\n\tlog.Println(\"start handling request\")\n\tlog.Println(msgID)\n\tlog.Println(\"sender IP:\", net.IPv4(msgID[0], msgID[1], msgID[2], msgID[3]).String(), \":\", binary.LittleEndian.Uint16(msgID[4:6]))\n\tlog.Println(\"command:\", reqPay.Command)\n\tif reqPay.Addr == nil {\n\n\t\treqPay.Addr = []byte(clientAddr.String())\n\t}\n\n\t// Try to find the response in the cache\n\tif respMsgBytes, ok := GetCachedResponse(msgID); ok {\n\t\t// Send the message back to the client\n\t\t_, _ = conn.WriteToUDP(respMsgBytes, clientAddr)\n\t} else {\n\t\t// Handle the command\n\t\trespPay := pb.KVResponse{}\n\n\t\t/*\n\t\t\tIf the command is PUT, GET or REMOVE, check whether the key exists in\n\t\t\tthis node first. Otherwise,\n\t\t*/\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\t// respPay.ErrCode = Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase GET:\n\t\t\t// var version int32\n\t\t\t// respPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t// respPay.Version = &version\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\tvar version int32\n\t\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t\trespPay.Version = version\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay,msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\t//log.Println(\"############################################################################\")\n\t\t\t//log.Println(\"########################### SHUT DOWN ! ####################################\")\n\t\t\t//log.Println(\"############################################################################\")\n\n\t\t\tshutdown <- true\n\t\t\treturn\n\t\tcase WIPEOUT:\n\t\t\trespPay.ErrCode = RemoveAll()\n\t\t\tnormalReplicate(WIPEOUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := int32(1) // Unused, return 1 for now\n\t\t\trespPay.MembershipCount = members\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_LIST:\n\t\t\tGetMemberShipList(clientAddr, msgID, respPay)\n\t\t\treturn\n\t\t//forward request\n\t\tcase PUT_FORWARD:\n\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase GET_FORWARD:\n\t\t\tvar version int32\n\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\trespPay.Version = version\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase REMOVE_FORWARD:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase PUT_REPLICATE_SON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 0)\n\t\t\treturn\n\t\tcase PUT_REPLICATE_GRANDSON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 1)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_SON:\n\t\t\tRemoveReplicate(reqPay.Key, 0)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_GRANDSON:\n\t\t\tRemoveReplicate(reqPay.Key, 1)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_SON:\n\t\t\tWipeoutReplicate(0)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_GRANDSON:\n\t\t\tWipeoutReplicate(1)\n\t\t\treturn\n\n\t\tcase GRANDSON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(FATHER_DIED, KVStore, addr)\n\t\t\treturn\n\t\tcase SON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(GRANDFATHER_DIED_1, KVStore, addr)\n\t\t\treturn\n\n\t\tcase HELLO:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\t\t\treceiveHello(addr, msgID)\n\t\t\treturn\n\t\tdefault:\n\t\t\trespPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t}\n\n\t\t// Send the response\n\t\tsendResponse(clientAddr, msgID, respPay)\n\t}\n}", "func addPayment(c *gin.Context) {\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"addPayment\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tvar p storage.Payments\n\terr = c.BindJSON(&p)\n\n\terr = paymentsDB.CreatePayment(&p)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Could not add a payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"success\", \"message\": \"Payment created\"})\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\thelper.SetupResponse(&w, r)\n\ti := invoice.Invoice{}\n\tif (*r).Method == \"OPTIONS\" {\n\t\treturn\n\t}\n\tif (*r).Method == \"GET\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tuserID := r.FormValue(\"userID\")\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tlessonID := r.FormValue(\"lessonID\")\n\t\tmode := r.FormValue(\"mode\")\n\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.Read(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"2\" {\n\t\t\tlogs := i.ReadItemLineItem(invoiceID, lessonID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"3\" {\n\t\t\tlogs := i.GetUnpaidInvoice(userID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"4\" {\n\t\t\tlogs := i.GetInvoiceLineItemByInvoiceID(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.GetAllInvoice()\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\t} else if (*r).Method == \"POST\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\t// Invoice\n\t\tuserID := r.FormValue(\"userID\")\n\t\tcreateDate := r.FormValue(\"createDate\")\n\t\ttotal := r.FormValue(\"total\")\n\t\tdetail := r.FormValue(\"detail\")\n\t\tstatus := r.FormValue(\"status\")\n\n\t\t// Line item\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tlessonID := r.FormValue(\"lessonID\")\n\t\tquantityDay := r.FormValue(\"quantityDay\")\n\t\tamountTotal := r.FormValue(\"amountTotal\")\n\n\t\tmode := r.FormValue(\"mode\")\n\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.AddItemToLineItem(invoiceID, lessonID, quantityDay, amountTotal)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.Create(userID, createDate, total, detail, status)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\n\t} else if (*r).Method == \"PUT\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\t// Invoice\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tuserID := r.FormValue(\"userID\")\n\t\tcreateDate := r.FormValue(\"createDate\")\n\t\ttotal := r.FormValue(\"total\")\n\t\tdetail := r.FormValue(\"detail\")\n\t\tstatus := r.FormValue(\"status\")\n\n\t\t// Line item\n\t\tlessonID := r.FormValue(\"lessonID\")\n\t\tquantityDay := r.FormValue(\"quantityDay\")\n\t\tamountTotal := r.FormValue(\"amountTotal\")\n\n\t\tmode := r.FormValue(\"mode\")\n\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.UpdateItemLineItem(invoiceID, lessonID, quantityDay, amountTotal)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"2\" {\n\t\t\tlogs := i.UpdateStatusInvoice(invoiceID, status)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.Update(invoiceID, userID, createDate, total, detail, status)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\n\t} else if (*r).Method == \"DELETE\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tinvoiceID := r.FormValue(\"invoiceID\")\n\t\tlessonID := r.FormValue(\"lessonID\")\n\n\t\tmode := r.FormValue(\"mode\")\n\t\tif mode == \"1\" {\n\t\t\tlogs := i.DeleteItemLineItem(invoiceID, lessonID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else if mode == \"2\" {\n\t\t\tlogs := i.CancelInvoice(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t} else {\n\t\t\tlogs := i.Delete(invoiceID)\n\t\t\tjson.NewEncoder(w).Encode(logs)\n\t\t}\n\n\t} else {\n\t\tfmt.Fprintf(w, \"Please use get medthod\")\n\t}\n}", "func getPaymentByID(c *gin.Context) {\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"getPaymentsByID\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tpayments, err := paymentsDB.GetPayment(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\"status\": \"error\", \"message\": \"Could not find a payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, payments)\n\n}", "func (c *BsnCommitTxHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {\n\t//txnID := requestContext.Response.TransactionID\n\t//GatewayLog.Logs( \"CommitTxHandler Handle TXID 发送交易\",txnID)\n\t//Register Tx event\n\n\t//reg, statusNotifier, err := clientContext.EventService.RegisterTxStatusEvent(string(txnID)) // TODO: Change func to use TransactionID instead of string\n\t//if err != nil {\n\t//\trequestContext.Error = errors.Wrap(err, \"error registering for TxStatus event\")\n\t//\treturn\n\t//}\n\t//defer clientContext.EventService.Unregister(reg)\n\n\tres, err := createAndSendBsnTransaction(clientContext.Transactor, requestContext.Response.Proposal, requestContext.Response.Responses)\n\n\t//GatewayLog.Logs( \"CommitTxHandler Handle 交易结束\")\n\tif err != nil {\n\t\trequestContext.Error = errors.Wrap(err, \"CreateAndSendTransaction failed\")\n\t\treturn\n\t}\n\t//requestContext.Response.TxValidationCode = 0\n\t//GatewayLog.Logs( \"requestContext.Response.Payload :\",string(requestContext.Response.Payload))\n\t//GatewayLog.Logs( \"requestContext.Response.BlockNumber :\",string(requestContext.Response.BlockNumber))\n\t//GatewayLog.Logs( \"requestContext.Response.ChaincodeStatus :\",string(requestContext.Response.ChaincodeStatus))\n\t//select {\n\t//case txStatus := <-statusNotifier:\n\t//\t//GatewayLog.Logs(\"statusNotifier 结果接收 \",&txStatus)\n\t//\trequestContext.Response.TxValidationCode = txStatus.TxValidationCode\n\t//\trequestContext.Response.BlockNumber=txStatus.BlockNumber\n\t//\tif txStatus.TxValidationCode != pb.TxValidationCode_VALID {\n\t//\t\trequestContext.Error = status.New(status.EventServerStatus, int32(txStatus.TxValidationCode),\n\t//\t\t\t\"received invalid transaction\", nil)\n\t//\t\treturn\n\t//\t}\n\t//case <-requestContext.Ctx.Done():\n\t//\trequestContext.Error = status.New(status.ClientStatus, status.Timeout.ToInt32(),\n\t//\t\t\"Execute didn't receive block event\", nil)\n\t//\treturn\n\t//}\n\n\t//Delegate to next step if any\n\tif res != nil {\n\t\trequestContext.Response.OrderDataLen = res.DataLen\n\t}\n\n\tif c.next != nil {\n\t\tc.next.Handle(requestContext, clientContext)\n\t}\n}", "func Process(inputFile string, outputFile string, db *Store) error {\n\tin, err := os.Open(inputFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout, err := os.Create(outputFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\tdefer out.Close()\n\n\tscanner := bufio.NewScanner(in)\n\twriter := bufio.NewWriter(out)\n\tfor scanner.Scan() {\n\t\t// Parse the request\n\t\treq, err := NewRequest(scanner.Text())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Check if it's already processed\n\t\tif db.IsDupTxn(req.ID, req.CustID) {\n\t\t\tlog.Println(\"Ignoring duplicate txn: \", req.ID)\n\t\t\tcontinue\n\t\t}\n\t\t// Fetch the account from DB\n\t\taccount := db.GetAccount(req.CustID)\n\t\t// Act on the request (if velocity limits agree)\n\t\taccepted := account.LoadFunds(req)\n\t\tresponse := NewResponse(req.ID, req.CustID, accepted)\n\t\tresBytes, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Record the response\n\t\tif _, err = writer.WriteString(string(resBytes) + \"\\n\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Record the transaction in DB\n\t\tdb.AddTxn(req.ID, req.CustID)\n\t}\n\t// Check if there were any errors while reading the input file\n\tif err := scanner.Err(); err != nil {\n\t\treturn err\n\t}\n\t// Flush any pending writes\n\twriter.Flush()\n\treturn nil\n}", "func (_obj *Apipayments) Payments_sendPaymentForm(params *TLpayments_sendPaymentForm, _opt ...map[string]string) (ret Payments_PaymentResult, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"payments_sendPaymentForm\", _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 = ret.ReadBlock(_is, 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 HandleInsert(w http.ResponseWriter, r *http.Request) {\n\n\t// Decode the request body into RequestDetails\n\trequestDetails := &queue.RequestDetails{}\n\tif err := json.NewDecoder(r.Body).Decode(requestDetails); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Set the queueDetails\n\tqueueDetails := &queue.Details{}\n\tqueueDetails.Name = requestDetails.Name\n\tqueueDetails.Type = requestDetails.Type\n\tqueueDetails.Depth = requestDetails.Depth\n\tqueueDetails.Rate = requestDetails.Rate\n\tqueueDetails.LastProcessed = requestDetails.LastProcessed\n\tqueueDetails.LastReported = time.Now()\n\n\t// Get the dbsession and insert into the database\n\tdbsession := context.Get(r, \"dbsession\")\n\tinsertFunction := insertQueueDetails(queueDetails)\n\tif err := executeOperation(dbsession, insertFunction); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error occured while saving queue details: %q\", err.Error()), 100)\n\t\treturn\n\t}\n\n\t// Send response\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write([]byte(`{\"result\":\"success\"}`))\n}", "func (e *BsnEndorsementHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {\n\t//GatewayLog.Logs( \"BSNEndorsementHandler Handle 开始交易提案\",)\n\tif len(requestContext.Opts.Targets) == 0 {\n\t\trequestContext.Error = status.New(status.ClientStatus, status.NoPeersFound.ToInt32(), \"targets were not provided\", nil)\n\t\treturn\n\t}\n\n\t// Endorse Tx\n\tvar TxnHeaderOpts []fab.TxnHeaderOpt\n\tif e.headerOptsProvider != nil {\n\t\tTxnHeaderOpts = e.headerOptsProvider()\n\t}\n\t//GatewayLog.Logs( \"createAndSendTransactionProposal 开始发送交易提案\",)\n\n\ttransactionProposalResponses, proposal, err := createAndSendBsnTransactionProposal(\n\t\tclientContext.Transactor,\n\t\t&requestContext.Request,\n\t\tpeer.PeersToTxnProcessors(requestContext.Opts.Targets),\n\t\tTxnHeaderOpts...,\n\t)\n\t//GatewayLog.Logs( \"Query createAndSendTransactionProposal END\",)\n\trequestContext.Response.Proposal = proposal\n\trequestContext.Response.TransactionID = proposal.TxnID // TODO: still needed?\n\n\tif err != nil {\n\t\trequestContext.Error = err\n\t\treturn\n\t}\n\n\trequestContext.Response.Responses = transactionProposalResponses\n\tif len(transactionProposalResponses) > 0 {\n\t\trequestContext.Response.Payload = transactionProposalResponses[0].ProposalResponse.GetResponse().Payload\n\t\trequestContext.Response.ChaincodeStatus = transactionProposalResponses[0].ChaincodeStatus\n\t}\n\t//GatewayLog.Logs( \"Query EndorsementHandler Handle END\",)\n\t//Delegate to next step if any\n\tif e.next != nil {\n\t\te.next.Handle(requestContext, clientContext)\n\t}\n}", "func (p *POSend) ProcessPackage(dealerid int, dealerkey string) ([]byte, error) {\n\tdb := p.db\n\t//10.04.2013 naj - start a transaction\n\ttransaction, err := db.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//06.02.2013 naj - make a slice to hold the purchase orders\n\tr := make([]AcceptedOrder, 0, len(p.PurchaseOrders))\n\n\t//06.05.2015 ghh -because the system has the ability to push more than one purchase\n\t//order through at the same time it will loop through our array and process each\n\t//one separately\n\tfor i := 0; i < len(p.PurchaseOrders); i++ {\n\t\t//06.02.2013 naj - stick the current PO into a new variable to keep the name short.\n\t\tc := p.PurchaseOrders[i]\n\n\n\t\t//06.02.2013 naj - put the current PONumber into the response\n\t\tr = r[0 : len(r)+1]\n\t\tr[i].DealerPO = c.DealerPONumber\n\n\t\t//06.10.2014 naj - check to see if the po is already in the system.\n\t\t//If it is and it's not processed yet, delete the the po and re-enter it.\n\t\t//If it is and it's processed return an error.\n\t\tvar result sql.Result\n\t\tvar temppoid int\n\t\tvar tempstatus int\n\n\t\t//06.02.2015 ghh - first we grab the Ponumber that is being sent to use and we're going to see\n\t\t//if it has already been processed by the vendor\n\t\terr = transaction.QueryRow(`select ifnull(POID, 0 ), ifnull( Status, 0 ) \n\t\t\t\t\t\t\t\t\t\t\tfrom PurchaseOrders \n\t\t\t\t\t\t\t\t\t\t\twhere DealerID = ? and DealerPONumber = ?`,\n\t\t\t\t\tdealerid, c.DealerPONumber).Scan(&temppoid, &tempstatus)\n\n\t\t//case err == sql.ErrNoRows:\n\t\t//if we have a PO already there and its not been processed yet by the vendor then we're going\n\t\t//to delete it as we're uploading it a second time.\n\t\tif temppoid > 0 { \n\t\t\tif tempstatus == 0 { //has it been processed by vendor yet?\n\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrders \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere DealerID=? \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tand DealerPONumber=? `, dealerid, c.DealerPONumber )\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t//now delete the items from the old $_POST[\n\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrderItems \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere POID=? `, temppoid )\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\n\t\t\t\t\t//08.06.2015 ghh - delete units from linked units table\n\t\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrderUnits \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere POID=? `, temppoid )\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//if we get here then we must have found an existing PO so lets log it and return\n\t\t\tif tempstatus > 0 {\n\t\t\t\terr = errors.New(\"Error: 16207 Purchase order already sent and pulled by vendor.\")\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif err != sql.ErrNoRows {\n\t\t\t\t//if there was an error then return it\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t//06.02.2013 naj - create the PO record in the database.\n\t\t\tresult, err = transaction.Exec(`insert into PurchaseOrders (\n\t\t\t\tDealerID, BSVKeyID, DealerPONumber, POReceivedDate, BillToFirstName, BillToLastName, BillToCompanyName, \n\t\t\t\tBillToAddress1, BillToAddress2, BillToCity, BillToState, BillToZip, \n\t\t\t\tBillToCountry, BillToPhone, BillToEmail, \n\t\t\t\tShipToFirstName, ShipToLastName, ShipToCompanyName, ShipToAddress1,\n\t\t\t\tShipToAddress2, ShipToCity, ShipToState, ShipToZip, ShipToCountry, \n\t\t\t\tShipToPhone, ShipToEmail, \n\t\t\t\tPaymentMethod, LastFour, ShipMethod) values \n\t\t\t\t(?, ?, curdate(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t?, ?, ?, ?, ?, ?, ? )`, \n\t\t\t\tdealerid, c.BSVKeyID, c.DealerPONumber,\n\t\t\t\tc.BillToFirstName, c.BillToLastName, c.BillToCompanyName, c.BillToAddress1, \n\t\t\t\tc.BillToAddress2, c.BillToCity, c.BillToState, c.BillToZip, c.BillToCountry, \n\t\t\t\tc.BillToPhone, c.BillToEmail,\n\t\t\t\tc.ShipToFirstName, c.ShipToLastName, c.ShipToCompanyName, c.ShipToAddress1, \n\t\t\t\tc.ShipToAddress2, c.ShipToCity, c.ShipToState, c.ShipToZip, c.ShipToCountry, \n\t\t\t\tc.ShipToPhone, c.ShipToEmail, c.PaymentMethod, c.LastFour, c.ShipMethod )\n\n\t\t\tif err != nil {\n\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t_ = transaction.Rollback()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//06.02.2013 naj - get the POID assigned to the PO\n\t\t\tpoid, err := result.LastInsertId()\n\n\t\t\t//06.02.2013 naj - format the POID and put the assigned POID into the response\n\t\t\ttemp := strconv.FormatInt(poid, 10)\n\n\t\t\tr[i].InternalID = temp\n\t\t\tr[i].DealerKey = dealerkey\n\n\t\t\tif err != nil {\n\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t_ = transaction.Rollback()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//06.05.2015 ghh - now loop through the items array and insert all the parts for\n\t\t\t//the order\n\t\t\tfor j := 0; j < len(c.Items); j++ {\n\t\t\t\t//06.02.2013 naj - attach the parts to the current PO.\n\t\t\t\t_, err := transaction.Exec(`insert into PurchaseOrderItems (POID, PartNumber, VendorID, \n\t\t\t\t\t\t\t\t\t\t\t\t\tQuantity) value (?, ?, ?, ?)`, \n\t\t\t\t\t\t\t\t\t\t\t\t\tpoid, c.Items[j].PartNumber, c.Items[j].VendorID, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Items[j].Qty)\n\t\t\t\tif err != nil {\n\t\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t\t_ = transaction.Rollback()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t\t//08.06.2015 ghh - ( now that we've written the line into the table we need to\n\t\t\t\t\t//query a few things in order to build a proper response to send back. Things\n\t\t\t\t\t//we want to know are how many will ship, any supersession or other known info\n\t\t\t\t\t//current cost...\n\n\t\t\t}\n\n\n\t\t\t//07.21.2015 ghh - now loop through the list of units and add them to the PO\n\t\t\tfor j := 0; j < len(c.Units); j++ {\n\t\t\t\t//06.02.2013 naj - attach the parts to the current PO.\n\t\t\t\t_, err := transaction.Exec(`insert into PurchaseOrderUnits (POID, ModelNumber, Year,\n\t\t\t\t\t\t\t\t\t\t\t\t\tVendorID, OrderCode, Colors, Details \n\t\t\t\t\t\t\t\t\t\t\t\t\tQuantity) value (?, ?, ?, ?, ?, ?, ?, ?)`, \n\t\t\t\t\t\t\t\t\t\t\t\t\tpoid, c.Units[j].ModelNumber, c.Units[j].Year, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].VendorID, c.Units[j].OrderCode,\n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].Colors, c.Units[j].Details,\n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].Qty)\n\t\t\t\tif err != nil {\n\t\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t\t_ = transaction.Rollback()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//06.05.2015 ghh - now we'll take the array and marshal it back into a json\n\t//array to be returned to client\n\tif len(r) > 0 {\n\t\t//06.02.2013 naj - JSON Encode the response data.\n\t\tresp, err := json.Marshal(r)\n\n\t\tif err != nil {\n\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t_ = transaction.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t//10.04.2013 naj - commit the transaction\n\t\terr = transaction.Commit()\n\t\tif err != nil {\n\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t_ = transaction.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn resp, nil\n\t} else {\n\t\t//10.04.2013 naj - rollback transaction\n\t\t_ = transaction.Rollback()\n\t\treturn nil, errors.New(\"No valid parts were in the purchase order\")\n\t\t}\n\n}", "func (r *analyticsDeferredResultHandle) executeHandle(req *gocbcore.HttpRequest, valuePtr interface{}) error {\n\tresp, err := r.provider.DoHttpRequest(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjsonDec := json.NewDecoder(resp.Body)\n\terr = jsonDec.Decode(valuePtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\tlogDebugf(\"Failed to close socket (%s)\", err)\n\t}\n\n\treturn nil\n}", "func HandleRequest(query []byte, conn *DatabaseConnection) {\n\tlog.Printf(\"Handling raw query: %s\", query)\n\tlog.Printf(\"Parsing request...\")\n\trequest, err := grammar.ParseRequest(query)\n\tlog.Printf(\"Parsed request\")\n\tvar response grammar.Response\n\n\tif err != nil {\n\t\tlog.Printf(\"Error in request parsing! %s\", err.Error())\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_INVALID_QUERY\n\t\tresponse.Data = err.Error()\n\t\tconn.Write(grammar.GetBufferFromResponse(response))\n\t}\n\n\tswitch request.Type {\n\tcase grammar.AUTH_REQUEST:\n\t\t// AUTH {username} {password}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_AUTH_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in AUTH request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\t// bucketname := tokens[2]\n\t\tlog.Printf(\"Client wants to authenticate.<username>:<password> %s:%s\", username, password)\n\n\t\tauthRequest := AuthRequest{Username: username, Password: password, Conn: conn}\n\t\tresponse = processAuthRequest(authRequest)\n\tcase grammar.SET_REQUEST:\n\t\t// SET {key} {value} [ttl] [nooverride]\n\t\trequest.Type = grammar.SET_RESPONSE\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_SET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in SET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tvalue := request.RequestData[1]\n\t\tlog.Printf(\"Setting %s:%s\", key, value)\n\t\tsetRequest := SetRequest{Key: key, Value: value, Conn: conn}\n\t\tresponse = processSetRequest(setRequest)\n\n\tcase grammar.GET_REQUEST:\n\t\t// GET {key}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_GET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in GET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tlog.Printf(\"Client wants to get key '%s'\", key)\n\t\tgetRequest := GetRequest{Key: key, Conn: conn}\n\t\tresponse = processGetRequest(getRequest)\n\n\tcase grammar.DELETE_REQUEST:\n\t\t// DELETE {key}\n\t\tlog.Println(\"Client wants to delete a bucket/key\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_DELETE_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in DELETE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\t// TODO implement\n\tcase grammar.CREATE_BUCKET_REQUEST:\n\t\tlog.Println(\"Client wants to create a bucket\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_BUCKET_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE bucket request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketName := request.RequestData[0]\n\t\tcreateBucketRequest := CreateBucketRequest{BucketName: bucketName, Conn: conn}\n\n\t\tresponse = processCreateBucketRequest(createBucketRequest)\n\tcase grammar.CREATE_USER_REQUEST:\n\t\tlog.Printf(\"Client wants to create a user\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_USER_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE user request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\tcreateUserRequest := CreateUserRequest{Username: username, Password: password, Conn: conn}\n\n\t\tresponse = processCreateUserRequest(createUserRequest)\n\tcase grammar.USE_REQUEST:\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_USE_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in USE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketname := request.RequestData[0]\n\t\tif bucketname == SALTS_BUCKET || bucketname == USERS_BUCKET {\n\t\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNAUTHORIZED\n\t\t\tbreak\n\t\t}\n\n\t\tuseRequest := UseRequest{BucketName: bucketname, Conn: conn}\n\t\tresponse = processUseRequest(useRequest)\n\tdefault:\n\t\tlog.Printf(illegalRequestTemplate, request.Type)\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNKNOWN_COMMAND\n\t}\n\tif response.Status != 0 {\n\t\tlog.Printf(\"Error in request. status: %d\", response.Status)\n\t}\n\tconn.Write(grammar.GetBufferFromResponse(response))\n\tlog.Printf(\"Wrote buffer: %s to client\", grammar.GetBufferFromResponse(response))\n\n}", "func (q queryManager) processQueryWithSignature(txEncoded []byte, signature []byte, executeifallowed bool) (*structures.Transaction, error) {\n\ttx, err := structures.DeserializeTransaction(txEncoded)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tq.Logger.Trace.Printf(\"Complete SQL TX\")\n\terr = tx.CompleteTransaction(signature)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tq.Logger.Trace.Printf(\"Completed with ID: %x\", tx.GetID())\n\t// verify\n\t// TODO\n\n\tq.Logger.Trace.Printf(\"Adding TX to pool\")\n\t//return nil, errors.New(\"Temp err \")\n\t// add to pool\n\t// if fails , execute rollback ???\n\t// query wil be executed inside transactions manager before adding to a pool\n\terr = q.getTransactionsManager().ReceivedNewTransaction(tx, executeifallowed)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}", "func HandleGetPreparedQuery(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t_ = json.NewEncoder(w).Encode(map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)\n\t\tdefer cancel()\n\t\t// get project id and dbType from url\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\t\tdbAlias := \"\"\n\t\tdbAliasQuery, exists := r.URL.Query()[\"dbAlias\"]\n\t\tif exists {\n\t\t\tdbAlias = dbAliasQuery[0]\n\t\t}\n\t\tidQuery, exists := r.URL.Query()[\"id\"]\n\t\tid := \"\"\n\t\tif exists {\n\t\t\tid = idQuery[0]\n\t\t}\n\t\tresult, err := syncMan.GetPreparedQuery(ctx, projectID, dbAlias, id)\n\t\tif err != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t_ = json.NewEncoder(w).Encode(map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_ = json.NewEncoder(w).Encode(model.Response{Result: result})\n\t}\n}", "func HandlerMessage(aResponseWriter http.ResponseWriter, aRequest *http.Request) {\n\taRequest.ParseForm()\n\n\tbody := aRequest.Form\n\tlog.Printf(\"aRequest.Form=%s\", body)\n\tbytesBody, err := ioutil.ReadAll(aRequest.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading body, err=%s\", err.Error())\n\t}\n\t//\tlog.Printf(\"bytesBody=%s\", string(bytesBody))\n\n\t//check Header Token\n\t//\theaderAuthentication := aRequest.Header.Get(STR_Authorization)\n\t//\tisValid, userId := DbIsTokenValid(headerAuthentication, nil)\n\t//\tlog.Printf(\"HandlerMessage, headerAuthentication=%s, isValid=%t, userId=%d\", headerAuthentication, isValid, userId)\n\t//\tif !isValid {\n\t//\t\tresult := new(objects.Result)\n\t//\t\tresult.ErrorMessage = STR_MSG_login\n\t//\t\tresult.ResultCode = http.StatusOK\n\t//\t\tServeResult(aResponseWriter, result, STR_template_result)\n\t//\t\treturn\n\t//\t}\n\n\treport := new(objects.Report)\n\tjson.Unmarshal(bytesBody, report)\n\tlog.Printf(\"HandlerMessage, report.ApiKey=%s, report.ClientId=%s, report.Message=%s, report.Sequence=%d, report.Time=%d\",\n\t\treport.ApiKey, report.ClientId, report.Message, report.Sequence, report.Time)\n\tvar isApiKeyValid = false\n\tif report.ApiKey != STR_EMPTY {\n\t\tisApiKeyValid, _ = IsApiKeyValid(report.ApiKey)\n\t}\n\tif !isApiKeyValid {\n\t\tresult := new(objects.Result)\n\t\tresult.ErrorMessage = STR_MSG_invalidapikey\n\t\tresult.ResultCode = http.StatusOK\n\t\tServeResult(aResponseWriter, result, STR_template_result)\n\t\treturn\n\t}\n\n\tDbAddReport(report.ApiKey, report.ClientId, report.Time, report.Sequence, report.Message, report.FilePath, nil)\n\n\tresult := new(objects.Result)\n\tresult.ErrorMessage = STR_EMPTY\n\tresult.ResultCode = http.StatusOK\n\tServeResult(aResponseWriter, result, STR_template_result)\n}", "func (cm *commonMiddlware) traceDB(ctx context.Context) trace.Span {\n\tif cm.ot == nil {\n\t\treturn nil\n\t}\n\tif span := trace.SpanFromContext(ctx); span != nil {\n\t\t_, sp := cm.ot.Start(ctx, \"Postgres Database Call\")\n\t\treturn sp\n\t}\n\t_, sp := cm.ot.Start(ctx, \"Asynchronous Postgres Database Call\")\n\treturn sp\n}", "func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// Initiialize a connection to Sentry to capture errors and traces\n\tsentry.Init(sentry.ClientOptions{\n\t\tDsn: os.Getenv(\"SENTRY_DSN\"),\n\t\tTransport: &sentry.HTTPSyncTransport{\n\t\t\tTimeout: time.Second * 3,\n\t\t},\n\t\tServerName: os.Getenv(\"FUNCTION_NAME\"),\n\t\tRelease: os.Getenv(\"VERSION\"),\n\t\tEnvironment: os.Getenv(\"STAGE\"),\n\t})\n\n\t// Create headers if they don't exist and add\n\t// the CORS required headers, otherwise the response\n\t// will not be accepted by browsers.\n\theaders := request.Headers\n\tif headers == nil {\n\t\theaders = make(map[string]string)\n\t}\n\theaders[\"Access-Control-Allow-Origin\"] = \"*\"\n\n\t// Update the order with an OrderID\n\tord, err := acmeserverless.UnmarshalOrder(request.Body)\n\tif err != nil {\n\t\treturn handleError(\"unmarshal\", headers, err)\n\t}\n\tord.OrderID = uuid.Must(uuid.NewV4()).String()\n\n\tdynamoStore := dynamodb.New()\n\tord, err = dynamoStore.AddOrder(ord)\n\tif err != nil {\n\t\treturn handleError(\"store\", headers, err)\n\t}\n\n\tprEvent := acmeserverless.PaymentRequestedEvent{\n\t\tMetadata: acmeserverless.Metadata{\n\t\t\tDomain: acmeserverless.OrderDomain,\n\t\t\tSource: \"AddOrder\",\n\t\t\tType: acmeserverless.PaymentRequestedEventName,\n\t\t\tStatus: acmeserverless.DefaultSuccessStatus,\n\t\t},\n\t\tData: acmeserverless.PaymentRequestDetails{\n\t\t\tOrderID: ord.OrderID,\n\t\t\tCard: ord.Card,\n\t\t\tTotal: ord.Total,\n\t\t},\n\t}\n\n\t// Send a breadcrumb to Sentry with the payment request\n\tsentry.AddBreadcrumb(&sentry.Breadcrumb{\n\t\tCategory: acmeserverless.PaymentRequestedEventName,\n\t\tTimestamp: time.Now(),\n\t\tLevel: sentry.LevelInfo,\n\t\tData: acmeserverless.ToSentryMap(prEvent.Data),\n\t})\n\n\tem := sqs.New()\n\terr = em.SendPaymentRequestedEvent(prEvent)\n\tif err != nil {\n\t\treturn handleError(\"request payment\", headers, err)\n\t}\n\n\tstatus := acmeserverless.OrderStatus{\n\t\tOrderID: ord.OrderID,\n\t\tUserID: ord.UserID,\n\t\tPayment: acmeserverless.CreditCardValidationDetails{\n\t\t\tMessage: \"pending payment\",\n\t\t\tSuccess: false,\n\t\t},\n\t}\n\n\t// Send a breadcrumb to Sentry with the shipment request\n\tsentry.AddBreadcrumb(&sentry.Breadcrumb{\n\t\tCategory: acmeserverless.PaymentRequestedEventName,\n\t\tTimestamp: time.Now(),\n\t\tLevel: sentry.LevelInfo,\n\t\tData: acmeserverless.ToSentryMap(status.Payment),\n\t})\n\n\tpayload, err := status.Marshal()\n\tif err != nil {\n\t\treturn handleError(\"response\", headers, err)\n\t}\n\n\tresponse := events.APIGatewayProxyResponse{\n\t\tStatusCode: http.StatusOK,\n\t\tBody: string(payload),\n\t\tHeaders: headers,\n\t}\n\n\treturn response, nil\n}", "func (kvs *keyValueServer) handleRequest(req *Request) {\n\tvar request []string\n\trequest = kvs.parseRequest(req.input)\n\tif request[0] == \"get\" {\n\t\tclient := kvs.clienter[req.cid]\n\t\tkvs.getFromDB(request, client)\n\t}\n\tif request[0] == \"put\" {\n\t\tkvs.putIntoDB(request)\n\t}\n}", "func handleGetData(request []byte, bc *Blockchain) {\n\tvar buff bytes.Buffer\n\tvar payload getdata\n\n\tbuff.Write(request[commandLength:])\n\tdec := gob.NewDecoder(&buff)\n\terr := dec.Decode(&payload)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif payload.Type == \"block\" {\n\t\tblock, err := bc.GetBlock([]byte(payload.ID))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tsendBlock(payload.AddrFrom, &block)\n\t}\n\n\tif payload.Type == \"tx\" {\n\t\ttxID := hex.EncodeToString(payload.ID)\n\t\ttx := mempool[txID]\n\n\t\tsendTx(payload.AddrFrom, &tx)\n\t\t// delete(mempool, txID)\n\t}\n}", "func (app *JSONStoreApplication) DeliverTx(tx types.RequestDeliverTx) types.ResponseDeliverTx {\n\t return types.ResponseDeliverTx{Code: code.CodeTypeOK}\n\n\t var temp interface{}\n\t err := json.Unmarshal(tx.Tx, &temp)\n\n\t if err != nil {\n\t\t return types.ResponseDeliverTx{Code: code.CodeTypeEncodingError,Log: fmt.Sprint(err)}\n\t }\n\n\t message := temp.(map[string]interface{})\n\n\t PublicKey := message[\"publicKey\"].(string)\n\n\t count := checkUserPublic(db,PublicKey)\n \n\t if count != 0 {\n //var temp2 interface{}\n\t\t//userInfo := message[\"userInfo\"].(map[string]interface{})\n\t\t// err2 := json.Unmarshal([]byte(message[\"userInfo\"].(string)), &temp2)\n // message2 := temp2.(map[string]interface{})\n\t\t//if err2 != nil {\n\t\t//\tpanic(err.Error)\n\t\t//}\n \n\t\tvar user User\n\t\tuser.ID = message[\"id\"].(int)\n\t\tuser.PublicKey = message[\"public_key\"].(string)\n\t\tuser.Role = message[\"role\"].(int)\n\n\t\tfmt.Printf(user.PublicKey)\n \n\t\t// log.PrintIn(\"id: \", user.ID, \"public_key: \", user.PublicKey, \"role: \", user.Role)\n\n\t\tstmt, err := db.Prepare(\"INSERT INTO user(id, public_key, role) VALUES(?,?,?)\")\n\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\t\t\n\t\tstmt.Exec(user.ID, user.PublicKey, user.Role)\n\n\t\t// log.PrintIn(\"insert result: \", res.LastInsertId())\n\n\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeOK}\n\t } else {\n\t\treturn types.ResponseDeliverTx{Code: code.CodeTypeBadData}\n\t }\n\t \n\t// var types interface{}\n\t// errType := json.Unmarshall(message[\"types\"].(string), &types)\n\t \n\t// if errType != nil {\n\t// \t panic(err.Error)\n\t// }\n\n\t// switch types[\"types\"] {\n\t// \tcase \"createUser\":\n\t// \t\tentity := types[\"entity\"].(map[string]interface{})\n\n\t// \t\tvar user User\n\t// \t\tuser.ID = entity[\"id\"].(int)\n\t// \t\tuser.PublicKey = entity[\"publicKey\"].(string)\n\t// \t\tuser.Role = entity[\"role\"].(int)\n\t// }\n}", "func Deposito(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"Application-json\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tdefer r.Body.Close()\n\tdeposit := models.Transaccion{}\n\n\tjson.NewDecoder(r.Body).Decode(&deposit)\n\tlog.Println(deposit)\n\n\ttsql := fmt.Sprintf(\"exec SP_DEPOSITO '%d', '%s', %f\", deposit.NoCuenta, deposit.TipoTran, deposit.Monto)\n\tQuery, err := db.Query(tsql)\n\n\tif err == nil {\n\t\tnotification := models.Notification{\n\t\t\tNoCuenta: deposit.NoCuenta,\n\t\t\tMonto: deposit.Monto,\n\t\t\tRazon: \"Transaccion realizada exitosamente\",\n\t\t\tStatus: true,\n\t\t}\n\n\t\tjsonresult, _ := json.Marshal(notification)\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write(jsonresult)\n\t\treturn\n\t}\n\n\tif err.Error() == help.ErrorCuentaNotFound {\n\t\tnotification := models.Notification{\n\t\t\tNoCuenta: deposit.NoCuenta,\n\t\t\tMonto: deposit.Monto,\n\t\t\tRazon: \"El numero de cuenta proporcionado no es válido\",\n\t\t\tStatus: false,\n\t\t}\n\n\t\tjsonresult, _ := json.Marshal(notification)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write(jsonresult)\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tlog.Println(\"+++ Error no controlado: \", err.Error(), \"+++\")\n\t\treturn\n\t}\n\n\tdefer Query.Close()\n}", "func (p *Proxy) handleShowCreateDatabase(session *driver.Session, query string, node sqlparser.Statement) (*sqltypes.Result, error) {\n\treturn p.ExecuteSingle(query)\n}", "func paymentCreate(service payment.UseCase) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer r.Body.Close()\n\t\tvar p *entity.Payment\n\t\terr := json.NewDecoder(r.Body).Decode(&p)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request payload\")\n\t\t\treturn\n\t\t}\n\t\tp.ID, err = service.Store(p)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\trespondWithJSON(w, http.StatusCreated, p)\n\t})\n}", "func (_obj *Apipayments) Payments_getPaymentForm(params *TLpayments_getPaymentForm, _opt ...map[string]string) (ret Payments_PaymentForm, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"payments_getPaymentForm\", _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 = ret.ReadBlock(_is, 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 (p *pbft) handleCommit(content []byte) {\n\t//The Request structure is parsed using JSON\n\tc := new(Commit)\n\terr := json.Unmarshal(content, c)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Printf(\"This node has received Commit message from %s. \\n\", c.NodeID)\n\t\n\tMessageNodePubKey := p.getPubKey(c.NodeID)\n\tdigestByte, _ := hex.DecodeString(c.Digest)\n\tif _, ok := p.prePareConfirmCount[c.Digest]; !ok {\n\t\tfmt.Println(\"The current temporary message pool does not have this digest. Deny storing into local message pool.\")\n\t} else if p.sequenceID != c.SequenceID {\n\t\tfmt.Println(\"ID is not correct. Deny storing into local message pool.\")\n\t} else if !p.RsaVerySignWithSha256(digestByte, c.Sign, MessageNodePubKey) {\n\t\tfmt.Println(\"The signiture is not valid! Deny storing into local message pool.\")\n\t} else {\n\t\tp.setCommitConfirmMap(c.Digest, c.NodeID, true) \n\t\tcount := 0\n\t\tfor range p.commitConfirmCount[c.Digest] {\n\t\t\tcount++\n\t\t}\n\t\t\n\t\tp.lock.Lock()\n\t\tif count >= nodeCount/3*2 && !p.isReply[c.Digest] && p.isCommitBordcast[c.Digest] {\n\t\t\tfmt.Println(\"This node has received at least 2f+1 (including itself) Commit messages.\")\n\t\t\t\n\t\t\tlocalMessagePool = append(localMessagePool, p.messagePool[c.Digest].Message)\n\t\t\tinfo := p.node.nodeID + \" has stored the message with msgid:\" + strconv.Itoa(p.messagePool[c.Digest].ID) + \" into the local message pool successfully. The message is \" + p.messagePool[c.Digest].Content\n\t\t\t\n\t\t\tfmt.Println(info)\n\t\t\tfmt.Println(\"sending Reply message to the client ...\")\n\t\t\ttcpDial([]byte(info), p.messagePool[c.Digest].ClientAddr)\n\t\t\tp.isReply[c.Digest] = true\n\t\t\tfmt.Println(\"Reply is done.\")\n\t\t}\n\t\tp.lock.Unlock()\n\t}\n}", "func (p *pbft) handlePrepare(content []byte) {\n\t//The Request structure is parsed using JSON\n\tpre := new(Prepare)\n\terr := json.Unmarshal(content, pre)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Printf(\"This node has received the Prepare message from %s ... \\n\", pre.NodeID)\n\t//\n\tMessageNodePubKey := p.getPubKey(pre.NodeID)\n\tdigestByte, _ := hex.DecodeString(pre.Digest)\n\tif _, ok := p.messagePool[pre.Digest]; !ok {\n\t\tfmt.Println(\"The current temporary message pool does not have this digest. Deny sending Commit message.\")\n\t} else if p.sequenceID != pre.SequenceID {\n\t\tfmt.Println(\"ID is not correct. Deny sending Commit message.\")\n\t} else if !p.RsaVerySignWithSha256(digestByte, pre.Sign, MessageNodePubKey) {\n\t\tfmt.Println(\"The signiture is not valid! Deny sending Commit message.\")\n\t} else {\n\t\tp.setPrePareConfirmMap(pre.Digest, pre.NodeID, true)\n\t\tcount := 0\n\t\tfor range p.prePareConfirmCount[pre.Digest] {\n\t\t\tcount++\n\t\t}\n\t\t//Since the primary node does not send Prepare message, so it does not include itself.\n\t\tspecifiedCount := 0\n\t\tif p.node.nodeID == \"N0\" {\n\t\t\tspecifiedCount = nodeCount / 3 * 2\n\t\t} else {\n\t\t\tspecifiedCount = (nodeCount / 3 * 2) - 1\n\t\t}\n\t\t\n\t\tp.lock.Lock()\n\t\t\n\t\tif count >= specifiedCount && !p.isCommitBordcast[pre.Digest] {\n\t\t\tfmt.Println(\"This node has received at least 2f (including itself) Prepare messages.\")\n\t\t\t\n\t\t\tsign := p.RsaSignWithSha256(digestByte, p.node.rsaPrivKey)\n\t\t\tc := Commit{pre.Digest, pre.SequenceID, p.node.nodeID, sign}\n\t\t\tbc, err := json.Marshal(c)\n\t\t\tif err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t\t\n\t\t\tfmt.Println(\"sending Commit message to other nodes...\")\n\t\t\tp.broadcast(cCommit, bc)\n\t\t\tp.isCommitBordcast[pre.Digest] = true\n\t\t\tfmt.Println(\"Commit is done.\")\n\t\t}\n\t\tp.lock.Unlock()\n\t}\n}", "func (api *Api) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\thandler(api.DB, w, r)\n\t}\n}", "func (pm *DPoSProtocolManager) handleMsg(msg *p2p.Msg, p *peer) error {\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\t// Handle the message depending on its contents\n\tswitch {\n\tcase msg.Code == SYNC_BIGPERIOD_REQUEST:\n\t\tvar request SyncBigPeriodRequest;\n\t\tif err := msg.Decode(&request); err != nil {\n\t\t\treturn errResp(DPOSErrDecode, \"%v: %v\", msg, err);\n\t\t}\n\t\tif SignCandidates(request.DelegatedTable) != request.DelegatedTableSign {\n\t\t\treturn errResp(DPOSErroDelegatorSign, \"\");\n\t\t}\n\t\tif DelegatorsTable == nil || len(DelegatorsTable) == 0 {\n\t\t\t// i am not ready.\n\t\t\tlog.Info(\"I am not ready!!!\")\n\t\t\treturn nil;\n\t\t}\n\t\tif request.Round == NextGigPeriodInstance.round {\n\t\t\tif NextGigPeriodInstance.state == STATE_CONFIRMED {\n\t\t\t\tlog.Debug(fmt.Sprintf(\"I am in the agreed round %v\", NextGigPeriodInstance.round));\n\t\t\t\t// if i have already confirmed this round. send this round to peer.\n\t\t\t\tif TestMode {\n\t\t\t\t\treturn nil;\n\t\t\t\t}\n\t\t\t\treturn p.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\t\tSTATE_CONFIRMED,\n\t\t\t\t\tcurrNodeIdHash});\n\t\t\t} else {\n\t\t\t\tif !reflect.DeepEqual(DelegatorsTable, request.DelegatedTable) {\n\t\t\t\t\tif len(DelegatorsTable) < len(request.DelegatedTable) {\n\t\t\t\t\t\t// refresh table if mismatch.\n\t\t\t\t\t\tDelegatorsTable, DelegatorNodeInfo, _ = VotingAccessor.Refresh()\n\t\t\t\t\t}\n\t\t\t\t\tif !reflect.DeepEqual(DelegatorsTable, request.DelegatedTable) {\n\t\t\t\t\t\tlog.Debug(\"Delegators are mismatched in two tables.\");\n\t\t\t\t\t\tif TestMode {\n\t\t\t\t\t\t\treturn nil;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// both delegators are not matched, both lose the election power of this round.\n\t\t\t\t\t\treturn p.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\t\t\t\tSTATE_MISMATCHED_DNUMBER,\n\t\t\t\t\t\t\tcurrNodeIdHash});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tNextGigPeriodInstance.state = STATE_CONFIRMED;\n\t\t\t\tNextGigPeriodInstance.delegatedNodes = request.DelegatedTable;\n\t\t\t\tNextGigPeriodInstance.delegatedNodesSign = request.DelegatedTableSign;\n\t\t\t\tNextGigPeriodInstance.activeTime = request.ActiveTime;\n\n\t\t\t\tpm.setNextRoundTimer();//sync the timer.\n\t\t\t\tlog.Debug(fmt.Sprintf(\"Agreed this table %v as %v round\", NextGigPeriodInstance.delegatedNodes, NextGigPeriodInstance.round));\n\t\t\t\tif TestMode {\n\t\t\t\t\treturn nil;\n\t\t\t\t}\n\t\t\t\t// broadcast it to all peers again.\n\t\t\t\tfor _, peer := range pm.ethManager.peers.peers {\n\t\t\t\t\terr := peer.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\t\t\tSTATE_CONFIRMED,\n\t\t\t\t\t\tcurrNodeIdHash})\n\t\t\t\t\tif (err != nil) {\n\t\t\t\t\t\tlog.Warn(\"Error occurred while sending VoteElectionRequest: \" + err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if request.Round < NextGigPeriodInstance.round {\n\t\t\tlog.Debug(fmt.Sprintf(\"Mismatched request.round %v, CurrRound %v: \", request.Round, NextGigPeriodInstance.round))\n\t\t\tif TestMode {\n\t\t\t\treturn nil;\n\t\t\t}\n\t\t\treturn p.SendSyncBigPeriodResponse(&SyncBigPeriodResponse{\n\t\t\t\tNextGigPeriodInstance.round,\n\t\t\t\tNextGigPeriodInstance.activeTime,\n\t\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\t\tSTATE_MISMATCHED_ROUND,\n\t\t\t\tcurrNodeIdHash});\n\t\t} else if request.Round > NextGigPeriodInstance.round {\n\t\t\tif (request.Round - NextElectionInfo.round) == 1 {\n\t\t\t\t// the most reason could be the round timeframe switching later than this request.\n\t\t\t\t// but we are continue switching as regular.\n\t\t\t} else {\n\t\t\t\t// attack happens.\n\t\t\t}\n\t\t}\n\tcase msg.Code == SYNC_BIGPERIOD_RESPONSE:\n\t\tvar response SyncBigPeriodResponse;\n\t\tif err := msg.Decode(&response); err != nil {\n\t\t\treturn errResp(DPOSErrDecode, \"%v: %v\", msg, err);\n\t\t}\n\t\tif response.Round != NextGigPeriodInstance.round {\n\t\t\treturn nil;\n\t\t}\n\t\tif SignCandidates(response.DelegatedTable) != response.DelegatedTableSign {\n\t\t\treturn errResp(DPOSErroDelegatorSign, \"\");\n\t\t}\n\t\tnodeId := common.Bytes2Hex(response.NodeId)\n\t\tlog.Debug(\"Received SYNC Big Period response: \" + nodeId);\n\t\tNextGigPeriodInstance.confirmedTickets[nodeId] ++;\n\t\tNextGigPeriodInstance.confirmedBestNode[nodeId] = &GigPeriodTable{\n\t\t\tresponse.Round,\n\t\t\tSTATE_CONFIRMED,\n\t\t\tresponse.DelegatedTable,\n\t\t\tresponse.DelegatedTableSign,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tresponse.ActiveTime,\n\t\t};\n\n\t\tmaxTickets, bestNodeId := uint32(0), \"\";\n\t\tfor key, value := range NextGigPeriodInstance.confirmedTickets {\n\t\t\tif maxTickets < value {\n\t\t\t\tmaxTickets = value;\n\t\t\t\tbestNodeId = key;\n\t\t\t}\n\t\t}\n\t\tif NextGigPeriodInstance.state == STATE_CONFIRMED {\n\t\t\t// set the best node as the final state.\n\t\t\tbestNode := NextGigPeriodInstance.confirmedBestNode[bestNodeId];\n\t\t\tNextGigPeriodInstance.delegatedNodes = bestNode.delegatedNodes;\n\t\t\tNextGigPeriodInstance.delegatedNodesSign = bestNode.delegatedNodesSign;\n\t\t\tNextGigPeriodInstance.activeTime = bestNode.activeTime;\n\t\t\tlog.Debug(fmt.Sprintf(\"Updated the best table: %v\", bestNode.delegatedNodes));\n\t\t\tpm.setNextRoundTimer();\n\t\t} else if NextGigPeriodInstance.state == STATE_LOOKING && uint32(NextGigPeriodInstance.confirmedTickets[bestNodeId]) > uint32(len(NextGigPeriodInstance.delegatedNodes)) {\n\t\t\tNextGigPeriodInstance.state = STATE_CONFIRMED;\n\t\t\tNextGigPeriodInstance.delegatedNodes = response.DelegatedTable;\n\t\t\tNextGigPeriodInstance.delegatedNodesSign = response.DelegatedTableSign;\n\t\t\tNextGigPeriodInstance.activeTime = response.ActiveTime;\n\n\t\t\tpm.setNextRoundTimer();\n\t\t} else if response.State == STATE_MISMATCHED_ROUND {\n\t\t\t// force to create new round\n\t\t\tNextGigPeriodInstance = &GigPeriodTable{\n\t\t\t\tresponse.Round,\n\t\t\t\tSTATE_LOOKING,\n\t\t\t\tresponse.DelegatedTable,\n\t\t\t\tresponse.DelegatedTableSign,\n\t\t\t\tmake(map[string]uint32),\n\t\t\t\tmake(map[string]*GigPeriodTable),\n\t\t\t\tresponse.ActiveTime,\n\t\t\t};\n\t\t\tpm.trySyncAllDelegators()\n\t\t} else if response.State == STATE_MISMATCHED_DNUMBER {\n\t\t\t// refresh table only, and this node loses the election power of this round.\n\t\t\tDelegatorsTable, DelegatorNodeInfo, _ = VotingAccessor.Refresh()\n\t\t}\n\t\treturn nil;\n\tdefault:\n\t\treturn errResp(ErrInvalidMsgCode, \"%v\", msg.Code)\n\t}\n\treturn nil\n}", "func (p *pbft) handleClientRequest(content []byte) {\n\tfmt.Println(\"The primary node has received the request from the client.\")\n\t//The Request structure is parsed using JSON\n\tr := new(Request)\n\terr := json.Unmarshal(content, r)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t//to add infoID\n\tp.sequenceIDAdd()\n\t//to get the digest\n\tdigest := getDigest(*r)\n\tfmt.Println(\"The request has been stored into the temporary message pool.\")\n\t//to store into the temp message pool\n\tp.messagePool[digest] = *r\n\t//to sign the digest by the primary node\n\tdigestByte, _ := hex.DecodeString(digest)\n\tsignInfo := p.RsaSignWithSha256(digestByte, p.node.rsaPrivKey)\n\t//setup PrePrepare message and send to other nodes\n\tpp := PrePrepare{*r, digest, p.sequenceID, signInfo}\n\tb, err := json.Marshal(pp)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Println(\"sending PrePrepare messsage to all the other nodes...\")\n\t//to send PrePrepare message to other nodes\n\tp.broadcast(cPrePrepare, b)\n\tfmt.Println(\"PrePrepare is done.\")\n}", "func generateHandler(db *sqlx.DB, mongodb *mongo.Database) func(w http.ResponseWriter, r *http.Request) {\n\t// prepare once in the beginning.\n\tloc, err := time.LoadLocation(\"Australia/Brisbane\")\n\tif err != nil {\n\t\tlog.Errorln(err)\n\t}\n\n\treturn (func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// req params\n\t\tpage := r.FormValue(\"page\")\n\t\tperPage := r.FormValue(\"per_page\")\n\t\tfilter := r.FormValue(\"filter\")\n\t\tstartDate := r.FormValue(\"start_date\")\n\t\tendDate := r.FormValue(\"end_date\")\n\n\t\toffset, pageInt, perPageInt := 0, 0, 10\n\t\tvar err error\n\t\tif page != \"\" && perPage != \"\" {\n\t\t\tpageInt, err = strconv.Atoi(page)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\t\t\tperPageInt, err = strconv.Atoi(perPage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\t\t\toffset = (pageInt - 1) * perPageInt\n\t\t}\n\t\tlog.Infoln(page, perPage, offset)\n\n\t\tvar filters []string\n\t\tvar args []interface{}\n\t\tidx := 1 // query placeholder for $n; to prevent sql injection.\n\t\tif filter != \"\" {\n\t\t\tfilters = append(filters, fmt.Sprintf(\"order_name ilike $%d\", idx))\n\t\t\targs = append(args, \"%\"+filter+\"%\")\n\t\t\tidx++\n\t\t}\n\t\tif startDate != \"\" {\n\t\t\tfilters = append(filters, fmt.Sprintf(\"DATE(created_at) >= $%d\", idx))\n\t\t\targs = append(args, startDate)\n\t\t\tidx++\n\t\t}\n\t\tif endDate != \"\" {\n\t\t\tfilters = append(filters, fmt.Sprintf(\"DATE(created_at) <= $%d\", idx))\n\t\t\targs = append(args, endDate)\n\t\t\tidx++\n\t\t}\n\n\t\t// TODO: use prepared statement.\n\t\tquery, where := buildQuery(filters, idx)\n\t\tlog.Infoln(query)\n\n\t\tvar orders []Order\n\t\terr = db.Select(&orders, query, append(args, perPage, offset)...)\n\t\tif err != nil {\n\t\t\tlog.Errorln(err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t// count query; use count(1) for efficiency.\n\t\tquery = \"select count(1) from orders \" + where\n\t\tlog.Infoln(query)\n\n\t\tvar total int\n\t\terr = db.Get(&total, query, args...)\n\t\tif err != nil {\n\t\t\tlog.Errorln(err)\n\t\t}\n\t\tlastPage := total / perPageInt\n\n\t\tcustomerColl := mongodb.Collection(\"customers\")\n\t\tcompaniesColl := mongodb.Collection(\"customer_companies\")\n\n\t\tvar data []Order\n\t\tfor _, o := range orders {\n\t\t\tlog.Infoln(o)\n\n\t\t\tvar customer Customer\n\t\t\tfilterCustomer := bson.D{{\"user_id\", o.CustomerID}}\n\t\t\terr = customerColl.FindOne(context.TODO(), filterCustomer).Decode(&customer)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\n\t\t\tvar company Company\n\t\t\tfilterCompany := bson.D{{\"company_id\", customer.CompanyID}}\n\t\t\terr = companiesColl.FindOne(context.TODO(), filterCompany).Decode(&company)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\n\t\t\tparsedTime, err := time.Parse(layoutFrom, o.OrderDate)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\n\t\t\to.CustomerCompany = company.CompanyName\n\t\t\to.CustomerName = customer.Name\n\t\t\to.OrderDate = parsedTime.In(loc).Format(layoutTo)\n\t\t\to.TotalAmountStr = fmt.Sprintf(\"$%.2f\", o.TotalAmount)\n\n\t\t\to.DeliveredAmountStr = \"-\"\n\t\t\tif o.DeliveredAmount > 0 {\n\t\t\t\to.DeliveredAmountStr = fmt.Sprintf(\"$%.2f\", o.DeliveredAmount)\n\t\t\t}\n\n\t\t\tdata = append(data, o)\n\t\t}\n\n\t\tresp := HTTPResponse{\n\t\t\tCurrentPage: pageInt,\n\t\t\tTotal: total,\n\t\t\tFrom: offset + 1,\n\t\t\tTo: offset + perPageInt,\n\t\t\tPerPage: perPageInt,\n\t\t\tLastPage: lastPage,\n\t\t\tData: data,\n\t\t}\n\n\t\t// TODO: move to separate config file.\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"http://localhost:8080\")\n\t\tencoded, err := json.Marshal(resp)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t_, err = w.Write(encoded)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t})\n}", "func (r *relay) handleRequest(reqId uint64, req []byte) {\n\trep := r.handler.HandleRequest(req)\n\tif err := r.sendReply(reqId, rep); err != nil {\n\t\tlog.Printf(\"iris: failed to send reply: %v.\", err)\n\t}\n}", "func (d *deliveryRepository) handlePendingApprovalToProposed(tx *gorm.DB, p *delivery.RequestUpdateDelivery) error {\n\tbalanceCheck, err := d.getBalanceCheck(tx, p)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tif balanceCheck.ServiceFee > balanceCheck.CoinAmount {\n\t\treturn errors.New(\"insufficient service_fee\")\n\t}\n\n\t// Add credit to coin transaction to admin\n\tvar adminId int\n\terr = tx.Raw(`\n\t\tSELECT \n\t\t\tu.id\n\t\tFROM ` + utils.EncloseString(\"user\", \"`\") + ` u\n\t\tWHERE 1 = 1\n\t\t\tAND u.email = (\n\t\t\t\tSELECT\n\t\t\t\t\t` + utils.EncloseString(\"value\", \"`\") + `\t\n\t\t\t\tFROM sysparam\n\t\t\t\tWHERE 1 = 1\n\t\t\t\t\tAND ` + utils.EncloseString(\"key\", \"`\") + ` = \"HANDLER_ADMIN\"\n\t\t\t)\n\t`).Scan(&adminId).Error\n\n\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\treturn errors.New(\"HANDLER_ADMIN not found\")\n\t}\n\tif err != nil {\n\t\treturn errors.New(\"error trying to fetch the HANDLER_ADMIN\")\n\t}\n\n\t// Add seller coin transaction\n\terr = d.addCoinTransaction(\n\t\ttx,\n\t\tadminId,\n\t\tbalanceCheck.SellerId,\n\t\t\"D\",\n\t\tbalanceCheck.ServiceFee,\n\t\tp.DeliveryId,\n\t)\n\tif err != nil {\n\t\treturn errors.New(\"error adding a new coin transaction for the seller: \" + err.Error())\n\t}\n\n\t// Add admin coin transaction\n\terr = d.addCoinTransaction(\n\t\ttx,\n\t\tadminId,\n\t\tadminId,\n\t\t\"D\",\n\t\tbalanceCheck.ServiceFee,\n\t\tp.DeliveryId,\n\t)\n\tif err != nil {\n\t\treturn errors.New(\"error adding a new coin transaction for the admin: \" + err.Error())\n\t}\n\n\t// Update totals seller\n\terr = d.updateCoinTotals(tx, adminId, balanceCheck.SellerId, balanceCheck.ServiceFee*-1)\n\tif err != nil {\n\t\treturn errors.New(\"error updating coin transaction for seller: \" + err.Error())\n\t}\n\n\t// Update totals admin\n\terr = d.updateCoinTotals(tx, adminId, adminId, balanceCheck.ServiceFee)\n\tif err != nil {\n\t\treturn errors.New(\"error updating coin transaction for seller: \" + err.Error())\n\t}\n\n\t// Also, update information of depending\n\t/**\n\tPolicyNumber\n\tName\n\tContactNo\n\tNote\n\tAddress\n\tDescription\n\t*/\n\n\thasLastMinuteUpdates := false\n\n\tif p.PolicyNumber != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.Name != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.ContactNo != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.Note != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.Address != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\tif p.ItemDescription != \"\" {\n\t\thasLastMinuteUpdates = true\n\t}\n\n\tif hasLastMinuteUpdates {\n\t\t// Do update\n\t\tsqlLastMinuteUpdate := `\n\t\t\tUPDATE delivery\n\t\t\t\tSET policy_number = ` + utils.GetSQLValue(\"policy_number\", p.PolicyNumber) + `,\n\t\t\t\t\tname = ` + utils.GetSQLValue(\"name\", p.Name) + `,\n\t\t\t\t\tcontact_number = ` + utils.GetSQLValue(\"contact_number\", p.ContactNo) + `,\n\t\t\t\t\tnote = ` + utils.GetSQLValue(\"note\", p.Note) + `,\n\t\t\t\t\taddress = ` + utils.GetSQLValue(\"address\", p.Address) + `,\n\t\t\t\t\titem_description = ` + utils.GetSQLValue(\"item_description\", p.ItemDescription) + `\n\t\t\tWHERE id = ?\n\t\t`\n\t\terr = tx.Exec(sqlLastMinuteUpdate, p.DeliveryId).Error\n\t\tif err != nil {\n\t\t\treturn errors.New(\"error executing last minute updates before moving delivery to 'Proposed': \" + err.Error())\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Has no last minute updates\")\n\t}\n\n\treturn nil\n}", "func (trd *trxDispatcher) process(evt *eventTrx) {\n\t// send the transaction out for burns processing\n\tselect {\n\tcase trd.outTransaction <- evt:\n\tcase <-trd.sigStop:\n\t\treturn\n\t}\n\n\t// process transaction accounts; exit if terminated\n\tvar wg sync.WaitGroup\n\tif !trd.pushAccounts(evt, &wg) {\n\t\treturn\n\t}\n\n\t// process transaction logs; exit if terminated\n\tfor _, lg := range evt.trx.Logs {\n\t\tif !trd.pushLog(lg, evt.blk, evt.trx, &wg) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// store the transaction into the database once the processing is done\n\t// we spawn a lot of go-routines here, so we should test the optimal queue length above\n\tgo trd.waitAndStore(evt, &wg)\n\n\t// broadcast new transaction; if it can not be broadcast quickly, skip\n\tselect {\n\tcase trd.onTransaction <- evt.trx:\n\tcase <-time.After(200 * time.Millisecond):\n\tcase <-trd.sigStop:\n\t}\n}", "func (d *Dao) doHTTPRequest(c context.Context, uri, ip string, params url.Values, res interface{}) (err error) {\n\tenc, err := d.sign(params)\n\tif err != nil {\n\t\terr = pkgerr.Wrapf(err, \"uri:%s,params:%v\", uri, params)\n\t\treturn\n\t}\n\tif enc != \"\" {\n\t\turi = uri + \"?\" + enc\n\t}\n\n\treq, err := xhttp.NewRequest(xhttp.MethodGet, uri, nil)\n\tif err != nil {\n\t\terr = pkgerr.Wrapf(err, \"method:%s,uri:%s\", xhttp.MethodGet, uri)\n\t\treturn\n\t}\n\treq.Header.Set(_userAgent, \"changxuanran@bilibili.com \"+env.AppID)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn d.client.Do(c, req, res)\n}", "func PurchasedRewardsAPIHandler(response http.ResponseWriter, request *http.Request) {\n\tt := time.Now()\n\tlogRequest := t.Format(\"2006/01/02 15:04:05\") + \" | Request:\" + request.Method + \" | Endpoint: purchasedrewards | \" //Connect to database\n\tfmt.Println(logRequest)\n\tdb, e := sql.Open(\"mysql\", dbConnectionURL)\n\tif e != nil {\n\t\tfmt.Print(e)\n\t}\n\n\t//set mime type to JSON\n\tresponse.Header().Set(\"Content-type\", \"application/json\")\n\n\terr := request.ParseForm()\n\tif err != nil {\n\t\thttp.Error(response, fmt.Sprintf(\"error parsing url %v\", err), 500)\n\t}\n\n\t//can't define dynamic slice in golang\n\tvar result = make([]string, 1000)\n\n\tswitch request.Method {\n\tcase GET:\n\t\tGroupId := strings.Replace(request.URL.Path, \"/api/purchasedrewards/\", \"\", -1)\n\n\t\t//fmt.Println(GroupId)\n\t\tst, getErr := db.Prepare(\"select * from PurchasedRewards where GroupId=?\")\n\t\tif err != nil {\n\t\t\tfmt.Print(getErr)\n\t\t}\n\t\trows, getErr := st.Query(GroupId)\n\t\tif getErr != nil {\n\t\t\tfmt.Print(getErr)\n\t\t}\n\t\ti := 0\n\t\tfor rows.Next() {\n\t\t\tvar RequestId int\n\t\t\tvar GroupId int\n\t\t\tvar RewardName string\n\t\t\tvar PointCost int\n\t\t\tvar RewardDescription string\n\t\t\tvar RewardedUser string\n\n\t\t\tgetErr := rows.Scan(&RequestId, &GroupId, &RewardName, &PointCost, &RewardDescription, &RewardedUser)\n\t\t\treward := &PurchasedReward{RequestId: RequestId, GroupId: GroupId, RewardName: RewardName, PointCost: PointCost, RewardDescription: RewardDescription, RewardedUser: RewardedUser}\n\t\t\tb, getErr := json.Marshal(reward)\n\t\t\tif getErr != nil {\n\t\t\t\tfmt.Println(getErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresult[i] = fmt.Sprintf(\"%s\", string(b))\n\t\t\ti++\n\t\t}\n\t\tresult = result[:i]\n\n\tcase POST:\n\n\t\tGroupId := request.PostFormValue(\"GroupId\")\n\t\tRewardName := request.PostFormValue(\"RewardName\")\n\t\tPointCost := request.PostFormValue(\"PointCost\")\n\t\tRewardDescription := request.PostFormValue(\"RewardDescription\")\n\t\tRewardedUser := request.PostFormValue(\"RewardedUser\")\n\n\t\tvar UserBalance int\n\t\tuserBalanceQueryErr := db.QueryRow(\"SELECT TotalPoints FROM `Points` WHERE `EmailAddress`=? AND `GroupId`=?\", RewardedUser, GroupId).Scan(&UserBalance)\n\t\tswitch {\n\t\tcase userBalanceQueryErr == sql.ErrNoRows:\n\t\t\tlog.Printf(logRequest, \"Unable to find user and group: \\n\", RewardedUser, GroupId)\n\t\tcase userBalanceQueryErr != nil:\n\t\t\tlog.Fatal(userBalanceQueryErr)\n\t\tdefault:\n\t\t}\n\t\tcostInt, err := strconv.Atoi(PointCost)\n\t\tif UserBalance > costInt {\n\t\t\t// Update user's points\n\t\t\tUserBalance -= costInt\n\n\t\t\t// Update database row\n\t\t\tstBalanceUpdate, postBalanceUpdateErr := db.Prepare(\"UPDATE Points SET `totalpoints`=?, `emailaddress`=? WHERE `groupid`=?\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Print(err)\n\t\t\t}\n\t\t\tresBalanceUpdate, postBalanceUpdateErr := stBalanceUpdate.Exec(UserBalance, RewardedUser, GroupId)\n\t\t\tif postBalanceUpdateErr != nil {\n\t\t\t\tfmt.Print(postBalanceUpdateErr)\n\t\t\t}\n\t\t\tif resBalanceUpdate != nil {\n\t\t\t\tresult[0] = \"Points Subtracted\"\n\t\t\t}\n\t\t\tresult = result[:1]\n\n\t\t\t// Add purchase to record\n\t\t\tstPurchase, postPurchaseErr := db.Prepare(\"INSERT INTO PurchasedRewards(`requestid`, `groupid`, `rewardname`, `pointcost`, `rewarddescription`, `rewardeduser`) VALUES(NULL,?,?,?,?,?)\")\n\t\t\tif postPurchaseErr != nil {\n\t\t\t\tfmt.Print(postPurchaseErr)\n\t\t\t}\n\t\t\tresPurchase, postPurchaseErr := stPurchase.Exec(GroupId, RewardName, PointCost, RewardDescription, RewardedUser)\n\t\t\tif postPurchaseErr != nil {\n\t\t\t\tfmt.Print(postPurchaseErr)\n\t\t\t}\n\n\t\t\tif resPurchase != nil {\n\t\t\t\tresult[0] = \"Purchase Added\"\n\t\t\t}\n\n\t\t\tresult = result[:1]\n\t\t} else {\n\t\t\tresult[0] = \"Purchase Rejected\"\n\t\t\tresult = result[:1]\n\t\t}\n\n\tcase PUT:\n\t\tRequestId := request.PostFormValue(\"RequestId\")\n\t\tGroupId := request.PostFormValue(\"GroupId\")\n\t\tRewardName := request.PostFormValue(\"RewardName\")\n\t\tPointCost := request.PostFormValue(\"PointCost\")\n\t\tRewardDescription := request.PostFormValue(\"RewardDescription\")\n\t\tRewardedUser := request.PostFormValue(\"RewardedUser\")\n\n\t\tst, putErr := db.Prepare(\"UPDATE PurchasedRewards SET GroupId=?, RewardName=?, PointCost=?, RewardDescription=?, RewardedUser=? WHERE RequestId=?\")\n\t\tif err != nil {\n\t\t\tfmt.Print(putErr)\n\t\t}\n\t\tres, putErr := st.Exec(GroupId, RewardName, PointCost, RewardDescription, RewardedUser, RequestId)\n\t\tif putErr != nil {\n\t\t\tfmt.Print(putErr)\n\t\t}\n\n\t\tif res != nil {\n\t\t\tresult[0] = \"Reward Modified\"\n\t\t}\n\t\tresult = result[:1]\n\n\tcase DELETE:\n\t\tRequestId := strings.Replace(request.URL.Path, \"/api/purchasedrewards/\", \"\", -1)\n\t\tst, deleteErr := db.Prepare(\"DELETE FROM PurchasedRewards where RequestId=?\")\n\t\tif deleteErr != nil {\n\t\t\tfmt.Print(deleteErr)\n\t\t}\n\t\tres, deleteErr := st.Exec(RequestId)\n\t\tif deleteErr != nil {\n\t\t\tfmt.Print(deleteErr)\n\t\t}\n\n\t\tif res != nil {\n\t\t\tresult[0] = \"Reward Deleted\"\n\t\t}\n\t\tresult = result[:1]\n\n\tdefault:\n\t}\n\n\tjson, err := json.Marshal(result)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t// Send the text diagnostics to the client. Clean backslashes from json\n\tfmt.Fprintf(response, \"%v\", CleanJSON(string(json)))\n\t//fmt.Fprintf(response, \" request.URL.Path '%v'\\n\", request.Method)\n\tdb.Close()\n}", "func updatePaymentByID(c *gin.Context) {\n\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"updatePaymentByID\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tvar p storage.Payments\n\terr = c.BindJSON(&p)\n\n\terr = paymentsDB.UpdatePayment(c.Param(\"id\"), &p)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": \"error\", \"message\": \"Could not update the payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"success\", \"message\": \"Payment updated\"})\n\n}", "func createOrderHandle(response http.ResponseWriter, request *http.Request) {\n\tlog.Println(\"Create new Order in System\")\n\tcreateOrderCommand := commands.CreateOrder{}\n\torderId := <-orderHandler.CreateOrder(createOrderCommand)\n\twriteResponse(response, orderId)\n}", "func (h RequestPPMPaymentHandler) Handle(params ppmop.RequestPPMPaymentParams) middleware.Responder {\n\treturn h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,\n\t\tfunc(appCtx appcontext.AppContext) (middleware.Responder, error) {\n\t\t\tppmID, err := uuid.FromString(params.PersonallyProcuredMoveID.String())\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\tppm, err := models.FetchPersonallyProcuredMove(appCtx.DB(), appCtx.Session(), ppmID)\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\terr = ppm.RequestPayment()\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\n\t\t\tverrs, err := models.SavePersonallyProcuredMove(appCtx.DB(), ppm)\n\t\t\tif err != nil || verrs.HasAny() {\n\t\t\t\treturn handlers.ResponseForVErrors(appCtx.Logger(), verrs, err), err\n\t\t\t}\n\n\t\t\tppmPayload, err := payloadForPPMModel(h.FileStorer(), *ppm)\n\t\t\tif err != nil {\n\t\t\t\treturn handlers.ResponseForError(appCtx.Logger(), err), err\n\t\t\t}\n\t\t\treturn ppmop.NewRequestPPMPaymentOK().WithPayload(ppmPayload), nil\n\t\t})\n}", "func paymentDelete(service payment.UseCase) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\tpaymentID, ok := vars[\"paymentID\"]\n\t\tif !ok {\n\t\t\trespondWithError(w, http.StatusNotFound, \"Missing route parameter 'paymentID'\")\n\t\t\treturn\n\t\t}\n\t\tif entity.IsValidID(paymentID) {\n\t\t\terr := service.Delete(entity.StringToID(paymentID))\n\t\t\tif err != nil {\n\t\t\t\trespondWithError(w, http.StatusNotFound, \"Payment ID does not exist\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespondWithJSON(w, http.StatusNoContent, nil)\n\t\t} else {\n\t\t\trespondWithError(w, http.StatusBadRequest, \"Invalid Payment ID\")\n\t\t\treturn\n\t\t}\n\t})\n}", "func (r *Responder) PaymentRequired() { r.write(http.StatusPaymentRequired) }", "func QueryHandler(w http.ResponseWriter, r *http.Request) {\n\tdb := Connect()\n\tdefer db.Close()\n\n\tcanAccess, account := ValidateAuth(db, r, w)\n\tif !canAccess {\n\t\treturn\n\t}\n\n\tconnection, err := GetConnection(db, account.Id)\n\tif err != nil {\n\t\tif isBadConn(err, false) {\n\t\t\tpanic(err);\n\t\t\treturn;\n\t\t}\n\t\tstateResponse := &StateResponse{\n\t\t\tPeerId: 0,\n\t\t\tStatus: \"\",\n\t\t\tShouldFetch: false,\n\t\t\tShouldPeerFetch: false,\n\t\t}\n\t\tif err := json.NewEncoder(w).Encode(stateResponse); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn;\n\t}\n\n\tpeerId := connection.GetPeerId(account.Id)\n\tstatus := \"\"\n\tif connection.Status == PENDING {\n\t\tif connection.InviteeId == account.Id {\n\t\t\tstatus = \"pendingWithMe\"\n\t\t} else {\n\t\t\tstatus = \"pendingWithPeer\"\n\t\t}\n\t} else {\n\t\tstatus = \"connected\"\n\t}\n\n\tstateResponse := &StateResponse{\n\t\tPeerId: peerId,\n\t\tStatus: status,\n\t}\n\terr = CompleteFetchResponse(stateResponse, db, connection, account)\n\tif err != nil {\n\t\tlog.Printf(\"QueryPayload failed: %s\", err)\n\t\thttp.Error(w, \"could not query payload\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := json.NewEncoder(w).Encode(stateResponse); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (t *Procure2Pay) CreatePurchaseOrder(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n var objpurchaseOrder purchaseOrder\n\tvar objitem item\n\tvar err error\n\t\n\tfmt.Println(\"Entering CreatePurchaseOrder\")\n\n\tif len(args) < 1 {\n\t\tfmt.Println(\"Invalid number of args\")\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"Args [0] is : %v\\n\", args[0])\n\n\t//unmarshal customerInfo data from UI to \"customerInfo\" struct\n\terr = json.Unmarshal([]byte(args[0]), &objpurchaseOrder)\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to unmarshal CreatePurchaseOrder input purchaseOrder: %s\\n\", err)\n\t\treturn shim.Error(err.Error())\n\t\t}\n\n\tfmt.Println(\"purchase order object PO ID variable value is : %s\\n\", objpurchaseOrder.POID)\n\tfmt.Println(\"purchase order object PO ID variable value is : %s\\n\", objpurchaseOrder.Quantity)\n\n\t// Data insertion for Couch DB starts here \n\ttransJSONasBytes, err := json.Marshal(objpurchaseOrder)\n\terr = stub.PutState(objpurchaseOrder.POID, transJSONasBytes)\n\t// Data insertion for Couch DB ends here\n\n\t//unmarshal LoanTransactions data from UI to \"LoanTransactions\" struct\n\terr = json.Unmarshal([]byte(args[0]), &objitem)\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to unmarshal CreatePurchaseOrder input purchaseOrder: %s\\n\", err)\n\t\treturn shim.Error(err.Error())\n\t\t}\n\n\tfmt.Println(\"item object Item ID variable value is : %s\\n\", objitem.ItemID)\n\n\t// Data insertion for Couch DB starts here \n\ttransJSONasBytesLoan, err := json.Marshal(objitem)\n\terr = stub.PutState(objitem.ItemID, transJSONasBytesLoan)\n\t// Data insertion for Couch DB ends here\n\n\tfmt.Println(\"Create Purchase Order Successfully Done\")\n\n\tif err != nil {\n\t\tfmt.Printf(\"\\nUnable to make transevent inputs : %v \", err)\n\t\treturn shim.Error(err.Error())\n\t\t//return nil,nil\n\t}\n\treturn shim.Success(nil)\n}", "func processCommand(db models.DataStore, command []string) (models.StoreyResponse, error) {\n\tswitch command[0] {\n\tcase models.CmdCreateParkingLot:\n\t\tmaxSlots, err := strToInt(command[1])\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn db.AddStorey(maxSlots)\n\tcase models.CmdPark:\n\t\treturn db.Park(command[1], command[2])\n\tcase models.CmdCreateParkingLot:\n\tcase models.CmdStatus:\n\t\treturn db.All()\n\tcase models.CmdLeave:\n\t\tslotPosition, err := strToInt(command[1])\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn db.LeaveByPosition(slotPosition)\n\tcase models.CmdRegistrationNumberByColor:\n\t\treturn db.FindAllByColor(command[1], models.CmdRegistrationNumberByColor)\n\tcase models.CmdSlotnoByCarColor:\n\t\treturn db.FindAllByColor(command[1], models.CmdSlotnoByCarColor)\n\tcase models.CmdSlotnoByRegNumber:\n\t\treturn db.FindByRegistrationNumber(command[1])\n\tdefault:\n\t}\n\n\treturn models.StoreyResponse{}, nil\n}", "func main() {\n\tr := mux.NewRouter()\n\n\tvar err error\n\n\tpsqlInfo := fmt.Sprintf(\n\t\t\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\",\n\t\thost, port, user, password, dbname)\n\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer db.Close()\n\n\tsqlDB := domain.NewSQLDatabase(db)\n\n\thandler := handlers.NewRequestHandler(sqlDB)\n\n\tr.HandleFunc(\"/pay_user\", handler.PayUser).Methods(http.MethodPost)\n\tr.HandleFunc(\"/get_transactions\", handler.GetTransactions).Methods(http.MethodPost)\n\n\tlog.Print(\"Listening on port 80\")\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", 80), r))\n\n}", "func (h *handler) invoke(method handlerMethod) error {\n\t// exp vars used for reading request counts\n\trestExpvars.Add(\"requests_total\", 1)\n\trestExpvars.Add(\"requests_active\", 1)\n\tdefer restExpvars.Add(\"requests_active\", -1)\n\n\tswitch h.rq.Header.Get(\"Content-Encoding\") {\n\tcase \"\":\n\t\th.requestBody = h.rq.Body\n\tdefault:\n\t\treturn base.HTTPErrorf(http.StatusUnsupportedMediaType, \"Unsupported Content-Encoding;\")\n\t}\n\n\th.setHeader(\"Server\", VersionString)\n\n\t//To Do: If there is a \"db\" path variable, look up the database context:\n\tvar dbc *db.DatabaseContext\n dbc, err := h.server.GetDatabase();\n\n\tif err != nil {\n\t\t\th.logRequestLine()\n\t\t\treturn err\n\t}\n\t\n\t\n\t// Authenticate, if not on admin port:\n\tif h.privs != adminPrivs {\n\t\tif err := h.checkAuth(dbc); err != nil { \n\t\t\th.logRequestLine()\n\t\t\treturn err\n\t\t}\n\t}\n\t\n\th.logRequestLine()\n\n\t//assign db to handler h\n\n\treturn method(h) // Call the actual handler code\n\t\n}", "func (httpServer *HttpServer) handleGetRewardAmount(params interface{}, closeChan <-chan struct{}) (interface{}, *rpcservice.RPCError) {\n\tarrayParams := common.InterfaceSlice(params)\n\tif arrayParams == nil || len(arrayParams) != 1 {\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"param must be an array at least 1 element\"))\n\t}\n\n\tpaymentAddress, ok := arrayParams[0].(string)\n\tif !ok{\n\t\treturn nil, rpcservice.NewRPCError(rpcservice.RPCInvalidParamsError, errors.New(\"payment address is invalid\"))\n\t}\n\n\treturn httpServer.blockService.GetRewardAmount(paymentAddress)\n}", "func handleRequest(pc net.PacketConn, addr net.Addr, pr *PacketRequest, connectionSvc *ConnectionService) {\n\tif pr.Op == OpRRQ { // Read Request\n\t\tLogReadRequest(pr.Filename)\n\t\tdata, err := connectionSvc.openRead(addr.String(), pr.Filename)\n\t\tif err != nil {\n\t\t\tLogFileNotFound(pr.Filename)\n\t\t\tsendResponse(pc, addr, &PacketError{0x1, \"File not found (error opening file read)\"})\n\t\t} else {\n\t\t\tsendResponse(pc, addr, &PacketData{0x1, data})\n\t\t}\n\t} else if pr.Op == OpWRQ { // Write Request\n\t\tLogWriteRequest(pr.Filename)\n\t\tconnectionSvc.openWrite(addr.String(), pr.Filename)\n\t\tsendResponse(pc, addr, &PacketAck{0})\n\t}\n}", "func DoPaymentWithOVO(req paymentRequest) error {\n\t//1. get user Data (saldo OVO)\n\tuserData, err := getUserData(req.userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(userData)\n\t//2. validate\n\t//3. reduce saldo\n\t//4. return sucess\n\treturn nil\n}", "func (app *Application) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {\n\tvar method, key, value []byte\n\tparts := bytes.Split(req.Tx, []byte(\"=\"))\n\tif len(parts) == 3 {\n\t\tmethod, key, value = parts[0], parts[1], parts[2]\n\t} else {\n\t\tmethod, key, value = req.Tx, req.Tx, req.Tx\n\t}\n\n lib.Log.Notice(string(method))\n\tlib.Log.Notice(string(key))\n lib.Log.Notice(string(value))\n\n switch string(method) {\n case \"add\":\n // 此处修改 app.state.db.Set(prefixKey(key), value)\n app.state.db.Set(key, value)\n app.state.Size++\n case \"modify\":\n exist, e := app.state.db.Has(key)\n lib.Log.Notice(exist)\n if e == nil {\n app.state.db.Delete(key)\n app.state.db.Set(key, value)\n }\n case \"delete\":\n exist, e := app.state.db.Has(key)\n lib.Log.Notice(exist)\n if e == nil {\n app.state.db.Delete(key)\n }\n }\n\n\tevents := []types.Event{\n\t\t{\n\t\t\tType: \"app\",\n\t\t\tAttributes: []kv.Pair{\n\t\t\t\t{Key: []byte(\"creator\"), Value: []byte(\"Cosmoshi Netowoko\")},\n\t\t\t\t{Key: []byte(\"key\"), Value: key},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn types.ResponseDeliverTx{Code: code.CodeTypeOK, Events: events}\n}", "func GetTransactionHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\t// retrieve the parameters\n\tparam := make(map[string]uint64)\n\tfor _, key := range []string{\"blockId\", \"txId\"} {\n\t\tparam[key], _ = strconv.ParseUint(vars[\"blockId\"], 10, 64)\n\t}\n\n\ttmp := atomic.LoadUint64(&lastBlock)\n\tif param[\"blockId\"] > tmp {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terr := fmt.Errorf(\"requested id %d latest %d\", param[\"blockId\"], lastBlock)\n\t\tlog.Println(err.Error())\n\t\t_, _ = w.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\t// retuning anything in the body regardless of any error code\n\t// it may contain\n\t_, _, body, _ := dataCollection.GetTransaction(param[\"blockId\"], param[\"txId\"], config.DefaultRequestsTimeout)\n\twriteResponse(body, &w)\n}", "func (self *Client) process(url *url.URL, method string, data interface{}) ([]byte, error) {\n\tjsonb, err := json.Marshal(&data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn self.send(url, method, jsonb)\n}", "func (srv *Server) DB(r *http.Request) (*DB, error) {\n\treturn srv.db(r)\n}", "func (s *Server) handleGetData(request []byte) {\n\tvar payload serverutil.MsgGetData\n\tif err := getPayload(request, &payload); err != nil {\n\t\tlog.Panic(err)\n\t}\n\taddr := payload.AddrSender.String()\n\tp, _ := s.GetPeer(addr)\n\tp.IncreaseBytesReceived(uint64(len(request)))\n\ts.AddPeer(p)\n\ts.Log(true, fmt.Sprintf(\"GetData kind: %s, with ID:%s received from %s\", payload.Kind, hex.EncodeToString(payload.ID), addr))\n\n\tif payload.Kind == \"block\" {\n\t\t//block\n\t\t//on recupère le block si il existe\n\t\tblock, _ := s.chain.GetBlockByHash(payload.ID)\n\t\tif block != nil {\n\t\t\t//envoie le block au noeud créateur de la requete\n\t\t\ts.sendBlock(payload.AddrSender, block)\n\t\t} else {\n\t\t\tfmt.Println(\"block is nil :( handleGetData\")\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\ttime.Sleep(time.Millisecond * 50)\n\t\t\t\t\tblock, _ := s.chain.GetBlockByHash(payload.ID)\n\t\t\t\t\tif block != nil {\n\t\t\t\t\t\ts.sendBlock(payload.AddrSender, block)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t} else {\n\t\ttx := mempool.Mempool.GetTx(hex.EncodeToString(payload.ID))\n\t\tif tx != nil {\n\t\t\ts.SendTx(payload.AddrSender, tx)\n\t\t}\n\t}\n}", "func (c *Connection) processRequest(ch *api.Channel, chMeta *channelMetadata, req *api.VppRequest) error {\n\t// check whether we are connected to VPP\n\tif atomic.LoadUint32(&c.connected) == 0 {\n\t\terr := ErrNotConnected\n\t\tlog.Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\t// retrieve message ID\n\tmsgID, err := c.GetMessageID(req.Message)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to retrieve message ID: %v\", err)\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"msg_name\": req.Message.GetMessageName(),\n\t\t\t\"msg_crc\": req.Message.GetCrcString(),\n\t\t}).Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\t// encode the message into binary\n\tdata, err := c.codec.EncodeMsg(req.Message, msgID)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to encode the messge: %v\", err)\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": msgID,\n\t\t}).Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\tif log.Level == logger.DebugLevel { // for performance reasons - logrus does some processing even if debugs are disabled\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": msgID,\n\t\t\t\"msg_size\": len(data),\n\t\t\t\"msg_name\": req.Message.GetMessageName(),\n\t\t}).Debug(\"Sending a message to VPP.\")\n\t}\n\n\t// send the message\n\tif req.Multipart {\n\t\t// expect multipart response\n\t\tatomic.StoreUint32(&chMeta.multipart, 1)\n\t}\n\n\t// send the request to VPP\n\terr = c.vpp.SendMsg(chMeta.id, data)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to send the messge: %v\", err)\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": msgID,\n\t\t}).Error(err)\n\t\tsendReply(ch, &api.VppReply{Error: err})\n\t\treturn err\n\t}\n\n\tif req.Multipart {\n\t\t// send a control ping to determine end of the multipart response\n\t\tpingData, _ := c.codec.EncodeMsg(msgControlPing, c.pingReqID)\n\n\t\tlog.WithFields(logger.Fields{\n\t\t\t\"context\": chMeta.id,\n\t\t\t\"msg_id\": c.pingReqID,\n\t\t\t\"msg_size\": len(pingData),\n\t\t}).Debug(\"Sending a control ping to VPP.\")\n\n\t\tc.vpp.SendMsg(chMeta.id, pingData)\n\t}\n\n\treturn nil\n}", "func (b *backend) ProcessVerifyUserPayment(user *database.User, vupt v1.VerifyUserPayment) (*v1.VerifyUserPaymentReply, error) {\n\tvar reply v1.VerifyUserPaymentReply\n\tif b.HasUserPaid(user) {\n\t\treply.HasPaid = true\n\t\treturn &reply, nil\n\t}\n\n\tif paywallHasExpired(user.NewUserPaywallPollExpiry) {\n\t\tb.GenerateNewUserPaywall(user)\n\n\t\treply.PaywallAddress = user.NewUserPaywallAddress\n\t\treply.PaywallAmount = user.NewUserPaywallAmount\n\t\treply.PaywallTxNotBefore = user.NewUserPaywallTxNotBefore\n\t\treturn &reply, nil\n\t}\n\n\ttx, _, err := util.FetchTxWithBlockExplorers(user.NewUserPaywallAddress,\n\t\tuser.NewUserPaywallAmount, user.NewUserPaywallTxNotBefore,\n\t\tb.cfg.MinConfirmationsRequired)\n\tif err != nil {\n\t\tif err == util.ErrCannotVerifyPayment {\n\t\t\treturn nil, v1.UserError{\n\t\t\t\tErrorCode: v1.ErrorStatusCannotVerifyPayment,\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif tx != \"\" {\n\t\treply.HasPaid = true\n\n\t\terr = b.updateUserAsPaid(user, tx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// TODO: Add the user to the in-memory pool.\n\t}\n\n\treturn &reply, nil\n}", "func (q queryManager) processQuery(sql string, pubKey []byte, executeifallowed bool) (uint, []byte, []byte, *structures.Transaction, error) {\n\tlocalError := func(err error) (uint, []byte, []byte, *structures.Transaction, error) {\n\t\treturn SQLProcessingResultError, nil, nil, nil, err\n\t}\n\tqp := q.getQueryParser()\n\t// this will get sql type and data from comments. data can be pubkey, txBytes, signature\n\tqparsed, err := qp.ParseQuery(sql)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\t// maybe this query contains signature and txData from previous calls\n\tif len(qparsed.Signature) > 0 && len(qparsed.TransactionBytes) > 0 {\n\t\t// this is a case when signature and txdata were part of SQL comments.\n\t\ttx, err := q.processQueryWithSignature(qparsed.TransactionBytes, qparsed.Signature, executeifallowed)\n\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\treturn SQLProcessingResultTranactionComplete, nil, nil, tx, nil\n\t}\n\n\tneedsTX, err := q.checkQueryNeedsTransaction(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif !needsTX {\n\t\tif !executeifallowed {\n\t\t\t// no need to execute query. just return\n\t\t\treturn SQLProcessingResultExecuted, nil, nil, nil, nil\n\t\t}\n\t\t// no need to have TX\n\t\tif qparsed.IsUpdate() {\n\t\t\t_, err := qp.ExecuteQuery(qparsed.SQL)\n\t\t\tif err != nil {\n\t\t\t\treturn localError(err)\n\t\t\t}\n\t\t}\n\t\treturn SQLProcessingResultExecuted, nil, nil, nil, nil\n\t}\n\t// decide which pubkey to use.\n\n\t// first priority for a key posted as argument, next is the key in SQL comment (parsed) and final is the key\n\t// provided to thi module\n\tif len(pubKey) == 0 {\n\t\tif len(qparsed.PubKey) > 0 {\n\t\t\tpubKey = qparsed.PubKey\n\t\t} else if len(q.pubKey) > 0 {\n\t\t\tpubKey = q.pubKey\n\t\t} else {\n\t\t\t// no pubkey to use. return notice about pubkey required\n\t\t\treturn SQLProcessingResultPubKeyRequired, nil, nil, nil, nil\n\t\t}\n\t}\n\n\t// check if the key has permissions to execute this query\n\thasPerm, err := q.checkExecutePermissions(qparsed, pubKey)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif !hasPerm {\n\t\treturn localError(errors.New(\"No permissions to execute this query\"))\n\t}\n\n\tamount, err := q.checkQueryNeedsPayment(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\t// prepare SQL part of a TX\n\t// this builds RefID for a TX update\n\tsqlUpdate, err := qp.MakeSQLUpdateStructure(qparsed)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\t// prepare curency TX and add SQL part\n\n\ttxBytes, datatosign, err := q.getTransactionsManager().PrepareNewSQLTransaction(pubKey, sqlUpdate, amount, \"MINTER\")\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\ttx, err := structures.DeserializeTransaction(txBytes)\n\n\tif err != nil {\n\t\treturn localError(err)\n\t}\n\n\tif len(q.pubKey) > 0 && bytes.Compare(q.pubKey, pubKey) == 0 {\n\t\t// transaction was created by internal pubkey. we have private key for it\n\t\tsignature, err := utils.SignDataByPubKey(q.pubKey, q.privKey, datatosign)\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\ttx, err = q.processQueryWithSignature(txBytes, signature, executeifallowed)\n\n\t\tif err != nil {\n\t\t\treturn localError(err)\n\t\t}\n\n\t\treturn SQLProcessingResultTranactionCompleteInternally, nil, nil, tx, nil\n\t}\n\treturn SQLProcessingResultSignatureRequired, txBytes, datatosign, nil, nil\n}", "func (b *backend) ProcessProposalPaywallPayment(user *database.User) (*v1.ProposalPaywallPaymentReply, error) {\n\tlog.Tracef(\"ProcessProposalPaywallPayment\")\n\n\tvar (\n\t\ttxID string\n\t\ttxAmount uint64\n\t\tconfirmations uint64\n\t)\n\n\tb.RLock()\n\tdefer b.RUnlock()\n\n\tpoolMember, ok := b.userPaywallPool[user.ID]\n\tif ok {\n\t\ttxID = poolMember.txID\n\t\ttxAmount = poolMember.txAmount\n\t\tconfirmations = poolMember.txConfirmations\n\t}\n\n\treturn &v1.ProposalPaywallPaymentReply{\n\t\tTxID: txID,\n\t\tTxAmount: txAmount,\n\t\tConfirmations: confirmations,\n\t}, nil\n}", "func (_obj *Apipayments) Payments_getPaymentReceipt(params *TLpayments_getPaymentReceipt, _opt ...map[string]string) (ret Payments_PaymentReceipt, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"payments_getPaymentReceipt\", _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 = ret.ReadBlock(_is, 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 handleQuery(schema *graphql.Schema, w http.ResponseWriter, r *http.Request, db database.DB) {\n\tif r.Body == nil {\n\t\thttp.Error(w, \"Must provide graphql query in request body\", 400)\n\t\treturn\n\t}\n\n\t// Read and close JSON request body\n\tbody, err := ioutil.ReadAll(r.Body)\n\n\tdefer func() {\n\t\t_ = r.Body.Close()\n\t}()\n\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"%d error request: %v\", http.StatusBadRequest, err)\n\t\tlog.Error(msg)\n\t\thttp.Error(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar req data\n\tif err := json.Unmarshal(body, &req); err != nil {\n\t\tmsg := fmt.Sprintf(\"Unmarshal request: %v\", err)\n\t\tlog.Error(msg)\n\t\thttp.Error(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Execute graphql query\n\tresult := graphql.Do(graphql.Params{\n\t\tSchema: *schema,\n\t\tRequestString: req.Query,\n\t\tVariableValues: req.Variables,\n\t\tOperationName: req.Operation,\n\t\tContext: context.WithValue(context.Background(), \"database\", db), //nolint\n\t})\n\n\t//// Error check\n\t//if len(result.Errors) > 0 {\n\t//\tlog.\n\t//\t\tWithField(\"query\", req.Query).\n\t//\t\tWithField(\"variables\", req.Variables).\n\t//\t\tWithField(\"operation\", req.Operation).\n\t//\t\tWithField(\"errors\", result.Errors).Error(\"Execute query error(s)\")\n\t//}\n\n\trender.JSON(w, r, result)\n}", "func (d *deliveryAgent) process(message string) {\n\tpb := &postback.Postback{}\n\tif err := json.Unmarshal([]byte(message), pb); err != nil {\n\t\tlog.Println(\"ERROR: \", err)\n\t\treturn\n\t}\n\tpb.MountURL()\n\n\treq := request.NewRequest(pb.Endpoint.Url, pb.Endpoint.Method)\n\n\tswitch strings.ToLower(pb.Endpoint.Method) {\n\tcase \"get\":\n\t\tres, err := req.Get()\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR: \", err)\n\t\t\treturn\n\t\t}\n\t\td.logResponse(res)\n\tcase \"post\":\n\t\tbody, err := json.Marshal(pb.Data[0])\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR: \", err)\n\t\t\treturn\n\t\t}\n\t\treq.Body = body\n\t\tres, err := req.Post()\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR: \", err)\n\t\t\treturn\n\t\t}\n\t\td.logResponse(res)\n\t}\n\n}", "func addProductHandle(response http.ResponseWriter, request *http.Request) {\n\torderId := strings.Split(request.URL.Path, \"/\")[3]\n\tlog.Printf(\"Add product for order %s!\", orderId)\n\tdecoder := json.NewDecoder(request.Body)\n\taddProductCommand := commands.AddProduct{}\n\terr := decoder.Decode(&addProductCommand)\n\tif err != nil {\n\t\twriteErrorResponse(response, err)\n\t}\n\torder := <-orderHandler.AddProductInOrder(OrderId{Id: orderId}, addProductCommand)\n\twriteResponse(response, order)\n}", "func handleConnection(conn net.Conn) {\n\tencoder := json.NewEncoder(conn)\n\tdecoder := json.NewDecoder(conn)\n\n\tvar incomingMsg BackendPayload\n\t// recieveing the response from the backend through the json decoder\n\terr := decoder.Decode(&incomingMsg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tswitch incomingMsg.Mode { // choose function based on the mode sent by front end server\n\tcase \"getTasks\":\n\t\tgetTasks(encoder)\n\tcase \"createTask\":\n\t\tcreateTask(incomingMsg)\n\tcase \"updateTask\":\n\t\tupdateTask(incomingMsg)\n\tcase \"deleteTask\":\n\t\tdeleteTask(incomingMsg)\n\t}\n}" ]
[ "0.8066236", "0.63811046", "0.60661125", "0.5885126", "0.5838394", "0.58021265", "0.57802284", "0.5765489", "0.5746198", "0.56511474", "0.5642199", "0.56173843", "0.55882144", "0.55527824", "0.547019", "0.54304844", "0.5391546", "0.5343794", "0.5305601", "0.52543783", "0.5251321", "0.52506506", "0.5242801", "0.52427405", "0.5229285", "0.5227413", "0.521083", "0.52093685", "0.5202559", "0.51825404", "0.5166067", "0.516251", "0.5159561", "0.5154124", "0.51427954", "0.51330686", "0.5097013", "0.5087672", "0.50868", "0.5080033", "0.50631624", "0.5061374", "0.50546414", "0.504892", "0.5032336", "0.5027094", "0.5015288", "0.5000177", "0.49972197", "0.49950552", "0.49854335", "0.49836838", "0.49712136", "0.4966476", "0.4957381", "0.49428272", "0.4941607", "0.49214017", "0.49186558", "0.49149886", "0.4914507", "0.4910198", "0.49094027", "0.49071002", "0.48836365", "0.48738378", "0.486894", "0.48682272", "0.48631966", "0.48624977", "0.48563594", "0.48393223", "0.48377025", "0.48263723", "0.4813279", "0.4812777", "0.4812759", "0.48085284", "0.48021486", "0.4800268", "0.479554", "0.4792473", "0.47874746", "0.47844213", "0.4780335", "0.47801137", "0.47771642", "0.47769427", "0.4768522", "0.4765779", "0.47639465", "0.4763944", "0.47607946", "0.47593787", "0.47567", "0.47480354", "0.4744062", "0.47370663", "0.47349915", "0.473103" ]
0.8300391
0
Bit returns a uint32 with vth bit set to 1.
Bit возвращает uint32 с битом vth установленным в 1.
func Bit(v int) uint32 { return uint32(1) << uint32(v) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (x *Int) Bit(i int) uint {}", "func IntBit(x *big.Int, i int) uint", "func Bit(x, n uint) uint {\n\treturn (x >> n) & 1\n}", "func MSB32(x uint32) uint32", "func Val(value byte, bit byte) byte {\n\treturn (value >> bit) & 1\n}", "func getBit(n int32, i int) int32 {\n\tresult := n & (1 << uint(i))\n\tif result != 0 {\n\t\treturn 1\n\t} else {\n\t\treturn 0\n\t}\n}", "func (b Bits) Bit(n int) int {\n\tif n < 0 || n >= b.Num {\n\t\tpanic(\"bit number out of range\")\n\t}\n\treturn int(b.Bits[n>>6] >> uint(n&63) & 1)\n}", "func OnBit(num int, nth int) int {\n\treturn num | (1 << uint(nth))\n}", "func OnBit(num, nth int) int {\n\treturn num | (1 << uint(nth))\n}", "func Bit(x *big.Int, i int) uint {\n\treturn x.Bit(i)\n}", "func Uint32() uint32", "func (bitmap *bitmap) Bit(index int) int {\n\tif index >= bitmap.Size {\n\t\tpanic(\"index out of range\")\n\t}\n\n\tdiv, mod := index/8, index%8\n\treturn int((uint(bitmap.data[div]) & (1 << uint(7-mod))) >> uint(7-mod))\n}", "func Bitno(b uint64) int", "func GetBit(x *Key, pos uint) int {\n\tif (((x)[(pos)/BITS_PER_BYTE]) & (0x1 << ((pos) % BITS_PER_BYTE))) != 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (cpu *Mos6502) bit() uint8 {\n\tcpu.fetch()\n\tcpu.temp = word(cpu.a & cpu.fetchedData)\n\tcpu.setStatusFlag(Z, (cpu.temp&0x00ff) == 0x00)\n\tcpu.setStatusFlag(N, (cpu.fetchedData&(1<<7)) > 0)\n\tcpu.setStatusFlag(V, (cpu.fetchedData&(1<<6)) > 0)\n\treturn 0\n}", "func bit(cpu *CPU, r, b byte) {\n\tbit := (r>>b)&1 == 0\n\tcpu.SetZero(bit)\n\tcpu.SetNegative(false)\n\tcpu.SetHalfCarry(true)\n}", "func (z *Int) SetBit(x *Int, i int, b uint) *Int {}", "func Bits(x, msb, lsb uint) uint {\n\treturn (x & Mask(msb, lsb)) >> lsb\n}", "func p256GetBit(scalar *[32]uint8, bit uint) uint32 {\n\treturn uint32(((scalar[bit>>3]) >> (bit & 7)) & 1)\n}", "func GetBit(b byte, idx uint) bool {\n\tif idx < 0 || idx > 7 {\n\t\tlog.Panic(\"the idx must be from 0 to 7\")\n\t}\n\tif (b>>idx)&1 == 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func setBit(addr uint32, bit uint, val uint) uint32 {\n\tif bit < 0 {\n\t\tpanic(\"negative bit index\")\n\t}\n\n\tif val == 0 {\n\t\treturn addr & ^(1 << (32 - bit))\n\t} else if val == 1 {\n\t\treturn addr | (1 << (32 - bit))\n\t} else {\n\t\tpanic(\"set bit is not 0 or 1\")\n\t}\n}", "func NthBit(num int, nth int) int {\n\treturn num >> uint(nth) & 1\n}", "func (x *Int) Bits() []Word {}", "func sm2P256GetBit(scalar *[32]uint8, bit uint) uint32 {\n\treturn uint32(((scalar[bit>>3]) >> (bit & 7)) & 1)\n}", "func (c *CPU) Bit(r Register, bitnum byte) {\n\tc.MaybeFlagSetter(c.reg[r]&(1<<bitnum) == 0, ZFlag)\n\tc.ResetFlag(NFlag)\n\tc.SetFlag(HFlag)\n\n}", "func valueAtbit(num int, bit int) int {\n\treturn -1\n}", "func getbit(a []uint64, x int) uint64 {\n\treturn (a[(x)/64] >> uint64((x)%64)) & 1\n}", "func getBit(bitboard uint64, square int) (rgw uint64) {\n\tif bitboard&(1<<square) != 0 {\n\t\trgw = 1\n\t}\n\treturn rgw\n}", "func (ip ip16) firstWithBitOne(bit uint8) ip16 {\n\tip.set(bit)\n\tfor ; bit < 128; bit++ {\n\t\tip.clear(bit)\n\t}\n\treturn ip\n}", "func SetBit(n int, pos uint, val int) int {\n\tn |= (val << pos)\n\treturn n\n}", "func msb(val uint64) uint64 {\n\tbit := uint64((math.MaxUint64 + 1) >> 1)\n\tfor val < bit {\n\t\tbit >>= 1\n\t}\n\treturn bit\n}", "func SetBit(b byte, idx uint, flag bool) byte {\n\tif idx < 0 || idx > 7 {\n\t\tlog.Panic(\"the idx must be from 0 to 7\")\n\t}\n\tif flag {\n\t\treturn b | (1 << idx)\n\t}\n\treturn b &^ (1 << idx)\n}", "func (x *Int) BitLen() int {}", "func updateBit(num int, i int, valIs1 bool) int {\n\t// set our bit value\n\tval := 0\n\tif valIs1 {\n\t\tval = 1\n\t}\n\t// create a mask to clear the ith bit in our number\n\tclearMask := ^(1 << i)\n\t// create a mask to set the ith bit in our number\n\tvalueMask := val << i\n\treturn (num & clearMask) | valueMask\n}", "func (t *Target) Bit(b bool) usm.Value {\n\tif b {\n\t\treturn \"true\"\n\t}\n\treturn \"false\"\n}", "func (w *Weighted) Bit(offset Uint128, density uint64, scale uint64) uint64 {\n\tvar bit uint64\n\t// In order to be able to cache/reuse values, we want to grab a whole\n\t// set of 128 bits including a given offset, and use the same\n\t// calculation for all of them. So we mask out the low-order 7 bits\n\t// of offset, and use them separately. Meanwhile, Bits will\n\t// always right-shift its column bits by 7, which reduces the\n\t// space of possible results but means that it produces the same\n\t// set of bits for any given batch...\n\toffset.Lo, bit = offset.Lo&^127, offset.Lo&127\n\tif offset == w.lastOffset && density == w.lastDensity && scale == w.lastScale {\n\t\treturn w.lastValue.Bit(bit)\n\t}\n\tw.lastValue = w.Bits(offset, density, scale)\n\tw.lastOffset, w.lastDensity, w.lastScale = offset, density, scale\n\treturn w.lastValue.Bit(bit)\n}", "func OffBit(num int, nth int) int {\n\treturn num & ^(1 << uint(nth))\n}", "func FastrandUint32() uint32", "func Test(value byte, bit byte) bool {\n\treturn (value>>bit)&1 == 1\n}", "func OffBit(num, nth int) int {\n\treturn num & ^(1 << uint(nth))\n}", "func (child MagicU32) Uint32() uint32 {\n\treturn uint32(child &^ (1 << 31))\n}", "func GetNthBit(num, nth int) int {\n\treturn num >> uint(nth) & 1\n}", "func (child MagicU32) MagicBit() bool {\n\treturn (child & (1 << 31)) > 0\n}", "func Set(value byte, bit byte) byte {\n\treturn value | (1 << bit)\n}", "func Uint32n(n uint32) uint32", "func bool2uint32(value bool) uint32 {\n\tif value {\n\t\treturn 1\n\t} else {\n\t\treturn 0\n\t}\n}", "func BvconstOne(bits uint32) TermT {\n\treturn TermT(C.yices_bvconst_one(C.uint32_t(bits)))\n}", "func (b *bitVec) get(n uint) bool {\n\tpos, slot := b.calculateBitLocation(n)\n\tif b.bits[pos]>>slot&1 == 1 {\n\t\treturn true\n\t}\n\treturn false\n}", "func setBit(num int, i int) int {\n\treturn num | (1 << i)\n}", "func SetBit(x *big.Int, i int, b uint) *big.Int {\n\treturn new(big.Int).SetBit(x, i, b)\n}", "func getBit(num int, i int) bool {\n\treturn (num & (1 << i)) != 0\n}", "func nthBit(x byte, n uint) bool {\n\tif x>>n&1 == byte(0) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (this *BigInteger) TestBit(n int64) bool {\n\tvar j int64 = int64(math.Floor(float64(n) / float64(DB)))\n\tif j >= this.T {\n\t\treturn this.S != 0\n\t}\n\treturn this.V[j]&(1<<uint(n%DB)) != 0\n}", "func BIT() operators.Operator {\n\treturn operators.Alts(\n\t\t\"BIT\",\n\t\toperators.String(\"0\", \"0\"),\n\t\toperators.String(\"1\", \"1\"),\n\t)\n}", "func BoolToUint(x bool) uint {\n\tif x {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func Uint32() uint32 { return globalRand.Uint32() }", "func Uint32() uint32 { return globalRand.Uint32() }", "func Uint32() uint32 { return globalRand.Uint32() }", "func (c *CPU) BitHL(bitnum byte) {\n\tv := c.readMemory(c.ReadHL())\n\tc.MaybeFlagSetter(v&(1<<bitnum) == 0, ZFlag)\n\tc.ResetFlag(NFlag)\n\tc.SetFlag(HFlag)\n}", "func (n *Uint256) Uint32() uint32 {\n\treturn uint32(n.n[0])\n}", "func setBit(bitboard uint64, square int) uint64 {\n\treturn bitboard | (1 << square)\n}", "func (td TupleDesc) GetBit(i int, tup Tuple) (v uint64, ok bool) {\n\ttd.expectEncoding(i, Bit64Enc)\n\tb := td.GetField(i, tup)\n\tif b != nil {\n\t\tv, ok = readBit64(b), true\n\t}\n\treturn\n}", "func MSB16(x uint16) uint16", "func (c *Configurator) Uint32(name string, value uint32, usage string) *uint32 {\n\tp := new(uint32)\n\n\tc.Uint32Var(p, name, value, usage)\n\n\treturn p\n}", "func (r *R1_eg) setBit(idx1 int, value int) {\n\tr.Values[idx1] = value\n}", "func (pl List) ToBitField() uint32 {\n\tvar ret uint32\n\tfor _, p := range pl {\n\t\tret |= p.Mask()\n\t}\n\treturn ret\n}", "func BvconstUint32(bits uint32, x uint32) TermT {\n\treturn TermT(C.yices_bvconst_uint32(C.uint32_t(bits), C.uint32_t(x)))\n}", "func uintVarToInt32(v uint32, numbits uint8) int32 {\n\tneg := (v & (0x1 << (numbits - 1))) != 0 //check positive/negative\n\tif neg { //2s complement\n\t\tv = v ^ ((1 << (numbits)) - 1) //flip all the bits\n\t\tv = v + 1 //add 1 - positive nbit number\n\t\tv = -v //get the negative - this gives us a proper negative int32\n\t}\n\treturn int32(v)\n}", "func xgetbv() (eax, edx uint32)", "func Uint(flag string, value uint, description string) *uint {\n\tvar v uint\n\tUintVar(&v, flag, value, description)\n\treturn &v\n}", "func (f *Uint32) Get() uint32 {\n\treturn f.get().(uint32)\n}", "func BitOr(x, y meta.ConstValue) meta.ConstValue {\n\tv1, ok1 := x.ToInt()\n\tv2, ok2 := y.ToInt()\n\tif ok1 && ok2 {\n\t\treturn meta.NewIntConst(v1 | v2)\n\t}\n\treturn meta.UnknownValue\n}", "func BitNum(num uint64) uint64 {\n\tvar bitn int64 = 63\n\tfor (bitn >= 0) && (((1 << uint64(bitn)) & num) == 0) {\n\t\tbitn--\n\t}\n\treturn uint64(bitn + 1)\n}", "func GetUint32(key string) uint32 { return viper.GetUint32(key) }", "func (r *Rand) Uint32() uint32 {\n\treturn uint32(r.Int63() >> 31)\n}", "func (w *Writer) BitIndex() int64", "func Uint32(v uint32) *uint32 {\n\treturn &v\n}", "func SetBit(bitfield []byte, id uint32) ([]byte, error) {\n\tif uint32(len(bitfield)*8) <= id {\n\t\treturn nil, fmt.Errorf(\"bitfield is too short\")\n\t}\n\n\tbitfield[id/8] = bitfield[id/8] | (128 >> (id % 8))\n\n\treturn bitfield, nil\n}", "func (w *Writer) Bit(b byte) (err error) {\n\tw.bits <<= 1\n\tw.bits |= (b & 1)\n\tw.free--\n\n\tif w.free == 0 {\n\t\terr = w.Flush()\n\t}\n\treturn\n}", "func MSB64(x uint64) uint64", "func IntSetBit(z *big.Int, x *big.Int, i int, b uint) *big.Int", "func MinUint32(x, min uint32) uint32 { return x }", "func (ch UintCheck) Check(item uint) (bool, error) { return ch(item) }", "func Signed20Bit(in uint32) (out uint32) {\n\tout = in\n\tif (out & 0x80000) != 0 {\n\t\t// Data is negative\n\t\tout |= 0xFFF00000\n\t}\n\treturn out\n}", "func (b Bitfield) GetValue(field Bitfield) uint8 {\n\tif b.Get(field) {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func newBitType(width int32, varying bool) (*types.T, error) {\n\tif width < 1 {\n\t\treturn nil, errBitLengthNotPositive\n\t}\n\tif varying {\n\t\treturn types.MakeVarBit(width), nil\n\t}\n\treturn types.MakeBit(width), nil\n}", "func (bm BitMap) GetBit(ctx context.Context, offset int64) (int64, error) {\n\treq := newRequest(\"*3\\r\\n$6\\r\\nGETBIT\\r\\n$\")\n\treq.addStringInt(bm.name, offset)\n\treturn bm.c.cmdInt(ctx, req)\n}", "func Uint32(n uint32) *uint32 {\n\treturn &n\n}", "func Uint32(v *uint32) uint32 {\n\tif v != nil {\n\t\treturn *v\n\t}\n\treturn 0\n}", "func msb(b Bitboard) int {\n\treturn 63 - bits.LeadingZeros64(uint64(b))\n}", "func opUI16Bitand(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI16(fp, expr.Inputs[0]) & ReadUI16(fp, expr.Inputs[1])\n\tWriteUI16(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func readVarUInt32(r io.Reader) (uint32, error) {\n\t// Since we are being given seven bits per byte, we can fit 4 1/2 bytes\n\t// of input into our four bytes of value, so don't read more than 5 bytes.\n\tbits, err := readVarNumber(5, r)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// 0xF0 == 0b1111_0000.\n\tif (len(bits) == 5) && (bits[4]&0xF0 != 0) {\n\t\treturn 0, errors.Errorf(\"number is too big to fit into uint32: % #x\", bits)\n\t}\n\n\tvar ret uint32\n\t// Compact all of the bits into a uint32, ignoring the stop bit.\n\t// Turn [0111 1111] [1110 1111] into [0011 1111] [1110 1111].\n\tfor _, b := range bits {\n\t\tret <<= 7\n\t\tret |= uint32(b & 0x7F)\n\t}\n\n\treturn ret, nil\n}", "func (difficulty *Difficulty) Bits() uint32 {\n\tdifficulty.RLock()\n\tdefer difficulty.RUnlock()\n\treturn difficulty.bits\n}", "func (z *Int) lshOne() {\n\tvar (\n\t\ta, b uint64\n\t)\n\ta = z[0] >> 63\n\tb = z[1] >> 63\n\n\tz[0] = z[0] << 1\n\tz[1] = z[1]<<1 | a\n\n\ta = z[2] >> 63\n\tz[2] = z[2]<<1 | b\n\tz[3] = z[3]<<1 | a\n}", "func (r *Rand) Uint32() uint32 {\n\tif x, err := r.cryptoRand.Uint32(); err == nil {\n\t\treturn x\n\t}\n\treturn r.mathRand.Uint32()\n}", "func IntBitLen(x *big.Int,) int", "func SetBit(b byte, bitN int) byte {\n\tif bitN <= 0 {\n\t\treturn b\n\t}\n\treturn b | byte(1<<byte(bitN)-1)\n}", "func (v Value) Uint(bitSize int) (uint64, error) {\n\ts, err := v.getIntStr()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := strconv.ParseUint(s, 10, bitSize)\n\tif err != nil {\n\t\treturn 0, v.newError(\"%v\", err)\n\t}\n\treturn n, nil\n}", "func getBitFromByte(b byte, indexInByte int) byte {\n\tb = b << uint(indexInByte)\n\tvar mask byte = 0x80\n\n\tvar bit byte = mask & b\n\n\tif bit == 128 {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func Get1(bm []uint64, i int32) uint64 {\n\treturn (bm[i>>6] >> uint(i&63)) & 1\n}" ]
[ "0.6833733", "0.66398203", "0.65513724", "0.64699847", "0.6399387", "0.63546085", "0.61861306", "0.61491585", "0.61178416", "0.6110519", "0.6080812", "0.6062119", "0.6059498", "0.587452", "0.5837608", "0.5821337", "0.58110696", "0.5806684", "0.5805188", "0.57958925", "0.5781236", "0.5778416", "0.57724726", "0.57548296", "0.5715238", "0.56732535", "0.56214446", "0.5616069", "0.5614811", "0.56121284", "0.5575782", "0.5572214", "0.5544884", "0.55348456", "0.5520158", "0.5497534", "0.5451004", "0.54434687", "0.54421806", "0.54396164", "0.54228765", "0.5408037", "0.5374821", "0.5363509", "0.53549033", "0.5351597", "0.53436655", "0.5338019", "0.53265876", "0.5315479", "0.5304822", "0.5295673", "0.5283538", "0.52811736", "0.5250888", "0.5223985", "0.5223985", "0.5223985", "0.52111715", "0.52090454", "0.5207057", "0.5189934", "0.5187925", "0.51758224", "0.5171509", "0.5166969", "0.5162627", "0.5143575", "0.5140376", "0.5080871", "0.50691026", "0.50622225", "0.50528747", "0.5049292", "0.5034737", "0.5026362", "0.5024662", "0.5021189", "0.5000637", "0.4997657", "0.4997467", "0.49875468", "0.4987389", "0.49846682", "0.49775374", "0.497169", "0.4966042", "0.49645188", "0.49627143", "0.4958641", "0.49552292", "0.49539837", "0.4950202", "0.49492696", "0.49476236", "0.49469605", "0.49391088", "0.49339372", "0.49248835", "0.49240616" ]
0.8089188
0
SetPostviewImageSize sets the Post View image size for the camera: The possible options are: "2M" a smaller preview, usually 2Megpixels in size, sometimes not camera dependant "Original" the size of the image taken
SetPostviewImageSize задает размер изображения в режиме просмотра для камеры: возможные варианты: "2M" — более мелкий предварительный просмотр, обычно размером 2 мегапикселя, иногда не зависящий от камеры "Original" — размер изображения, которое было снято
func (c *Camera) SetPostviewImageSize(size PostViewSize) (err error) { _, err = c.newRequest(endpoints.Camera, "setPostviewImageSize", size).Do() return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Camera) GetPostviewImageSize() (size string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getPostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) > 0 {\n\t\terr = json.Unmarshal(resp.Result[0], &size)\n\t}\n\n\treturn\n}", "func (c *Camera) SetImageSize(width int, height int) (err error) {\n\tc.imageWidth = width\n\tc.imageHeight = height\n\n\terr = c.Lens.setAspectRatio(float64(width) / float64(height))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.output = image.NewRGBA(image.Rect(0, 0, c.imageWidth, c.imageHeight))\n\treturn\n}", "func (c *Camera) GetSupportedPostviewImageSize() (sizes []string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getSupportedPostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) > 0 {\n\t\terr = json.Unmarshal(resp.Result[0], &sizes)\n\t}\n\n\treturn\n}", "func (c *Camera) SetSize(widht, height int) {\n\tc.windowWidth = widht\n\tc.windowHeight = height\n}", "func (canvas *Canvas) SetSize(width, height Unit) {\n\tcanvas.page.MediaBox = Rectangle{Point{0, 0}, Point{width, height}}\n}", "func (c *Camera) GetAvailablePostviewImageSize() (current string, available []string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getAvailablePostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) >= 1 {\n\t\t// Current size\n\t\tif err := json.Unmarshal(resp.Result[0], &current); err != nil {\n\t\t\treturn current, available, err\n\t\t}\n\n\t\t// Available sizes\n\t\tif err := json.Unmarshal(resp.Result[1], &available); err != nil {\n\t\t\treturn current, available, err\n\t\t}\n\t}\n\n\treturn\n}", "func (c *Client) RenterSetStreamCacheSizePost(cacheSize uint64) (err error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"streamcachesize\", strconv.FormatUint(cacheSize, 10))\n\terr = c.post(\"/renter\", values.Encode(), nil)\n\treturn\n}", "func qr_decoder_set_image_size(p _QrDecoderHandle, width, height, depth, channel int) _QrDecoderHandle {\n\tv := C.qr_decoder_set_image_size(C.QrDecoderHandle(p),\n\t\tC.int(width), C.int(height), C.int(depth), C.int(channel),\n\t)\n\treturn _QrDecoderHandle(v)\n}", "func (b *builder) SetSize(width, height pic.Twiplet, dpi int32) {\n\tb.width = width.Pixels(dpi)\n\tb.height = height.Pixels(dpi)\n\tb.dpi = float64(dpi)\n}", "func (tv *TextView) SetSize() bool {\n\tsty := &tv.Sty\n\tspc := sty.BoxSpace()\n\trndsz := tv.RenderSz\n\trndsz.X += tv.LineNoOff\n\tnetsz := mat32.Vec2{float32(tv.LinesSize.X) + tv.LineNoOff, float32(tv.LinesSize.Y)}\n\tcursz := tv.LayData.AllocSize.SubScalar(2 * spc)\n\tif cursz.X < 10 || cursz.Y < 10 {\n\t\tnwsz := netsz.Max(rndsz)\n\t\ttv.Size2DFromWH(nwsz.X, nwsz.Y)\n\t\ttv.LayData.Size.Need = tv.LayData.AllocSize\n\t\ttv.LayData.Size.Pref = tv.LayData.AllocSize\n\t\treturn true\n\t}\n\tnwsz := netsz.Max(rndsz)\n\talloc := tv.LayData.AllocSize\n\ttv.Size2DFromWH(nwsz.X, nwsz.Y)\n\tif alloc != tv.LayData.AllocSize {\n\t\ttv.LayData.Size.Need = tv.LayData.AllocSize\n\t\ttv.LayData.Size.Pref = tv.LayData.AllocSize\n\t\treturn true\n\t}\n\t// fmt.Printf(\"NO resize: netsz: %v cursz: %v rndsz: %v\\n\", netsz, cursz, rndsz)\n\treturn false\n}", "func (w *WebGLRenderTarget) SetSize(width, height float64) *WebGLRenderTarget {\n\tw.p.Call(\"setSize\", width, height)\n\treturn w\n}", "func (r *ImageRef) SetPageHeight(height int) error {\n\tout, err := vipsCopyImage(r.image)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvipsSetPageHeight(out, height)\n\n\tr.setImage(out)\n\treturn nil\n}", "func (b *GoGLBackendOffscreen) SetSize(w, h int) {\n\tb.GoGLBackend.SetBounds(0, 0, w, h)\n\tb.offscrImg.w = b.offscrBuf.w\n\tb.offscrImg.h = b.offscrBuf.h\n}", "func (pu *PostUpdate) SetViewCount(i int) *PostUpdate {\n\tpu.mutation.ResetViewCount()\n\tpu.mutation.SetViewCount(i)\n\treturn pu\n}", "func (wg *WidgetImplement) SetSize(w, h int) {\n\twg.w = w\n\twg.h = h\n}", "func (self *TraitPixbufLoader) SetSize(width int, height int) {\n\tC.gdk_pixbuf_loader_set_size(self.CPointer, C.int(width), C.int(height))\n\treturn\n}", "func (this *Window) SetSize(size Vector2u) {\n\tC.sfWindow_setSize(this.cptr, size.toC())\n}", "func (v *PixbufLoader) SetSize(width, height int) {\n\tC.gdk_pixbuf_loader_set_size(v.Native(), C.int(width), C.int(height))\n}", "func (m *Map) SetView(center *LatLng, zoom int) {\n\tm.Value.Call(\"setView\", center.Value, zoom)\n}", "func (puo *PostUpdateOne) SetViewCount(i int) *PostUpdateOne {\n\tpuo.mutation.ResetViewCount()\n\tpuo.mutation.SetViewCount(i)\n\treturn puo\n}", "func (in *ActionIpAddressIndexInput) SetSize(value int64) *ActionIpAddressIndexInput {\n\tin.Size = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"Size\"] = nil\n\treturn in\n}", "func (c *Camera) SetPersp(view image.Rectangle, fov, near, far float64) {\n\taspectRatio := float64(view.Dx()) / float64(view.Dy())\n\tm := lmath.Mat4Perspective(fov, aspectRatio, near, far)\n\tc.Projection = ConvertMat4(m)\n}", "func (s *Surface) SetSize(w, h int) {\n\ts.Canvas.Set(\"width\", w)\n\ts.Canvas.Set(\"height\", h)\n}", "func (m *PrinterDefaults) SetMediaSize(value *string)() {\n err := m.GetBackingStore().Set(\"mediaSize\", value)\n if err != nil {\n panic(err)\n }\n}", "func (a *PhonebookAccess1) SetFixedImageSize(v bool) error {\n\treturn a.SetProperty(\"FixedImageSize\", v)\n}", "func imgSetWidthHeight(camera int, width int, height int) int {\n\tlog.Printf(\"imgSetWidthHeight - camera:%d width:%d height:%d\", camera, width, height)\n\tvar f = mod.NewProc(\"img_set_wh\")\n\tret, _, _ := f.Call(uintptr(camera), uintptr(width), uintptr(height))\n\treturn int(ret) // retval is cameraID\n}", "func SetSize(scope *Scope, set_indices tf.Output, set_values tf.Output, set_shape tf.Output, optional ...SetSizeAttr) (size tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"SetSize\",\n\t\tInput: []tf.Input{\n\t\t\tset_indices, set_values, set_shape,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (dw *DrawingWand) SetFontSize(pointSize float64) {\n\tC.MagickDrawSetFontSize(dw.dw, C.double(pointSize))\n}", "func SetViewRect(view ViewID, x, y, w, h int) {\n\tC.bgfx_set_view_rect(\n\t\tC.ushort(view),\n\t\tC.ushort(x),\n\t\tC.ushort(y),\n\t\tC.ushort(w),\n\t\tC.ushort(h),\n\t)\n}", "func (c *Camera) SetZoom(z float64) {\n\tif z == 0.0 {\n\t\treturn\n\t}\n\tc.zoom = z\n\tc.zoomInv = 1 / z\n\tc.sTop = c.lookAtY + float64(c.screenH/2)*c.zoomInv\n\tc.sBottom = c.lookAtY - float64(c.screenH/2)*c.zoomInv\n\tc.sLeft = c.lookAtX - float64(c.screenW/2)*c.zoomInv\n\tc.sRight = c.lookAtX + float64(c.screenW/2)*c.zoomInv\n}", "func SetWindowSize(file *os.File, width, height int) error {\n\tws := &winsize{row: uint16(height), col: uint16(width)}\n\t_, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tfile.Fd(),\n\t\tuintptr(syscall.TIOCSWINSZ),\n\t\tuintptr(unsafe.Pointer(ws)),\n\t)\n\tif err != 0 {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (gc *GceCache) SetMigTargetSize(ref GceRef, size int64) {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\tgc.migTargetSizeCache[ref] = size\n}", "func (gc *GceCache) SetMigTargetSize(ref GceRef, size int64) {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\tgc.migTargetSizeCache[ref] = size\n}", "func hookSetImageSize(e *evtx.GoEvtxMap) {\n\tvar path *evtx.GoEvtxPath\n\tvar modpath *evtx.GoEvtxPath\n\tswitch e.EventID() {\n\tcase 1:\n\t\tpath = &pathSysmonImage\n\t\tmodpath = &pathImSize\n\tdefault:\n\t\tpath = &pathSysmonImageLoaded\n\t\tmodpath = &pathImLoadedSize\n\t}\n\tif image, err := e.GetString(path); err == nil {\n\t\tif fsutil.IsFile(image) {\n\t\t\tif stat, err := os.Stat(image); err == nil {\n\t\t\t\te.Set(modpath, toString(stat.Size()))\n\t\t\t}\n\t\t}\n\t}\n}", "func SetWindowSizeCallback(f WindowSizeHandler) {\n\twindowSize = f\n\tC.glfwSetWindowSizeCB()\n}", "func (m NoMDEntries) SetMDEntrySize(value decimal.Decimal, scale int32) {\n\tm.Set(field.NewMDEntrySize(value, scale))\n}", "func (o *PostDeviceRackParams) SetSize(size *string) {\n\to.Size = size\n}", "func (s Surface) SetSize(width, height float64) error {\n\tC.cairo_ps_surface_set_size(s.XtensionRaw(), C.double(width), C.double(height))\n\treturn s.Err()\n}", "func SetViewTransform(viewID ViewID, view, proj [16]float32) {\n\tC.bgfx_set_view_transform(\n\t\tC.ushort(viewID),\n\t\tunsafe.Pointer(&view[0]),\n\t\tunsafe.Pointer(&proj[0]),\n\t)\n}", "func (s *sizes) setSizes(width int, height int) {\n\ts.width = width\n\ts.height = height\n\ts.curStreamsPerStreamDisplay = 1 + height/10\n}", "func (m verboseModel) resizeView(msg tea.WindowSizeMsg) verboseModel {\n\t// handle width changes\n\tm.viewport.Width = msg.Width\n\n\t// handle height changes\n\tif outlinePadding >= msg.Height {\n\t\t// height too short to fit viewport\n\t\tm.viewport.Height = 0\n\t} else {\n\t\tnewHeight := msg.Height - outlinePadding\n\t\tm.viewport.Height = newHeight\n\t}\n\n\treturn m\n}", "func (m *AttachmentItem) SetSize(value *int64)() {\n m.size = value\n}", "func (p *Post) SetViewAttributes(\n\tmetas map[uint64]map[string]string,\n\ttaxonomies map[uint64]map[string][]uint64,\n\tformatMap map[uint64]string) {\n\n\t// set Template\n\ttemplate, ok := metas[p.ID][\"_wp_page_template\"]\n\tif ok {\n\t\tp.Template = template\n\t}\n\n\tif p.Type == PostType {\n\t\t// set Tags\n\t\ttags, ok := taxonomies[p.ID][TagType]\n\t\tif ok {\n\t\t\tp.Tags = tags\n\t\t}\n\t\t// set Categories\n\t\tcategories, ok := taxonomies[p.ID][CategoryType]\n\t\tif ok {\n\t\t\tp.Categories = categories\n\t\t}\n\t\t// set Format\n\t\tformat, ok := formatMap[p.ID]\n\t\tif ok {\n\t\t\tp.Format = strings.Replace(format, \"post-format-\", \"\", -1)\n\t\t}\n\t}\n\n}", "func (c *Camera) ZoomOut() {\n\tc.zoom--\n\tc.Update()\n}", "func hookSetImageSize(e *evtx.GoEvtxMap) {\n\tvar path *evtx.GoEvtxPath\n\tvar modpath *evtx.GoEvtxPath\n\tswitch e.EventID() {\n\tcase 1:\n\t\tpath = &sysmonImage\n\t\tmodpath = &imSizePath\n\tdefault:\n\t\tpath = &sysmonImageLoaded\n\t\tmodpath = &imLoadedSizePath\n\t}\n\tif image, err := e.GetString(path); err == nil {\n\t\tif fsutil.IsFile(image) {\n\t\t\tif stat, err := os.Stat(image); err == nil {\n\t\t\t\te.Set(modpath, stat.Size())\n\t\t\t}\n\t\t}\n\t}\n}", "func (ps PostStorage) SetPost(ctx sdk.Context, postInfo *Post) {\n\tstore := ctx.KVStore(ps.key)\n\tinfoByte := ps.cdc.MustMarshalBinaryLengthPrefixed(*postInfo)\n\tstore.Set(GetPostInfoKey(linotypes.GetPermlink(postInfo.Author, postInfo.PostID)), infoByte)\n}", "func (g *Gravatar) SetSize(size int) {\n\tg.size = size\n}", "func (c *CseSiterestrictListCall) ImgSize(imgSize string) *CseSiterestrictListCall {\n\tc.urlParams_.Set(\"imgSize\", imgSize)\n\treturn c\n}", "func SetScreenSize(w, h float32) {\n\tscreen.SetRealSize(w, h)\n}", "func downsamplePostImage(url string, currentStatus, id int, c chan DownsampleResult) {\n\tprf(\"Downsampling image #%d status %d urls %s\\n\", id, currentStatus, url)\n\n\tassert(image_DownsampleError <= currentStatus && currentStatus <= image_DownsampleVersionTarget)\n\n\t//image_Unprocessed\t\t= 0\n\t//image_Downsampled\t\t= 1 // 125 x 75\n\t//image_DownsampledV2 = 2 // NOTE: THIS SHOULD BE THE NEW SIZE! a - 160 x 116 - thumbnail\n\t// // AND b - 160 x 150\n\t//image_DownsampledV3 // V3 += LARGE THUMBNAIL c - 570 x [preserve aspect ratio]\n\t//image_DownsampleError\t= -1\n\n\tbytes, err := downloadImage(url)\n\tif err != nil {\n\t\tprf(\" ERR downsampleImage - could not download image because: %s\", err.Error())\n\t\tc <- DownsampleResult{id, url, err}\n\t\treturn\n\t}\n\n\tif currentStatus < image_DownsampledV2 {\n\t\t// Small thumbnail - a\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"a\", \"jpeg\", 160, 116)\n\t\tif err != nil {\n\t\t\tprVal(\"# A downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t\t// Small thumbnail - b\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"b\", \"jpeg\", 160, 150)\n\t\tif err != nil {\n\t\t\tprVal(\"# B downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tif currentStatus < image_DownsampledV3 {\n\t\t// Large Thumbnail - c\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"c\", \"jpeg\", 570, -1)\n\t\tif err != nil {\n\t\t\tprVal(\"# C downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tprf(\"Result for #%d image %s: Success\\n\", id, url)\n\tc <- DownsampleResult{id, url, err}\n\treturn\n}", "func (st *Settings) SetMaxFrameSize(size uint32) {\n\tst.frameSize = size\n}", "func (st *Settings) SetMaxFrameSize(size uint32) {\n\tst.frameSize = size\n}", "func PostExpires(value string) PostOption {\n\treturn setMultipartField(\"Expires\", value)\n}", "func SetScreenSize(c *xgb.Conn, Window xproto.Window, Width uint16, Height uint16, MmWidth uint32, MmHeight uint32) SetScreenSizeCookie {\n\tc.ExtLock.RLock()\n\tdefer c.ExtLock.RUnlock()\n\tif _, ok := c.Extensions[\"RANDR\"]; !ok {\n\t\tpanic(\"Cannot issue request 'SetScreenSize' using the uninitialized extension 'RANDR'. randr.Init(connObj) must be called first.\")\n\t}\n\tcookie := c.NewCookie(false, false)\n\tc.NewRequest(setScreenSizeRequest(c, Window, Width, Height, MmWidth, MmHeight), cookie)\n\treturn SetScreenSizeCookie{cookie}\n}", "func (b *ImageButton) SetFontSize(size float64) {\n\n\tif b.label != nil {\n\t\tb.label.SetFontSize(size)\n\t\tb.recalc()\n\t}\n}", "func (p *Panorama) ResetZoom() {\n\tswitch p.viewMode {\n\tcase core.ViewFixed:\n\t\tp.resolution[p.viewMode] = defaultFixedResolution\n\tcase core.ViewCentered:\n\t\tp.resolution[p.viewMode] = defaultCenteredResolution\n\t}\n\tp.updateFrequencyRange()\n}", "func (v *View) Resize(w, h int) {\n\t// Always include 1 line for the command line at the bottom\n\th--\n\tv.width = int(float32(w) * float32(v.widthPercent) / 100)\n\t// We subtract 1 for the statusline\n\tv.height = int(float32(h)*float32(v.heightPercent)/100) - 1\n}", "func (c *Camera) SetOrtho(view image.Rectangle, near, far float64) {\n\tw := float64(view.Dx())\n\tw = float64(int((w / 2.0)) * 2)\n\th := float64(view.Dy())\n\th = float64(int((h / 2.0)) * 2)\n\tm := lmath.Mat4Ortho(0, w, 0, h, near, far)\n\tc.Projection = ConvertMat4(m)\n}", "func (st *Settings) SetMaxWindowSize(size uint32) {\n\tst.windowSize = size\n}", "func (st *Settings) SetMaxWindowSize(size uint32) {\n\tst.windowSize = size\n}", "func (w *Window) SetSize(width, height int) {\n\tif w.closed {\n\t\treturn\n\t}\n\n\tw.width, w.height = width, height\n\tif w.lockedSize {\n\t\tw.updateSizeHints()\n\t}\n\tw.win.Resize(width, height)\n\treturn\n}", "func (gau *GithubAssetUpdate) SetSize(i int64) *GithubAssetUpdate {\n\tgau.mutation.ResetSize()\n\tgau.mutation.SetSize(i)\n\treturn gau\n}", "func (h *HexWidget) SetSize(s fyne.Size) {\n\th.size = s\n\th.Refresh()\n}", "func (c *UPHostClient) NewModifyPHostImageInfoRequest() *ModifyPHostImageInfoRequest {\n\treq := &ModifyPHostImageInfoRequest{}\n\n\t// setup request with client config\n\tc.Client.SetupRequest(req)\n\n\t// setup retryable with default retry policy (retry for non-create action and common error)\n\treq.SetRetryable(true)\n\treturn req\n}", "func (s *Dynamic) SetSize(n int64) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.size = n\n\treturn nil\n}", "func (postProcessor *PostProcessor) Configure(settings ...interface{}) (err error) {\n\tif len(settings) == 0 {\n\t\terr = fmt.Errorf(\"No settings\")\n\n\t\treturn\n\t}\n\n\t// Builder settings.\n\tpostProcessor.settings = &config.Settings{}\n\terr = confighelper.Decode(postProcessor.settings, &confighelper.DecodeOpts{\n\t\tInterpolate: true,\n\t\tInterpolateContext: &postProcessor.interpolationContext,\n\t}, settings...)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = postProcessor.settings.Validate()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpostProcessor.client = compute.NewClient(\n\t\tpostProcessor.settings.McpRegion,\n\t\tpostProcessor.settings.McpUser,\n\t\tpostProcessor.settings.McpPassword,\n\t)\n\tif os.Getenv(\"MCP_EXTENDED_LOGGING\") != \"\" {\n\t\tpostProcessor.client.EnableExtendedLogging()\n\t}\n\n\t// Configure post-processor execution logic.\n\tpostProcessor.runner = &multistep.BasicRunner{\n\t\tSteps: []multistep.Step{\n\t\t\t&steps.ResolveDatacenter{\n\t\t\t\tDatacenterID: postProcessor.settings.DatacenterID,\n\t\t\t\tAsTarget: true,\n\t\t\t},\n\t\t\t&steps.CheckTargetImage{\n\t\t\t\tTargetImage: postProcessor.settings.TargetImageName,\n\t\t\t},\n\t\t\t&steps.ConvertVMXToOVF{\n\t\t\t\tPackageName: postProcessor.settings.OVFPackagePrefix,\n\t\t\t\tOutputDir: \"\", // Create a new use new temporary directory\n\t\t\t\tCleanupOVF: true, // Delete once post-processor is done.\n\t\t\t\tDiskCompression: 5, // Hard-coded for now\n\t\t\t},\n\t\t\t&steps.UploadOVFPackage{},\n\t\t\t&steps.ImportCustomerImage{\n\t\t\t\tTargetImageName: postProcessor.settings.TargetImageName,\n\t\t\t\tDatacenterID: postProcessor.settings.DatacenterID,\n\t\t\t\tOVFPackagePrefix: postProcessor.settings.OVFPackagePrefix,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn nil\n}", "func (db *DB) PostView(ddoc, view string, result interface{}, opts Options, payload Payload) error {\n\tddoc = strings.Replace(ddoc, \"_design/\", \"\", 1)\n\tpath, err := optpath(opts, viewJsonKeys, db.name, \"_design\", ddoc, \"_view\", view)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjson, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbody := bytes.NewReader(json)\n\tresp, err := db.request(db.ctx, \"POST\", path, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn readBody(resp, &result)\n}", "func (wg *WidgetImplement) SetFixedSize(w, h int) {\n\twg.fixedW = w\n\twg.fixedH = h\n}", "func (s *MultipassServer) TargetSize(ctx context.Context, request *apigrpc.NodeGroupServiceRequest) (*apigrpc.TargetSizeReply, error) {\n\tglog.V(5).Infof(\"Call server TargetSize: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\tnodeGroup := s.Groups[request.GetNodeGroupID()]\n\n\tif nodeGroup == nil {\n\t\tglog.Errorf(errNodeGroupNotFound, request.GetNodeGroupID())\n\n\t\treturn &apigrpc.TargetSizeReply{\n\t\t\tResponse: &apigrpc.TargetSizeReply_Error{\n\t\t\t\tError: &apigrpc.Error{\n\t\t\t\t\tCode: cloudProviderError,\n\t\t\t\t\tReason: fmt.Sprintf(errNodeGroupNotFound, request.GetNodeGroupID()),\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn &apigrpc.TargetSizeReply{\n\t\tResponse: &apigrpc.TargetSizeReply_TargetSize{\n\t\t\tTargetSize: int32(nodeGroup.targetSize()),\n\t\t},\n\t}, nil\n}", "func (m *ComanagedDevicesItemResizeCloudPcRequestBuilder) Post(ctx context.Context, body ComanagedDevicesItemResizeCloudPcPostRequestBodyable, requestConfiguration *ComanagedDevicesItemResizeCloudPcRequestBuilderPostRequestConfiguration)(error) {\n requestInfo, err := m.ToPostRequestInformation(ctx, body, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (dw *DrawingWand) SetViewbox(x1, y1, x2, y2 uint) {\n\tC.MagickDrawSetViewbox(dw.dw, C.ulong(x1), C.ulong(y1), C.ulong(x2), C.ulong(y2))\n}", "func (win *Window) SetDefaultSize(width, height int) {\n\twin.Candy().Guify(\"gtk_window_set_default_size\", win, width, height)\n}", "func (u *GithubGistUpsertOne) SetSize(v int64) *GithubGistUpsertOne {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.SetSize(v)\n\t})\n}", "func (s *Server) SetView(view *gview.View) {\n\ts.config.View = view\n}", "func (c *ProjectsLocationsOsPolicyAssignmentsListRevisionsCall) PageSize(pageSize int64) *ProjectsLocationsOsPolicyAssignmentsListRevisionsCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}", "func SetSize(fd uintptr, size TerminalSize) error {\n\treturn term.SetWinsize(fd, &term.Winsize{Height: size.Height, Width: size.Width})\n}", "func PostCacheControl(value string) PostOption {\n\treturn setMultipartField(\"Cache-Control\", value)\n}", "func (d *DataPacket) SetPreviewData(value bool) {\n\td.setOptionsBit(7, value)\n}", "func (v *Viewport) SetDimensions(x, y, width, height int) {\n\tv.x = int32(x)\n\tv.y = int32(y)\n\tv.width = int32(width)\n\tv.height = int32(height)\n}", "func (i *Image) CreatePreview() error {\r\n\t//max X and Y image dimension for previews\r\n\tconst maxX = 175\r\n\tconst maxY = 200\r\n\r\n\tprts := strings.SplitAfter(i.URL, \"/uploads/\")\r\n\tif len(prts) != 2 {\r\n\t\treturn fmt.Errorf(\"Wrong number of URL splits\")\r\n\t}\r\n\tparts := strings.Split(prts[1], \"/\")\r\n\trelPath := \"\"\r\n\tfor i := 0; i < len(parts)-1; i++ {\r\n\t\trelPath = path.Join(relPath, parts[i])\r\n\t}\r\n\t//filename\r\n\tfname := parts[len(parts)-1]\r\n\t//original image folder\r\n\tsrcPath := path.Join(config.UploadsPath(), relPath)\r\n\t//preview folder\r\n\tpreviewPath := path.Join(config.UploadsPath(), relPath, \"previews\")\r\n\tif err := os.MkdirAll(previewPath, 0755); err != nil {\r\n\t\treturn err\r\n\t}\r\n\tfile, err := os.Open(filepath.Join(srcPath, fname))\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tdefer file.Close()\r\n\r\n\timg, err := decodeImage(file)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\timg = resize.Thumbnail(maxX, maxY, img, resize.Lanczos3)\r\n\tbounds := img.Bounds()\r\n\toffset := image.Pt((maxX-bounds.Dx())/2, (maxY-bounds.Dy())/2)\r\n\tb := image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: maxX, Y: maxY}}\r\n\tm := image.NewRGBA(b)\r\n\tdraw.Draw(m, b, image.NewUniform(color.RGBA{255, 255, 255, 255}), image.ZP, draw.Src)\r\n\tdraw.Draw(m, bounds.Add(offset), img, image.ZP, draw.Over)\r\n\r\n\tdst, err := os.Create(path.Join(previewPath, fname))\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tdefer dst.Close()\r\n\tif err := jpeg.Encode(dst, m, &jpeg.Options{Quality: 80}); err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\trelURL := strings.ReplaceAll(relPath, string(filepath.Separator), \"/\")\r\n\tif len(relURL) > 0 {\r\n\t\trelURL = fmt.Sprintf(\"%s/previews/%s\", relURL, fname)\r\n\t} else {\r\n\t\trelURL = fmt.Sprintf(\"previews/%s\", fname)\r\n\t}\r\n\ti.PreviewURL = fmt.Sprintf(\"/public/uploads/%s\", relURL)\r\n\treturn nil\r\n}", "func (u *GithubGistUpsert) SetSize(v int64) *GithubGistUpsert {\n\tu.Set(githubgist.FieldSize, v)\n\treturn u\n}", "func (fpsc *FloorPlanScaleCreate) SetScaleInMeters(f float64) *FloorPlanScaleCreate {\n\tfpsc.mutation.SetScaleInMeters(f)\n\treturn fpsc\n}", "func (rr *OPT) SetUDPSize(size uint16) {\n\trr.Hdr.Class = size\n}", "func (sf *TWindow) SetMaximized(maximize bool) {\n\tif maximize == sf.maximized {\n\t\treturn\n\t}\n\n\tif maximize {\n\t\tx, y := sf.pos.Get()\n\t\tsf.posOrig.X().Set(x)\n\t\tsf.posOrig.Y().Set(y)\n\t\tsf.origWidth, sf.origHeight = sf.Size()\n\t\tsf.maximized = true\n\t\tsf.SetPos(0, 0)\n\t\twidth, height := ScreenSize()\n\t\tsf.SetSize(width, height)\n\t} else {\n\t\tsf.maximized = false\n\t\tsf.SetPos(sf.posOrig.GetX(), sf.posOrig.GetY())\n\t\tsf.SetSize(sf.origWidth, sf.origHeight)\n\t}\n\tsf.ResizeChildren()\n\tsf.PlaceChildren()\n}", "func (gauo *GithubAssetUpdateOne) SetSize(i int64) *GithubAssetUpdateOne {\n\tgauo.mutation.ResetSize()\n\tgauo.mutation.SetSize(i)\n\treturn gauo\n}", "func (c *Camera) SetPerspective(angle, ratio, zNear, zFar float32) {\n\tglm.PerspectiveIn(angle, ratio, zNear, zFar, &c.Projection)\n}", "func (af *filtBase) SetStepSize(mu float64) error {\n\tvar err error\n\taf.mu, err = af.checkFloatParam(mu, af.muMin, af.muMax, \"mu\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *CseListCall) ImgSize(imgSize string) *CseListCall {\n\tc.urlParams_.Set(\"imgSize\", imgSize)\n\treturn c\n}", "func (g *getRatesFilter) SetPageSize(size int) *getRatesFilter {\n\t(*g)[\"page[size]\"] = strconv.Itoa(size)\n\treturn g\n}", "func (m *Main) SetView(view webview.WebView) {\n\tm.w = view\n}", "func (o *InlineResponse200115) SetPostId(v string) {\n\to.PostId = &v\n}", "func (s *Sprite) Zoom(length float64) DrawingBuilder {\n\tif s.op == nil {\n\t\ts.err = errors.New(\"add a &ebiten.DrawImageOptions{} to s.op\")\n\t\treturn s\n\t}\n\ts.scale += length\n\ts.Width += length\n\ts.Height += length\n\n\ts.op.GeoM.Scale(float64(s.scale), float64(s.scale))\n\treturn s\n}", "func SetMaxMemory(maxMemory int64) {\n\tmaxMemoryForMultipartForm = maxMemory\n}", "func (m *MetricsProvider) OutboxPostTime(value time.Duration) {\n}", "func (n *Node) SetTreeSize(ctx context.Context, ts uint64) (err error) {\n\treturn n.SetXattrString(ctx, prefixes.TreesizeAttr, strconv.FormatUint(ts, 10))\n}", "func (c *OrganizationsSecurityProfilesListRevisionsCall) PageSize(pageSize int64) *OrganizationsSecurityProfilesListRevisionsCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}", "func (u *GithubGistUpsert) UpdateSize() *GithubGistUpsert {\n\tu.SetExcluded(githubgist.FieldSize)\n\treturn u\n}", "func (d *Data) setResolution(uuid dvid.UUID, jsonBytes []byte) error {\n\tconfig := make(dvid.NdFloat32, 3)\n\tif err := json.Unmarshal(jsonBytes, &config); err != nil {\n\t\treturn err\n\t}\n\td.Properties.VoxelSize = config\n\treturn datastore.SaveDataByUUID(uuid, d)\n}", "func (b *blogsQueryBuilder) SetTopPost(_topPost *Post) error {\n\tif b.err != nil {\n\t\treturn b.err\n\t}\n\trelation, err := NRN_Blogs.Model.RelationByIndex(4)\n\tif err != nil {\n\t\treturn errors.Wrapf(mapping.ErrInternal, \"getting 'TopPost' relation by index for model 'Blog' failed: %v\", err)\n\t}\n\treturn b.builder.SetRelations(relation, _topPost)\n}", "func NewImageSpecSize(x, y, chans int, format TypeDesc) *ImageSpec {\n\tspec := C.ImageSpec_New_Size(C.int(x), C.int(y), C.int(chans), (C.TypeDesc)(format))\n\treturn newImageSpec(spec)\n}" ]
[ "0.6737561", "0.62523794", "0.6224132", "0.5630493", "0.5371186", "0.5294629", "0.49871954", "0.49389657", "0.48399967", "0.47075906", "0.4678444", "0.46008775", "0.4587406", "0.44018033", "0.4371223", "0.43571287", "0.43469974", "0.43336517", "0.43305343", "0.43261597", "0.43258822", "0.43241102", "0.43184796", "0.4312631", "0.43096754", "0.42847577", "0.4235014", "0.42307195", "0.42197484", "0.4210126", "0.4200299", "0.41870865", "0.41870865", "0.4169747", "0.4166673", "0.41074073", "0.40980485", "0.4091124", "0.4081013", "0.4080681", "0.40743127", "0.4071958", "0.4071271", "0.40525088", "0.40516555", "0.40456778", "0.39969155", "0.3996888", "0.3994175", "0.3988299", "0.3934771", "0.3934771", "0.39320266", "0.39315504", "0.39314058", "0.39069614", "0.39044768", "0.3901075", "0.38936666", "0.38936666", "0.38895893", "0.38884574", "0.38841748", "0.38839033", "0.38810992", "0.3877865", "0.38772735", "0.38729548", "0.38695288", "0.38604465", "0.38581142", "0.38561675", "0.38463968", "0.38226038", "0.3812271", "0.38115478", "0.38102368", "0.38057154", "0.38045424", "0.38002312", "0.3793813", "0.37893364", "0.3781833", "0.37698135", "0.37637335", "0.37607306", "0.37495694", "0.37488216", "0.37473297", "0.37461674", "0.37460148", "0.3735061", "0.37293425", "0.37247005", "0.37213346", "0.37202173", "0.37190607", "0.37174165", "0.37139615", "0.37137666" ]
0.83650637
0
GetPostviewImageSize obtains the current Post View Image size from the camera: The possible options are: "2M" a smaller preview, usually 2Megpixels in size, sometimes not camera dependant "Original" the size of the image taken
GetPostviewImageSize получает текущий размер изображения Post View с камеры: возможные варианты: "2M" — более мелкий предварительный просмотр, обычно размером 2 мегапикселя, иногда не зависящий от камеры "Original" — размер изображения, которое было снято
func (c *Camera) GetPostviewImageSize() (size string, err error) { resp, err := c.newRequest(endpoints.Camera, "getPostviewImageSize").Do() if err != nil { return } if len(resp.Result) > 0 { err = json.Unmarshal(resp.Result[0], &size) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Camera) GetSupportedPostviewImageSize() (sizes []string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getSupportedPostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) > 0 {\n\t\terr = json.Unmarshal(resp.Result[0], &sizes)\n\t}\n\n\treturn\n}", "func (c *Camera) GetAvailablePostviewImageSize() (current string, available []string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getAvailablePostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) >= 1 {\n\t\t// Current size\n\t\tif err := json.Unmarshal(resp.Result[0], &current); err != nil {\n\t\t\treturn current, available, err\n\t\t}\n\n\t\t// Available sizes\n\t\tif err := json.Unmarshal(resp.Result[1], &available); err != nil {\n\t\t\treturn current, available, err\n\t\t}\n\t}\n\n\treturn\n}", "func (c *Camera) SetPostviewImageSize(size PostViewSize) (err error) {\n\t_, err = c.newRequest(endpoints.Camera, \"setPostviewImageSize\", size).Do()\n\treturn\n}", "func getOriginalSizeUrl(flickrOauth FlickrOAuth, photo Photo) (string, string) {\n\n\tif photo.Media == \"photo\" {\n\t\treturn photo.OriginalUrl, \"\"\n\t}\n\n\textras := map[string]string{\"photo_id\": photo.Id}\n\n\tvar err error\n\tvar body []byte\n\n\tbody, err = makeGetRequest(func() string { return generateOAuthUrl(apiBaseUrl, \"flickr.photos.getSizes\", flickrOauth, extras) })\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresponse := PhotoSizeResponse{}\n\terr = xml.Unmarshal(body, &response)\n\tif err != nil {\n\t\tlogMessage(\"Could not unmarshal body, check logs for body detail.\", true)\n\t\tlogMessage(string(body), false)\n\t\treturn \"\", \"\"\n\t}\n\n\tphotoUrl := \"\"\n\tvideoUrl := \"\"\n\tfor _, v := range response.SizesContainer.Sizes {\n\t\tif v.Label == \"Original\" {\n\t\t\tphotoUrl = v.Url\n\t\t}\n\n\t\tif v.Label == \"Video Original\" {\n\t\t\tvideoUrl = v.Url\n\t\t}\n\t}\n\n\treturn photoUrl, videoUrl\n}", "func (r *MachinePoolsListServerRequest) GetSize() (value int, ok bool) {\n\tok = r != nil && r.size != nil\n\tif ok {\n\t\tvalue = *r.size\n\t}\n\treturn\n}", "func (m *wasiSnapshotPreview1Impl) argsSizesGet() (r0 wasiSize, r1 wasiSize, err wasiErrno) {\n\tsize := 0\n\tfor _, s := range m.args {\n\t\tsize += len(s) + 1\n\t}\n\treturn wasiSize(len(m.args)), wasiSize(size), wasiErrnoSuccess\n}", "func (canvas *Canvas) Size() (width, height Unit) {\n\tmbox := canvas.page.MediaBox\n\treturn mbox.Dx(), mbox.Dy()\n}", "func (m *Manager) GetImageSize(hash string) (int64, error) {\n\tpath := filepath.Join(m.Options.Directory, hash)\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to locate image path: %v\", err)\n\t}\n\n\t// FIXME need a real way to do this\n\treturn 0, nil\n}", "func (size *BitmapSize) Size() int64 {\n\treturn int64(size.handle.size)\n}", "func (image *JPGImage) GetFileSize() uint64 {\n\treturn uint64(len(image.data))\n}", "func (is ImageSurface) Size() Point {\n\treturn Point{float64(is.width), float64(is.height)}\n}", "func (o GetReposRepoTagOutput) ImageSize() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetReposRepoTag) int { return v.ImageSize }).(pulumi.IntOutput)\n}", "func (hmd *Hmd) GetFovTextureSize(eye EyeType, fov FovPort, pixelsPerDisplayPixel float32) Sizei {\n\tvar cFov C.ovrFovPort\n\tcFov.DownTan = C.float(fov.DownTan)\n\tcFov.LeftTan = C.float(fov.LeftTan)\n\tcFov.RightTan = C.float(fov.RightTan)\n\tcFov.UpTan = C.float(fov.UpTan)\n\treturn sizei(C.ovrHmd_GetFovTextureSize(hmd.cptr(), C.ovrEyeType(eye), cFov, C.float(pixelsPerDisplayPixel)))\n}", "func (r *MachinePoolsListResponse) GetSize() (value int, ok bool) {\n\tok = r != nil && r.size != nil\n\tif ok {\n\t\tvalue = *r.size\n\t}\n\treturn\n}", "func qr_decoder_set_image_size(p _QrDecoderHandle, width, height, depth, channel int) _QrDecoderHandle {\n\tv := C.qr_decoder_set_image_size(C.QrDecoderHandle(p),\n\t\tC.int(width), C.int(height), C.int(depth), C.int(channel),\n\t)\n\treturn _QrDecoderHandle(v)\n}", "func (me *Image) Size() util.Size {\n\tvar s util.Size\n\ts.Width = me.key.width\n\ts.Height = me.key.height\n\treturn s\n}", "func (a *PhonebookAccess1) GetFixedImageSize() (bool, error) {\n\tv, err := a.GetProperty(\"FixedImageSize\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v.Value().(bool), nil\n}", "func GetVMSize(vm *compute.VirtualMachine) (Vmsize compute.VirtualMachineSizeTypes) {\n\n\tVmsize = vm.VirtualMachineProperties.HardwareProfile.VMSize\n\treturn\n\n}", "func (r *Reader) Size() int64 {\n\treturn r.xml.ImageSize\n}", "func (c *Camera) SetImageSize(width int, height int) (err error) {\n\tc.imageWidth = width\n\tc.imageHeight = height\n\n\terr = c.Lens.setAspectRatio(float64(width) / float64(height))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.output = image.NewRGBA(image.Rect(0, 0, c.imageWidth, c.imageHeight))\n\treturn\n}", "func (g *GistFile) GetSize() int {\n\tif g == nil || g.Size == nil {\n\t\treturn 0\n\t}\n\treturn *g.Size\n}", "func (is ImageSize) Size() (width int, height int) {\n\tconst tokensWidthHeightCount = 2\n\n\tsizeTokens := strings.Split(string(is), \"x\")\n\tif len(sizeTokens) != tokensWidthHeightCount {\n\t\treturn 0, 0\n\t}\n\n\tvar err error\n\twidth, err = strconv.Atoi(sizeTokens[0])\n\tswitch {\n\tcase err != nil:\n\t\tfallthrough\n\tcase width <= 0:\n\t\treturn 0, 0\n\t}\n\n\theight, err = strconv.Atoi(sizeTokens[1])\n\tswitch {\n\tcase err != nil:\n\t\tfallthrough\n\tcase height <= 0:\n\t\treturn 0, 0\n\t}\n\n\treturn width, height\n}", "func (o *ViewSampleProject) GetImagePreview() string {\n\tif o == nil || o.ImagePreview == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ImagePreview\n}", "func (o *ARVRInterface) GetRenderTargetsize() gdnative.Vector2 {\n\t//log.Println(\"Calling ARVRInterface.GetRenderTargetsize()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ARVRInterface\", \"get_render_targetsize\")\n\n\t// Call the parent method.\n\t// Vector2\n\tretPtr := gdnative.NewEmptyVector2()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewVector2FromPointer(retPtr)\n\treturn ret\n}", "func (s *MultipassServer) TargetSize(ctx context.Context, request *apigrpc.NodeGroupServiceRequest) (*apigrpc.TargetSizeReply, error) {\n\tglog.V(5).Infof(\"Call server TargetSize: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\tnodeGroup := s.Groups[request.GetNodeGroupID()]\n\n\tif nodeGroup == nil {\n\t\tglog.Errorf(errNodeGroupNotFound, request.GetNodeGroupID())\n\n\t\treturn &apigrpc.TargetSizeReply{\n\t\t\tResponse: &apigrpc.TargetSizeReply_Error{\n\t\t\t\tError: &apigrpc.Error{\n\t\t\t\t\tCode: cloudProviderError,\n\t\t\t\t\tReason: fmt.Sprintf(errNodeGroupNotFound, request.GetNodeGroupID()),\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn &apigrpc.TargetSizeReply{\n\t\tResponse: &apigrpc.TargetSizeReply_TargetSize{\n\t\t\tTargetSize: int32(nodeGroup.targetSize()),\n\t\t},\n\t}, nil\n}", "func (this *Window) GetSize() Vector2u {\n\tsize := C.sfWindow_getSize(this.cptr)\n\treturn Vector2u{uint(size.x), uint(size.y)}\n}", "func GetSize() (width, heigth int) {\n\tjsObject := atom.Call(\"getSize\")\n\twidth = jsObject.Get(\"width\").Int()\n\theigth = jsObject.Get(\"heigth\").Int()\n\treturn\n}", "func (c Capture) RequestSize() int64 {\n\tif c.rr == nil {\n\t\treturn 0\n\t}\n\treturn c.rr.size\n}", "func (r *ReleaseAsset) GetSize() int {\n\tif r == nil || r.Size == nil {\n\t\treturn 0\n\t}\n\treturn *r.Size\n}", "func (c *Camera) ScreenSize() (int, int) {\n\treturn c.screenW, c.screenH\n}", "func getThumbnailSize(w, h int, size string) (newWidth, newHeight int) {\n\tvar thumbWidth int\n\tvar thumbHeight int\n\n\tswitch {\n\tcase size == \"op\":\n\t\tthumbWidth = config.Config.ThumbWidth\n\t\tthumbHeight = config.Config.ThumbHeight\n\tcase size == \"reply\":\n\t\tthumbWidth = config.Config.ThumbWidthReply\n\t\tthumbHeight = config.Config.ThumbHeightReply\n\tcase size == \"catalog\":\n\t\tthumbWidth = config.Config.ThumbWidthCatalog\n\t\tthumbHeight = config.Config.ThumbHeightCatalog\n\t}\n\tif w == h {\n\t\tnewWidth = thumbWidth\n\t\tnewHeight = thumbHeight\n\t} else {\n\t\tvar percent float32\n\t\tif w > h {\n\t\t\tpercent = float32(thumbWidth) / float32(w)\n\t\t} else {\n\t\t\tpercent = float32(thumbHeight) / float32(h)\n\t\t}\n\t\tnewWidth = int(float32(w) * percent)\n\t\tnewHeight = int(float32(h) * percent)\n\t}\n\treturn\n}", "func (o *ViewMetaPage) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}", "func (m *PrinterDefaults) GetMediaSize()(*string) {\n val, err := m.GetBackingStore().Get(\"mediaSize\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (r *SubscriptionsListServerRequest) GetSize() (value int, ok bool) {\n\tok = r != nil && r.size != nil\n\tif ok {\n\t\tvalue = *r.size\n\t}\n\treturn\n}", "func (s *AppsServiceOp) GetInstanceSize(ctx context.Context, slug string) (*AppInstanceSize, *Response, error) {\n\tpath := fmt.Sprintf(\"%s/tiers/instance_sizes/%s\", appsBasePath, slug)\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\troot := new(instanceSizeRoot)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn root.InstanceSize, resp, nil\n}", "func (m *wasiSnapshotPreview1Impl) environSizesGet() (r0 wasiSize, r1 wasiSize, err wasiErrno) {\n\tsize := 0\n\tfor _, s := range m.env {\n\t\tsize += len(s) + 1\n\t}\n\treturn wasiSize(len(m.env)), wasiSize(size), wasiErrnoSuccess\n}", "func (w *WebviewWindow) Size() (width int, height int) {\n\tif w.impl == nil {\n\t\treturn 0, 0\n\t}\n\treturn w.impl.size()\n}", "func GetSize() float64 {\n\toldScore := pastFourScore[0] + pastFourScore[1]\n\tnewScore := pastFourScore[2] + pastFourScore[3]\n\n\tdiff := newScore - oldScore\n\n\tif diff > 0.0 {\n\t\tsize := 600.0 + diff*60.0\n\t\tif size < 2000.0 {\n\t\t\treturn size\n\t\t}\n\t\treturn 2000.0\n\t}\n\n\tif diff > -5.0 && diff <= 0.0 {\n\t\treturn 100.0 + diff*18.0\n\t}\n\n\treturn 10.0\n}", "func (w *MainWindow) GetSize() (int, int) {\n\treturn w.glfwWindow.GetSize()\n}", "func (u UserResult) GetSize() int {\n\treturn u.size\n}", "func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}", "func (r *MachinePoolsListServerRequest) Size() int {\n\tif r != nil && r.size != nil {\n\t\treturn *r.size\n\t}\n\treturn 0\n}", "func (cfp *FsPool) GetSize(fileIndex int64) int64 {\n\treturn cfp.container.Files[fileIndex].Size\n}", "func (c *Canvas) Size() image.Point {\n\treturn c.buffer.Size()\n}", "func (m *BitPrecMat) Size() (w, h int) {\n\treturn m.w, m.h\n}", "func (r *Request) Size() int64 {\n\treturn r.request.ContentLength\n}", "func (vb *ViewBox2D) SizeRect() image.Rectangle {\n\treturn image.Rect(0, 0, vb.Size.X, vb.Size.Y)\n}", "func (v *View) Size() int64 { return v.data.Size() }", "func (snake *Snake) GetImageForSize(size int) *ebiten.Image {\n\n\timage := snake.image.images[int(size)]\n\n\t//this is inefficient, but should only be called\n\t//once for non-advanced snek ( it does not change size )\n\n\tif !snake.advanced {\n\t\tfmt.Println(\"im not advanced\")\n\t\timage.Fill(color.White)\n\t}\n\n\treturn image\n\n}", "func (n *FileEntry) GetSize() uint64 {\n\treturn n.size\n}", "func GetSizeInBytes(key string) uint { return viper.GetSizeInBytes(key) }", "func (info *ImageInfoType) Height() float64 {\n\treturn info.h / (info.scale * info.dpi / 72)\n}", "func GetRenderbufferDepthSize(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_DEPTH_SIZE, &params)\n\treturn params\n}", "func (this *RectangleShape) GetSize() (size Vector2f) {\n\tsize.fromC(C.sfRectangleShape_getSize(this.cptr))\n\treturn\n}", "func getImageDimensions(imagePath string) (int, int) {\n file, err := os.Open(imagePath)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%v\\n\", err)\n }\n defer file.Close()\n imageConfig, _, err := image.DecodeConfig(file)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%s: %v\\n\", imagePath, err)\n }\n return imageConfig.Width, imageConfig.Height\n}", "func (p *Picture) GetHeight() int {\r\n\treturn p.pixelHeight\r\n}", "func (o *FileversionFileversion) GetFileSize() int32 {\n\tif o == nil || o.FileSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.FileSize\n}", "func (i *Image) Size() (int, int) {\n\treturn i.image.Size()\n}", "func (tv *TextView) RenderSize() mat32.Vec2 {\n\tspc := tv.Sty.BoxSpace()\n\tif tv.Par == nil {\n\t\treturn mat32.Vec2Zero\n\t}\n\tparw := tv.ParentLayout()\n\tif parw == nil {\n\t\tlog.Printf(\"giv.TextView Programmer Error: A TextView MUST be located within a parent Layout object -- instead parent is %v at: %v\\n\", tv.Par.Type(), tv.PathUnique())\n\t\treturn mat32.Vec2Zero\n\t}\n\tparw.SetReRenderAnchor()\n\tpaloc := parw.LayData.AllocSizeOrig\n\tif !paloc.IsNil() {\n\t\t// fmt.Printf(\"paloc: %v, pvp: %v lineonoff: %v\\n\", paloc, parw.VpBBox, tv.LineNoOff)\n\t\ttv.RenderSz = paloc.Sub(parw.ExtraSize).SubScalar(spc * 2)\n\t\ttv.RenderSz.X -= spc // extra space\n\t\t// fmt.Printf(\"alloc rendersz: %v\\n\", tv.RenderSz)\n\t} else {\n\t\tsz := tv.LayData.AllocSizeOrig\n\t\tif sz.IsNil() {\n\t\t\tsz = tv.LayData.SizePrefOrMax()\n\t\t}\n\t\tif !sz.IsNil() {\n\t\t\tsz.SetSubScalar(2 * spc)\n\t\t}\n\t\ttv.RenderSz = sz\n\t\t// fmt.Printf(\"fallback rendersz: %v\\n\", tv.RenderSz)\n\t}\n\ttv.RenderSz.X -= tv.LineNoOff\n\t// fmt.Printf(\"rendersz: %v\\n\", tv.RenderSz)\n\treturn tv.RenderSz\n}", "func (x *GetPhotoSequenceRequest) GetView() PhotoView {\n\tif x != nil {\n\t\treturn x.View\n\t}\n\treturn PhotoView_BASIC\n}", "func (s *storageImageSource) Size() (int64, error) {\n\treturn s.getSize()\n}", "func (e *Input) SizeHint() image.Point {\n\treturn image.Point{10, 1}\n}", "func (c *CseSiterestrictListCall) ImgSize(imgSize string) *CseSiterestrictListCall {\n\tc.urlParams_.Set(\"imgSize\", imgSize)\n\treturn c\n}", "func (fe FileExtractor) Size() int {\n\treturn fe.size\n}", "func Size() (w int, h int) {\n\tw = goterm.Width()\n\th = goterm.Height()\n\treturn\n}", "func Size() (w int, h int) {\n\tw = goterm.Width()\n\th = goterm.Height()\n\treturn\n}", "func (o *JsonEnvironment) GetSize() string {\n\tif o == nil || o.Size == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Size\n}", "func GetDimensions(imageData io.Reader) (int, int, error) {\n\tcfg, _, err := image.DecodeConfig(imageData)\n\tif seeker, ok := imageData.(io.ReadSeeker); ok {\n\t\tdefer seeker.Seek(0, 0)\n\t}\n\treturn cfg.Width, cfg.Height, err\n}", "func (p *PdfiumImplementation) FPDFBitmap_GetHeight(request *requests.FPDFBitmap_GetHeight) (*responses.FPDFBitmap_GetHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetHeight{\n\t\tHeight: int(height),\n\t}, nil\n}", "func GetSize(f *os.File) (ws Size, err error) {\n\terr = ioctl(f.Fd(), unix.TIOCGWINSZ, uintptr(unsafe.Pointer(&ws)))\n\treturn\n}", "func DecodePhotoSize(buf *bin.Buffer) (PhotoSizeClass, error) {\n\tid, err := buf.PeekID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch id {\n\tcase PhotoSizeEmptyTypeID:\n\t\t// Decoding photoSizeEmpty#e17e23c.\n\t\tv := PhotoSizeEmpty{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoSizeTypeID:\n\t\t// Decoding photoSize#77bfb61b.\n\t\tv := PhotoSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoCachedSizeTypeID:\n\t\t// Decoding photoCachedSize#e9a734fa.\n\t\tv := PhotoCachedSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoStrippedSizeTypeID:\n\t\t// Decoding photoStrippedSize#e0b0bc2e.\n\t\tv := PhotoStrippedSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoSizeProgressiveTypeID:\n\t\t// Decoding photoSizeProgressive#5aa86a51.\n\t\tv := PhotoSizeProgressive{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoPathSizeTypeID:\n\t\t// Decoding photoPathSize#d8214d41.\n\t\tv := PhotoPathSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", bin.NewUnexpectedID(id))\n\t}\n}", "func GetHeight() int {\n\treturn viper.GetInt(FlagHeight)\n}", "func downsamplePostImage(url string, currentStatus, id int, c chan DownsampleResult) {\n\tprf(\"Downsampling image #%d status %d urls %s\\n\", id, currentStatus, url)\n\n\tassert(image_DownsampleError <= currentStatus && currentStatus <= image_DownsampleVersionTarget)\n\n\t//image_Unprocessed\t\t= 0\n\t//image_Downsampled\t\t= 1 // 125 x 75\n\t//image_DownsampledV2 = 2 // NOTE: THIS SHOULD BE THE NEW SIZE! a - 160 x 116 - thumbnail\n\t// // AND b - 160 x 150\n\t//image_DownsampledV3 // V3 += LARGE THUMBNAIL c - 570 x [preserve aspect ratio]\n\t//image_DownsampleError\t= -1\n\n\tbytes, err := downloadImage(url)\n\tif err != nil {\n\t\tprf(\" ERR downsampleImage - could not download image because: %s\", err.Error())\n\t\tc <- DownsampleResult{id, url, err}\n\t\treturn\n\t}\n\n\tif currentStatus < image_DownsampledV2 {\n\t\t// Small thumbnail - a\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"a\", \"jpeg\", 160, 116)\n\t\tif err != nil {\n\t\t\tprVal(\"# A downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t\t// Small thumbnail - b\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"b\", \"jpeg\", 160, 150)\n\t\tif err != nil {\n\t\t\tprVal(\"# B downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tif currentStatus < image_DownsampledV3 {\n\t\t// Large Thumbnail - c\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"c\", \"jpeg\", 570, -1)\n\t\tif err != nil {\n\t\t\tprVal(\"# C downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tprf(\"Result for #%d image %s: Success\\n\", id, url)\n\tc <- DownsampleResult{id, url, err}\n\treturn\n}", "func (m FileUploadItem) Size() int64 {\n\tf, err := os.Stat(m.path())\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn f.Size()\n}", "func (fi *fileInfo) Size() int64 {\n\treturn fi.size\n}", "func (i *UploadShrinker) Size() int64 {\n\treturn i.size\n}", "func (c *Configuration) GetRoutePostEncryptMTU() int {\n\tif c.encapEnabled {\n\t\tif c.postEncryptMTU == 0 {\n\t\t\treturn EthernetMTU - TunnelOverhead\n\t\t}\n\t\treturn c.postEncryptMTU\n\n\t}\n\treturn c.GetDeviceMTU()\n}", "func (e Event) GetResizeHeight() int {\n\treturn int(C.caca_get_event_resize_height(e.Ev))\n}", "func (o InstanceGroupManagerVersionResponseOutput) TargetSize() FixedOrPercentResponseOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersionResponse) FixedOrPercentResponse { return v.TargetSize }).(FixedOrPercentResponseOutput)\n}", "func GetSize(matches []logol.Match) int {\n\tstart := 0\n\tend := 0\n\tif len(matches) > 0 {\n\t\tstart = matches[0].Start\n\t\tend = matches[len(matches)-1].End\n\t}\n\treturn end - start\n}", "func (st *Settings) MaxFrameSize() uint32 {\n\treturn st.frameSize\n}", "func (st *Settings) MaxFrameSize() uint32 {\n\treturn st.frameSize\n}", "func (o *ObjectInfo) Size() int64 {\n\t_, _, size, err := processFileName(o.ObjectInfo.Remote())\n\tif err != nil {\n\t\tfs.Errorf(o, \"Could not get size for: %s\", o.ObjectInfo.Remote())\n\t\treturn -1\n\t}\n\tif size == -2 { // File is uncompressed\n\t\treturn o.ObjectInfo.Size()\n\t}\n\treturn size\n}", "func (gc *GceCache) GetMigTargetSize(ref GceRef) (int64, bool) {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\tsize, found := gc.migTargetSizeCache[ref]\n\tif found {\n\t\tklog.V(5).Infof(\"Target size cache hit for %s\", ref)\n\t}\n\treturn size, found\n}", "func (gc *GceCache) GetMigTargetSize(ref GceRef) (int64, bool) {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\tsize, found := gc.migTargetSizeCache[ref]\n\tif found {\n\t\tklog.V(5).Infof(\"Target size cache hit for %s\", ref)\n\t}\n\treturn size, found\n}", "func (o *DriveItemVersion) GetSize() int64 {\n\tif o == nil || o.Size == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Size\n}", "func (m *wasiSnapshotPreview1Impl) fdFilestatSetSize(pfd wasiFd, psize wasiFilesize) (err wasiErrno) {\n\tf, err := m.files.getFile(pfd, wasiRightsFdRead)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tif ferr := f.SetSize(psize); ferr != nil {\n\t\treturn fileErrno(ferr)\n\t}\n\treturn wasiErrnoSuccess\n}", "func (o ScalingConfigResponseOutput) InstanceSize() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScalingConfigResponse) string { return v.InstanceSize }).(pulumi.StringOutput)\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Size() pulumi.IntOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) int { return v.Size }).(pulumi.IntOutput)\n}", "func (o DashboardFreeFormLayoutScreenCanvasSizeOptionsOutput) OptimizedViewPortWidth() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DashboardFreeFormLayoutScreenCanvasSizeOptions) string { return v.OptimizedViewPortWidth }).(pulumi.StringOutput)\n}", "func (m *GGCRImage) Size() (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetSize(file string) (int64, error) {\n\tstat, err := os.Stat(realPath(file))\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn stat.Size(), nil\n}", "func (l PostingList) Size() int32 {\n\treturn l.n\n}", "func (m NoMDEntries) GetMDEntrySize() (v decimal.Decimal, err quickfix.MessageRejectError) {\n\tvar f field.MDEntrySizeField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func getUTMetaSize(data []byte) (\n\tutMetadata int, metadataSize int, err error) {\n\n\tv, err := Decode(data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdict, ok := v.(map[string]interface{})\n\tif !ok {\n\t\terr = errors.New(\"invalid dict\")\n\t\treturn\n\t}\n\n\tif err = parseKeys(\n\t\tdict, [][]string{{\"metadata_size\", \"int\"}, {\"m\", \"map\"}}); err != nil {\n\t\treturn\n\t}\n\n\tm := dict[\"m\"].(map[string]interface{})\n\tif err = parseKey(m, \"ut_metadata\", \"int\"); err != nil {\n\t\treturn\n\t}\n\n\tutMetadata = m[\"ut_metadata\"].(int)\n\tmetadataSize = dict[\"metadata_size\"].(int)\n\n\tif metadataSize > MaxMetadataSize {\n\t\terr = errors.New(\"metadata_size too long\")\n\t}\n\treturn\n}", "func (t *Text) Size() image.Point { return t.size }", "func getFileSize(filePath string) int64 {\n\tfileInfo, _ := os.Stat(filePath)\n\treturn fileInfo.Size()\n}", "func (interp Interpolator) SizeHint() int { return surge.SizeHint(interp.basis) }", "func (tbd *TermboxDriver) Size() (width int, height int) {\n\treturn tbd.width, tbd.height\n}", "func (size *BitmapSize) Height() int16 {\n\treturn int16(size.handle.height)\n}" ]
[ "0.7458114", "0.69781554", "0.61268085", "0.48669896", "0.48574117", "0.47957015", "0.47445032", "0.47146225", "0.47024658", "0.46297923", "0.46039", "0.45731974", "0.45198196", "0.4490976", "0.44749692", "0.44173935", "0.44143057", "0.44099662", "0.44064572", "0.439179", "0.4387702", "0.4379497", "0.4378113", "0.4365362", "0.43605274", "0.43580112", "0.43565622", "0.43450737", "0.43190277", "0.4306943", "0.42957604", "0.4294795", "0.42919397", "0.42824665", "0.42773166", "0.42659733", "0.4262675", "0.42600873", "0.4259802", "0.42530787", "0.42515364", "0.4235656", "0.42259732", "0.4222378", "0.42171827", "0.42096666", "0.41868982", "0.41807166", "0.4177666", "0.41745326", "0.4171102", "0.41700765", "0.41584894", "0.41430533", "0.4136481", "0.4113359", "0.41077065", "0.41076443", "0.41072205", "0.4106888", "0.41063505", "0.40965903", "0.4095374", "0.40917408", "0.40862456", "0.40862456", "0.40828118", "0.40775844", "0.40761197", "0.4075942", "0.4074701", "0.4072464", "0.40685418", "0.40651035", "0.40644372", "0.40595847", "0.4051886", "0.40410757", "0.40406087", "0.40368733", "0.40250632", "0.40250632", "0.40247187", "0.40203094", "0.40203094", "0.4020085", "0.40175578", "0.40149355", "0.40002766", "0.39973736", "0.3993742", "0.39921772", "0.3988855", "0.39872485", "0.3980797", "0.39779136", "0.3977745", "0.397638", "0.39701518", "0.39681846" ]
0.8124131
0
GetSupportedPostviewImageSize obtains the supported Post View Image sizes from the camera
GetSupportedPostviewImageSize получает поддерживаемые размеры изображения Post View с камеры
func (c *Camera) GetSupportedPostviewImageSize() (sizes []string, err error) { resp, err := c.newRequest(endpoints.Camera, "getSupportedPostviewImageSize").Do() if err != nil { return } if len(resp.Result) > 0 { err = json.Unmarshal(resp.Result[0], &sizes) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Camera) GetAvailablePostviewImageSize() (current string, available []string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getAvailablePostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) >= 1 {\n\t\t// Current size\n\t\tif err := json.Unmarshal(resp.Result[0], &current); err != nil {\n\t\t\treturn current, available, err\n\t\t}\n\n\t\t// Available sizes\n\t\tif err := json.Unmarshal(resp.Result[1], &available); err != nil {\n\t\t\treturn current, available, err\n\t\t}\n\t}\n\n\treturn\n}", "func (c *Camera) GetPostviewImageSize() (size string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getPostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) > 0 {\n\t\terr = json.Unmarshal(resp.Result[0], &size)\n\t}\n\n\treturn\n}", "func (c *Camera) SetPostviewImageSize(size PostViewSize) (err error) {\n\t_, err = c.newRequest(endpoints.Camera, \"setPostviewImageSize\", size).Do()\n\treturn\n}", "func (m *wasiSnapshotPreview1Impl) argsSizesGet() (r0 wasiSize, r1 wasiSize, err wasiErrno) {\n\tsize := 0\n\tfor _, s := range m.args {\n\t\tsize += len(s) + 1\n\t}\n\treturn wasiSize(len(m.args)), wasiSize(size), wasiErrnoSuccess\n}", "func (a *PhonebookAccess1) GetFixedImageSize() (bool, error) {\n\tv, err := a.GetProperty(\"FixedImageSize\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v.Value().(bool), nil\n}", "func qr_decoder_set_image_size(p _QrDecoderHandle, width, height, depth, channel int) _QrDecoderHandle {\n\tv := C.qr_decoder_set_image_size(C.QrDecoderHandle(p),\n\t\tC.int(width), C.int(height), C.int(depth), C.int(channel),\n\t)\n\treturn _QrDecoderHandle(v)\n}", "func (fc *FacebookClient) GetImageUrlsFromPostId(postId string) []ImageInfo {\n\turl := fmt.Sprintf(fc.attachmentUrl, postId) + \"?access_token=\" + fc.accessToken\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\tresp, err := client.Do(req)\n\n\t// TLS handshake timeout\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn make([]ImageInfo, 0)\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\n\t// Unmarshall response\n\tatt := new(AttachmentResponse)\n\tjson.Unmarshal(body, &att)\n\tret := make([]ImageInfo, 0)\n\tfor _, data := range att.Data {\n\t\t// Since missing values get unmarshalled into their type's 0'd value, make sure the src exists before we make an ImageInfo struct\n\t\tif len(data.Media.Image.Src) > 0 {\n\t\t\tinfo := ImageInfo{}\n\t\t\tinfo.Url = data.Media.Image.Src\n\t\t\tinfo.Id = data.Target.Id\n\t\t\tret = append(ret, info)\n\t\t}\n\t}\n\treturn ret\n}", "func (t *TargetBuilder) MaxImgSizes() []int {\n\tsz0 := t.bspPkg.FlashMap.Areas[flash.FLASH_AREA_NAME_IMAGE_0].Size\n\tsz1 := t.bspPkg.FlashMap.Areas[flash.FLASH_AREA_NAME_IMAGE_1].Size\n\ttrailerSz := t.bootTrailerSize()\n\n\treturn []int{\n\t\tsz0 - trailerSz,\n\t\tsz1 - trailerSz,\n\t}\n}", "func (m *wasiSnapshotPreview1Impl) environSizesGet() (r0 wasiSize, r1 wasiSize, err wasiErrno) {\n\tsize := 0\n\tfor _, s := range m.env {\n\t\tsize += len(s) + 1\n\t}\n\treturn wasiSize(len(m.env)), wasiSize(size), wasiErrnoSuccess\n}", "func PossibleImageSizeValues() []ImageSize {\n\treturn []ImageSize{\n\t\tImageSize512x512,\n\t\tImageSize1024x1024,\n\t\tImageSize256x256,\n\t}\n}", "func (is ImageSurface) Size() Point {\n\treturn Point{float64(is.width), float64(is.height)}\n}", "func (m *BitPrecMat) Size() (w, h int) {\n\treturn m.w, m.h\n}", "func (is ImageSize) Size() (width int, height int) {\n\tconst tokensWidthHeightCount = 2\n\n\tsizeTokens := strings.Split(string(is), \"x\")\n\tif len(sizeTokens) != tokensWidthHeightCount {\n\t\treturn 0, 0\n\t}\n\n\tvar err error\n\twidth, err = strconv.Atoi(sizeTokens[0])\n\tswitch {\n\tcase err != nil:\n\t\tfallthrough\n\tcase width <= 0:\n\t\treturn 0, 0\n\t}\n\n\theight, err = strconv.Atoi(sizeTokens[1])\n\tswitch {\n\tcase err != nil:\n\t\tfallthrough\n\tcase height <= 0:\n\t\treturn 0, 0\n\t}\n\n\treturn width, height\n}", "func (p *PdfiumImplementation) FPDFBitmap_GetHeight(request *requests.FPDFBitmap_GetHeight) (*responses.FPDFBitmap_GetHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetHeight{\n\t\tHeight: int(height),\n\t}, nil\n}", "func GetBlobSizesR(state kv.KVStoreReader, blobHash hashing.HashValue) *collections.ImmutableMap {\n\treturn collections.NewMapReadOnly(state, sizesMapName(blobHash))\n}", "func (c *Camera) ScreenSize() (int, int) {\n\treturn c.screenW, c.screenH\n}", "func (canvas *Canvas) Size() (width, height Unit) {\n\tmbox := canvas.page.MediaBox\n\treturn mbox.Dx(), mbox.Dy()\n}", "func (hmd *Hmd) GetFovTextureSize(eye EyeType, fov FovPort, pixelsPerDisplayPixel float32) Sizei {\n\tvar cFov C.ovrFovPort\n\tcFov.DownTan = C.float(fov.DownTan)\n\tcFov.LeftTan = C.float(fov.LeftTan)\n\tcFov.RightTan = C.float(fov.RightTan)\n\tcFov.UpTan = C.float(fov.UpTan)\n\treturn sizei(C.ovrHmd_GetFovTextureSize(hmd.cptr(), C.ovrEyeType(eye), cFov, C.float(pixelsPerDisplayPixel)))\n}", "func imgSetWidthHeight(camera int, width int, height int) int {\n\tlog.Printf(\"imgSetWidthHeight - camera:%d width:%d height:%d\", camera, width, height)\n\tvar f = mod.NewProc(\"img_set_wh\")\n\tret, _, _ := f.Call(uintptr(camera), uintptr(width), uintptr(height))\n\treturn int(ret) // retval is cameraID\n}", "func getOriginalSizeUrl(flickrOauth FlickrOAuth, photo Photo) (string, string) {\n\n\tif photo.Media == \"photo\" {\n\t\treturn photo.OriginalUrl, \"\"\n\t}\n\n\textras := map[string]string{\"photo_id\": photo.Id}\n\n\tvar err error\n\tvar body []byte\n\n\tbody, err = makeGetRequest(func() string { return generateOAuthUrl(apiBaseUrl, \"flickr.photos.getSizes\", flickrOauth, extras) })\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresponse := PhotoSizeResponse{}\n\terr = xml.Unmarshal(body, &response)\n\tif err != nil {\n\t\tlogMessage(\"Could not unmarshal body, check logs for body detail.\", true)\n\t\tlogMessage(string(body), false)\n\t\treturn \"\", \"\"\n\t}\n\n\tphotoUrl := \"\"\n\tvideoUrl := \"\"\n\tfor _, v := range response.SizesContainer.Sizes {\n\t\tif v.Label == \"Original\" {\n\t\t\tphotoUrl = v.Url\n\t\t}\n\n\t\tif v.Label == \"Video Original\" {\n\t\t\tvideoUrl = v.Url\n\t\t}\n\t}\n\n\treturn photoUrl, videoUrl\n}", "func GetRenderbufferDepthSize(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_DEPTH_SIZE, &params)\n\treturn params\n}", "func getImageDimensions(imagePath string) (int, int) {\n file, err := os.Open(imagePath)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%v\\n\", err)\n }\n defer file.Close()\n imageConfig, _, err := image.DecodeConfig(file)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%s: %v\\n\", imagePath, err)\n }\n return imageConfig.Width, imageConfig.Height\n}", "func (o ApplicationSpecRolloutplanOutput) TargetSize() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplan) *int { return v.TargetSize }).(pulumi.IntPtrOutput)\n}", "func (size *BitmapSize) Size() int64 {\n\treturn int64(size.handle.size)\n}", "func downsamplePostImage(url string, currentStatus, id int, c chan DownsampleResult) {\n\tprf(\"Downsampling image #%d status %d urls %s\\n\", id, currentStatus, url)\n\n\tassert(image_DownsampleError <= currentStatus && currentStatus <= image_DownsampleVersionTarget)\n\n\t//image_Unprocessed\t\t= 0\n\t//image_Downsampled\t\t= 1 // 125 x 75\n\t//image_DownsampledV2 = 2 // NOTE: THIS SHOULD BE THE NEW SIZE! a - 160 x 116 - thumbnail\n\t// // AND b - 160 x 150\n\t//image_DownsampledV3 // V3 += LARGE THUMBNAIL c - 570 x [preserve aspect ratio]\n\t//image_DownsampleError\t= -1\n\n\tbytes, err := downloadImage(url)\n\tif err != nil {\n\t\tprf(\" ERR downsampleImage - could not download image because: %s\", err.Error())\n\t\tc <- DownsampleResult{id, url, err}\n\t\treturn\n\t}\n\n\tif currentStatus < image_DownsampledV2 {\n\t\t// Small thumbnail - a\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"a\", \"jpeg\", 160, 116)\n\t\tif err != nil {\n\t\t\tprVal(\"# A downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t\t// Small thumbnail - b\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"b\", \"jpeg\", 160, 150)\n\t\tif err != nil {\n\t\t\tprVal(\"# B downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tif currentStatus < image_DownsampledV3 {\n\t\t// Large Thumbnail - c\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"c\", \"jpeg\", 570, -1)\n\t\tif err != nil {\n\t\t\tprVal(\"# C downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tprf(\"Result for #%d image %s: Success\\n\", id, url)\n\tc <- DownsampleResult{id, url, err}\n\treturn\n}", "func (w *WebviewWindow) Size() (width int, height int) {\n\tif w.impl == nil {\n\t\treturn 0, 0\n\t}\n\treturn w.impl.size()\n}", "func (m *MockImage) ValidateImageSize(width, height int) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ValidateImageSize\", width, height)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (r *MachinePoolsListServerRequest) GetSize() (value int, ok bool) {\n\tok = r != nil && r.size != nil\n\tif ok {\n\t\tvalue = *r.size\n\t}\n\treturn\n}", "func GetDimensions(imageData io.Reader) (int, int, error) {\n\tcfg, _, err := image.DecodeConfig(imageData)\n\tif seeker, ok := imageData.(io.ReadSeeker); ok {\n\t\tdefer seeker.Seek(0, 0)\n\t}\n\treturn cfg.Width, cfg.Height, err\n}", "func (o *ARVRInterface) GetRenderTargetsize() gdnative.Vector2 {\n\t//log.Println(\"Calling ARVRInterface.GetRenderTargetsize()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ARVRInterface\", \"get_render_targetsize\")\n\n\t// Call the parent method.\n\t// Vector2\n\tretPtr := gdnative.NewEmptyVector2()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewVector2FromPointer(retPtr)\n\treturn ret\n}", "func (s *MultipassServer) TargetSize(ctx context.Context, request *apigrpc.NodeGroupServiceRequest) (*apigrpc.TargetSizeReply, error) {\n\tglog.V(5).Infof(\"Call server TargetSize: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\tnodeGroup := s.Groups[request.GetNodeGroupID()]\n\n\tif nodeGroup == nil {\n\t\tglog.Errorf(errNodeGroupNotFound, request.GetNodeGroupID())\n\n\t\treturn &apigrpc.TargetSizeReply{\n\t\t\tResponse: &apigrpc.TargetSizeReply_Error{\n\t\t\t\tError: &apigrpc.Error{\n\t\t\t\t\tCode: cloudProviderError,\n\t\t\t\t\tReason: fmt.Sprintf(errNodeGroupNotFound, request.GetNodeGroupID()),\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn &apigrpc.TargetSizeReply{\n\t\tResponse: &apigrpc.TargetSizeReply_TargetSize{\n\t\t\tTargetSize: int32(nodeGroup.targetSize()),\n\t\t},\n\t}, nil\n}", "func GetVideoModeCount() int {\n\treturn int(C.freenect_get_video_mode_count())\n}", "func Images(ctx *model.Context, selectedPages types.IntSet) ([]map[int]model.Image, *ImageListMaxLengths, error) {\n\tpageNrs := []int{}\n\tfor k, v := range selectedPages {\n\t\tif !v {\n\t\t\tcontinue\n\t\t}\n\t\tpageNrs = append(pageNrs, k)\n\t}\n\tsort.Ints(pageNrs)\n\n\tmm := []map[int]model.Image{}\n\tvar (\n\t\tmaxLenObjNr, maxLenID, maxLenSize, maxLenFilters int\n\t)\n\n\tfor _, i := range pageNrs {\n\t\tm, err := ExtractPageImages(ctx, i, true)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif len(m) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, i := range m {\n\t\t\ts := strconv.Itoa(i.ObjNr)\n\t\t\tif len(s) > maxLenObjNr {\n\t\t\t\tmaxLenObjNr = len(s)\n\t\t\t}\n\t\t\tif len(i.Name) > maxLenID {\n\t\t\t\tmaxLenID = len(i.Name)\n\t\t\t}\n\t\t\tlenSize := len(types.ByteSize(i.Size).String())\n\t\t\tif lenSize > maxLenSize {\n\t\t\t\tmaxLenSize = lenSize\n\t\t\t}\n\t\t\tif len(i.Filter) > maxLenFilters {\n\t\t\t\tmaxLenFilters = len(i.Filter)\n\t\t\t}\n\t\t}\n\t\tmm = append(mm, m)\n\t}\n\n\tmaxLen := &ImageListMaxLengths{ObjNr: maxLenObjNr, ID: maxLenID, Size: maxLenSize, Filters: maxLenFilters}\n\n\treturn mm, maxLen, nil\n}", "func (o InstanceGroupManagerVersionResponseOutput) TargetSize() FixedOrPercentResponseOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersionResponse) FixedOrPercentResponse { return v.TargetSize }).(FixedOrPercentResponseOutput)\n}", "func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}", "func (o GoogleCloudRetailV2alphaProductResponseOutput) Sizes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaProductResponse) []string { return v.Sizes }).(pulumi.StringArrayOutput)\n}", "func (mtr *Msmsintprp5Metrics) Size() int {\n\tsz := 0\n\n\tsz += mtr.Read.Size()\n\n\tsz += mtr.Security.Size()\n\n\tsz += mtr.Decode.Size()\n\n\treturn sz\n}", "func (r PostNotSupported) Post(app *App, request *http.Request) (int, interface{}, error) {\n\treturn notSupported(POST)\n}", "func getThumbnailSize(w, h int, size string) (newWidth, newHeight int) {\n\tvar thumbWidth int\n\tvar thumbHeight int\n\n\tswitch {\n\tcase size == \"op\":\n\t\tthumbWidth = config.Config.ThumbWidth\n\t\tthumbHeight = config.Config.ThumbHeight\n\tcase size == \"reply\":\n\t\tthumbWidth = config.Config.ThumbWidthReply\n\t\tthumbHeight = config.Config.ThumbHeightReply\n\tcase size == \"catalog\":\n\t\tthumbWidth = config.Config.ThumbWidthCatalog\n\t\tthumbHeight = config.Config.ThumbHeightCatalog\n\t}\n\tif w == h {\n\t\tnewWidth = thumbWidth\n\t\tnewHeight = thumbHeight\n\t} else {\n\t\tvar percent float32\n\t\tif w > h {\n\t\t\tpercent = float32(thumbWidth) / float32(w)\n\t\t} else {\n\t\t\tpercent = float32(thumbHeight) / float32(h)\n\t\t}\n\t\tnewWidth = int(float32(w) * percent)\n\t\tnewHeight = int(float32(h) * percent)\n\t}\n\treturn\n}", "func (d *Data) GetSizeRange(v dvid.VersionID, minSize, maxSize uint64) (string, error) {\n\tstore, err := storage.MutableStore()\n\tif err != nil {\n\t\treturn \"{}\", fmt.Errorf(\"Data type imagesz had error initializing store: %v\\n\", err)\n\t}\n\n\t// Get the start/end keys for the size range.\n\tfirstKey := NewSizeLabelTKey(minSize, 0)\n\tvar upperBound uint64\n\tif maxSize != 0 {\n\t\tupperBound = maxSize\n\t} else {\n\t\tupperBound = math.MaxUint64\n\t}\n\tlastKey := NewSizeLabelTKey(upperBound, math.MaxUint64)\n\n\t// Grab all keys for this range in one sequential read.\n\tctx := datastore.NewVersionedCtx(d, v)\n\tkeys, err := store.KeysInRange(ctx, firstKey, lastKey)\n\tif err != nil {\n\t\treturn \"{}\", err\n\t}\n\n\t// Convert them to a JSON compatible structure.\n\tlabels := make([]uint64, len(keys))\n\tfor i, key := range keys {\n\t\tlabels[i], _, err = DecodeSizeLabelTKey(key)\n\t\tif err != nil {\n\t\t\treturn \"{}\", err\n\t\t}\n\t}\n\tm, err := json.Marshal(labels)\n\tif err != nil {\n\t\treturn \"{}\", nil\n\t}\n\treturn string(m), nil\n}", "func (o GetReposRepoTagOutput) ImageSize() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetReposRepoTag) int { return v.ImageSize }).(pulumi.IntOutput)\n}", "func (c *Camera) SetImageSize(width int, height int) (err error) {\n\tc.imageWidth = width\n\tc.imageHeight = height\n\n\terr = c.Lens.setAspectRatio(float64(width) / float64(height))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.output = image.NewRGBA(image.Rect(0, 0, c.imageWidth, c.imageHeight))\n\treturn\n}", "func (o *ViewMetaPage) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}", "func (o *ViewSampleProject) HasImagePreview() bool {\n\tif o != nil && o.ImagePreview != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r *MachinePoolsListResponse) GetSize() (value int, ok bool) {\n\tok = r != nil && r.size != nil\n\tif ok {\n\t\tvalue = *r.size\n\t}\n\treturn\n}", "func (r *Release) getPostRenderer() []string {\n\targs := []string{}\n\tif r.PostRenderer != \"\" {\n\t\targs = append(args, \"--post-renderer\", r.PostRenderer)\n\t}\n\treturn args\n}", "func (l PostingList) Size() int32 {\n\treturn l.n\n}", "func (d *Device) Size() (w, h int16) {\n\tif d.rotation == drivers.Rotation0 || d.rotation == drivers.Rotation180 {\n\t\treturn d.width, d.height\n\t}\n\treturn d.height, d.width\n}", "func (rb *ByProjectKeyImageSearchRequestBuilder) Post(body io.Reader) *ByProjectKeyImageSearchRequestMethodPost {\n\treturn &ByProjectKeyImageSearchRequestMethodPost{\n\t\tbody: body,\n\t\turl: fmt.Sprintf(\"/%s/image-search\", rb.projectKey),\n\t\tclient: rb.client,\n\t}\n}", "func (i *Image) Size() (int, int) {\n\treturn i.image.Size()\n}", "func verifyDimensions(t *testing.T, img image.Image, width, height int) {\n\tb := img.Bounds()\n\tw := b.Max.X - b.Min.X\n\th := b.Max.Y - b.Min.Y\n\n\tif w != width || h != height {\n\t\tt.Errorf(\"Merge() produced incorrect output size: %v w x %v h\\nexpected: %v w x %v h\", w, h, width, height)\n\t}\n}", "func (o InstanceGroupManagerVersionOutput) TargetSize() FixedOrPercentPtrOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersion) *FixedOrPercent { return v.TargetSize }).(FixedOrPercentPtrOutput)\n}", "func previewImage(ctx context.Context, log utils.DebugLabeler, src io.Reader, basename, contentType string) (res *PreviewRes, err error) {\n\tdefer func() {\n\t\t// decoding ico images can cause a panic, let's catch anything here.\n\t\t// https://github.com/biessek/golang-ico/issues/4\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Debug(ctx, \"Recovered %v\", r)\n\t\t\tres = nil\n\t\t\terr = fmt.Errorf(\"unable to preview image: %v\", r)\n\t\t}\n\t}()\n\tdefer log.Trace(ctx, &err, \"previewImage\")()\n\t// images.Decode in camlistore correctly handles exif orientation information.\n\tlog.Debug(ctx, \"previewImage: decoding image\")\n\timg, _, err := images.Decode(src, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth, height := previewDimensions(img.Bounds())\n\n\tlog.Debug(ctx, \"previewImage: resizing image: bounds: %s\", img.Bounds())\n\tpreview := resize.Resize(width, height, img, resize.Bicubic)\n\tvar buf bytes.Buffer\n\n\tvar encodeContentType string\n\tswitch contentType {\n\tcase \"image/vnd.microsoft.icon\", \"image/x-icon\", \"image/png\":\n\t\tencodeContentType = \"image/png\"\n\t\tif err := png.Encode(&buf, preview); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\tencodeContentType = \"image/jpeg\"\n\t\tif err := jpeg.Encode(&buf, preview, &jpeg.Options{Quality: 90}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &PreviewRes{\n\t\tSource: buf.Bytes(),\n\t\tContentType: encodeContentType,\n\t\tBaseWidth: img.Bounds().Dx(),\n\t\tBaseHeight: img.Bounds().Dy(),\n\t\tPreviewWidth: int(width),\n\t\tPreviewHeight: int(height),\n\t}, nil\n}", "func (o ApplicationSpecRolloutplanPtrOutput) TargetSize() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecRolloutplan) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TargetSize\n\t}).(pulumi.IntPtrOutput)\n}", "func (o *ViewMetaPage) GetPageSizeOk() (*int32, bool) {\n\tif o == nil || o.PageSize == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PageSize, true\n}", "func (info *ImageInfoType) Height() float64 {\n\treturn info.h / (info.scale * info.dpi / 72)\n}", "func qr_decoder_open_with_image_size(width, height, depth, channel int) _QrDecoderHandle {\n\tp := C.qr_decoder_open_with_image_size(\n\t\tC.int(width), C.int(height), C.int(depth), C.int(channel),\n\t)\n\treturn _QrDecoderHandle(p)\n}", "func (m *CvMat) Size() []int {\n\tsizeLen := int32(0)\n\tintArray := C.cvMatrixSize(m.ptr, (*_Ctype_int)(&sizeLen))\n\tslice := (*[1 << 28]C.CInt)(unsafe.Pointer(intArray))[:sizeLen:sizeLen]\n\tres := make([]int, sizeLen)\n\tfor i := int32(0); i < sizeLen; i++ {\n\t\tres[i] = int(slice[i])\n\t}\n\t// C.free(unsafe.Pointer(intArray))\n\treturn res\n}", "func (r *MachinePoolsListServerRequest) Size() int {\n\tif r != nil && r.size != nil {\n\t\treturn *r.size\n\t}\n\treturn 0\n}", "func (vb *ViewBox2D) SizeRect() image.Rectangle {\n\treturn image.Rect(0, 0, vb.Size.X, vb.Size.Y)\n}", "func (r *Reader) Size() int64 {\n\treturn r.xml.ImageSize\n}", "func (me *Image) Size() util.Size {\n\tvar s util.Size\n\ts.Width = me.key.width\n\ts.Height = me.key.height\n\treturn s\n}", "func (x Exif) PreviewImage(tags ...PreviewImageTag) (start int64, length int64, err error) {\n\ttags = append(tags,\n\t\tNewPreviewImageTag(PreviewImageStart, PreviewImageLength, FieldName(\"None\")), // IFD0 PreviewImage\n\t\tNewPreviewImageTag(ThumbJPEGInterchangeFormat, ThumbJPEGInterchangeFormatLength, FieldName(\"None\")), // IFD0 ThumbnailImage\n\t)\n\tfor i, tag := range tags {\n\t\t// If Preview Image is of type JPEG, PNG, WEBP else continue\n\t\tif tag.Compression != FieldName(\"None\") {\n\t\t\tcompression, err := x.Get(tag.Compression)\n\t\t\tif err == nil {\n\t\t\t\tc, err := compression.Int(0)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t_, ok := exifCompressionValues[uint16(c)]\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toffset, err := x.Get(tag.StartTag)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\ttags[i].Start, err = offset.Int(0)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tlength, err := x.Get(tag.LengthTag)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\ttags[i].Length, err = length.Int(0)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tvar maxTag PreviewImageTag\n\tfor i := range tags {\n\t\tif tags[i].Length > maxTag.Length {\n\t\t\tmaxTag = tags[i]\n\t\t}\n\t}\n\tfmt.Println(maxTag)\n\treturn int64(maxTag.Start), int64(maxTag.Length), nil\n}", "func (client *Client) GetImageInfosWithOptions(request *GetImageInfosRequest, runtime *util.RuntimeOptions) (_result *GetImageInfosResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AuthTimeout)) {\n\t\tquery[\"AuthTimeout\"] = request.AuthTimeout\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ImageIds)) {\n\t\tquery[\"ImageIds\"] = request.ImageIds\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OutputType)) {\n\t\tquery[\"OutputType\"] = request.OutputType\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"GetImageInfos\"),\n\t\tVersion: tea.String(\"2017-03-21\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &GetImageInfosResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (m *wasiSnapshotPreview1Impl) fdFilestatSetSize(pfd wasiFd, psize wasiFilesize) (err wasiErrno) {\n\tf, err := m.files.getFile(pfd, wasiRightsFdRead)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tif ferr := f.SetSize(psize); ferr != nil {\n\t\treturn fileErrno(ferr)\n\t}\n\treturn wasiErrnoSuccess\n}", "func GetSupportedRegions() map[string]bool {\n\treturn supportedRegions\n}", "func (st *Settings) MaxFrameSize() uint32 {\n\treturn st.frameSize\n}", "func (st *Settings) MaxFrameSize() uint32 {\n\treturn st.frameSize\n}", "func (info *ImageInfoType) Extent() (wd, ht float64) {\n\treturn info.Width(), info.Height()\n}", "func (r *ImageRef) PageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}", "func TestUpscale(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tw, h := 64, 48\n\tif err := jpeg.Encode(b, image.NewNRGBA(image.Rect(0, 0, w, h)), nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsizes := []struct {\n\t\tmw, mh int\n\t\twantW, wantH int\n\t}{\n\t\t{wantW: w, wantH: h},\n\t\t{mw: w, mh: h, wantW: w, wantH: h},\n\t\t{mw: w, mh: 2 * h, wantW: w, wantH: h},\n\t\t{mw: 2 * w, mh: w, wantW: w, wantH: h},\n\t\t{mw: 2 * w, mh: 2 * h, wantW: w, wantH: h},\n\t\t{mw: w / 2, mh: h / 2, wantW: w / 2, wantH: h / 2},\n\t\t{mw: w / 2, mh: 2 * h, wantW: w / 2, wantH: h / 2},\n\t\t{mw: 2 * w, mh: h / 2, wantW: w / 2, wantH: h / 2},\n\t}\n\tfor i, size := range sizes {\n\t\tvar opts DecodeOpts\n\t\tswitch {\n\t\tcase size.mw != 0 && size.mh != 0:\n\t\t\topts = DecodeOpts{MaxWidth: size.mw, MaxHeight: size.mh}\n\t\tcase size.mw != 0:\n\t\t\topts = DecodeOpts{MaxWidth: size.mw}\n\t\tcase size.mh != 0:\n\t\t\topts = DecodeOpts{MaxHeight: size.mh}\n\t\t}\n\t\tim, _, err := Decode(bytes.NewReader(b.Bytes()), &opts)\n\t\tif err != nil {\n\t\t\tt.Error(i, err)\n\t\t}\n\t\tgotW := im.Bounds().Dx()\n\t\tgotH := im.Bounds().Dy()\n\t\tif gotW != size.wantW || gotH != size.wantH {\n\t\t\tt.Errorf(\"%d got %dx%d want %dx%d\", i, gotW, gotH, size.wantW, size.wantH)\n\t\t}\n\t}\n}", "func (mw *MagickWand) Size() (columns, rows uint, err error) {\n\treturn mw.Width(), mw.Height(), nil\n}", "func (w *MainWindow) GetSize() (int, int) {\n\treturn w.glfwWindow.GetSize()\n}", "func GetBlogPostVersionCount(ctx context.Context) (int, error) {\n\tq := datastore.NewQuery(blogPostVersionKind).KeysOnly()\n\tk, err := q.GetAll(ctx, nil)\n\treturn len(k), err\n}", "func (v *SrsMp4Sample) size() uint32 {\n if v.handlerType == SrsMp4HandlerTypeSOUN {\n if v.codec == SrsAudioCodecIdAAC {\n return v.nbSample + 2\n }\n return v.nbSample + 1\n }\n if v.codec == SrsVideoCodecIdAVC {\n return v.nbSample + 5\n }\n return v.nbSample + 1\n}", "func (verSet *basicSet) Size() int {\n\tverSet.verifierMu.RLock()\n\tdefer verSet.verifierMu.RUnlock()\n\treturn len(verSet.verifiers)\n}", "func (o *ViewSampleProject) GetImagePreviewOk() (*string, bool) {\n\tif o == nil || o.ImagePreview == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ImagePreview, true\n}", "func (current OffsetPageBase) getPageSize() (int, error) {\n\tvar pageSize int\n\n\tswitch pb := current.Body.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range pb {\n\t\t\t// ignore xxx_links\n\t\t\tif !strings.HasSuffix(k, \"links\") {\n\t\t\t\t// check the field's type. we only want []interface{} (which is really []map[string]interface{})\n\t\t\t\tswitch vt := v.(type) {\n\t\t\t\tcase []interface{}:\n\t\t\t\t\tpageSize = len(vt)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tpageSize = len(pb)\n\tdefault:\n\t\terr := golangsdk.ErrUnexpectedType{}\n\t\terr.Expected = \"map[string]interface{}/[]interface{}\"\n\t\terr.Actual = fmt.Sprintf(\"%T\", pb)\n\t\treturn 0, err\n\t}\n\n\treturn pageSize, nil\n}", "func (o *ViewSampleProject) GetImagePreview() string {\n\tif o == nil || o.ImagePreview == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ImagePreview\n}", "func (m *Manager) GetImageSize(hash string) (int64, error) {\n\tpath := filepath.Join(m.Options.Directory, hash)\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to locate image path: %v\", err)\n\t}\n\n\t// FIXME need a real way to do this\n\treturn 0, nil\n}", "func (res SearchRes) Size() uint {\n\treturn res.Control.Size() + res.DescriptionB.DeviceHardware.Size() + res.DescriptionB.SupportedServices.Size()\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Size() pulumi.IntOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) int { return v.Size }).(pulumi.IntOutput)\n}", "func GetBlobSizes(state kv.KVStore, blobHash hashing.HashValue) *collections.Map {\n\treturn collections.NewMap(state, sizesMapName(blobHash))\n}", "func getImageInfo(image_path string) (w int, h int, kind string, err error) {\n\timf, err := os.Open(image_path)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\tdefer imf.Close()\n\n\tconfig, kind, err := image.DecodeConfig(imf)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\n\treturn config.Width, config.Height, kind, nil\n}", "func (o *FieldArrayPoolOptions) Size() int { return o.size }", "func (m *IosDeviceFeaturesConfiguration) GetWallpaperImage()(MimeContentable) {\n val, err := m.GetBackingStore().Get(\"wallpaperImage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(MimeContentable)\n }\n return nil\n}", "func (state *State) GetDimensions() (int, int) {\n\treturn state.width, state.height\n}", "func DecodePhotoSize(buf *bin.Buffer) (PhotoSizeClass, error) {\n\tid, err := buf.PeekID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch id {\n\tcase PhotoSizeEmptyTypeID:\n\t\t// Decoding photoSizeEmpty#e17e23c.\n\t\tv := PhotoSizeEmpty{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoSizeTypeID:\n\t\t// Decoding photoSize#77bfb61b.\n\t\tv := PhotoSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoCachedSizeTypeID:\n\t\t// Decoding photoCachedSize#e9a734fa.\n\t\tv := PhotoCachedSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoStrippedSizeTypeID:\n\t\t// Decoding photoStrippedSize#e0b0bc2e.\n\t\tv := PhotoStrippedSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoSizeProgressiveTypeID:\n\t\t// Decoding photoSizeProgressive#5aa86a51.\n\t\tv := PhotoSizeProgressive{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tcase PhotoPathSizeTypeID:\n\t\t// Decoding photoPathSize#d8214d41.\n\t\tv := PhotoPathSize{}\n\t\tif err := v.Decode(buf); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", err)\n\t\t}\n\t\treturn &v, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unable to decode PhotoSizeClass: %w\", bin.NewUnexpectedID(id))\n\t}\n}", "func (is ImageSurface) Height() int {\n\treturn is.height\n}", "func getSizeFromAnnotations(sourcePvc *corev1.PersistentVolumeClaim) (int64, bool) {\n\tvirtualImageSize, available := sourcePvc.Annotations[AnnVirtualImageSize]\n\tif available {\n\t\tsourceCapacity, available := sourcePvc.Annotations[AnnSourceCapacity]\n\t\tcurrCapacity := sourcePvc.Status.Capacity\n\t\t// Checks if the original PVC's capacity has changed\n\t\tif available && currCapacity.Storage().Cmp(resource.MustParse(sourceCapacity)) == 0 {\n\t\t\t// Parse the raw string containing the image size into a 64-bit int\n\t\t\timgSizeInt, _ := strconv.ParseInt(virtualImageSize, 10, 64)\n\t\t\treturn imgSizeInt, true\n\t\t}\n\t}\n\n\treturn 0, false\n}", "func (w *WidgetImplement) Size() (int, int) {\n\treturn w.w, w.h\n}", "func (a *App) trueToSizeHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\ta.getTrueToSize(w, r)\n\tcase http.MethodPost:\n\t\ta.postTrueToSize(w, r)\n\tdefault:\n\t\tsendHttpErr(w, http.StatusNotImplemented)\n\t}\n}", "func GetSize(matches []logol.Match) int {\n\tstart := 0\n\tend := 0\n\tif len(matches) > 0 {\n\t\tstart = matches[0].Start\n\t\tend = matches[len(matches)-1].End\n\t}\n\treturn end - start\n}", "func (size *BitmapSize) Height() int16 {\n\treturn int16(size.handle.height)\n}", "func checkSize(img image.Image) image.Image {\n\tif img.Bounds().Dx() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(IMAGE_MAX_SIZE, 0, img, resize.Bilinear)\n\t}\n\n\tif img.Bounds().Dy() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(0, IMAGE_MAX_SIZE, img, resize.Bilinear)\n\t}\n\n\treturn img\n}", "func (m *IGApiManager) GetRecentPostMedia(username string) (medias []IGMedia, err error) {\n\tui, err := m.GetUserInfo(username)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, node := range ui.EdgeOwnerToTimelineMedia.Edges {\n\t\tmedias = append(medias, node.Node)\n\t}\n\treturn\n}", "func (p *Picture) GetHeight() int {\r\n\treturn p.pixelHeight\r\n}", "func (r *MachinePoolsListResponse) Size() int {\n\tif r != nil && r.size != nil {\n\t\treturn *r.size\n\t}\n\treturn 0\n}", "func ScreenSize() (w, h float32) {\n\treturn screen.rlWidth, screen.rlHeight\n}", "func GetParameters(maxSize uint, fpProb float64) (m uint, k uint) {\n m = uint(-1 * (float64(maxSize) * math.Log(fpProb)) / math.Pow(math.Log(2), 2))\n k = uint((float64(m) / float64(maxSize)) * math.Log(2))\n return\n}" ]
[ "0.74820864", "0.730369", "0.571322", "0.4549322", "0.44948772", "0.4281146", "0.427835", "0.4273784", "0.4234962", "0.42299852", "0.418386", "0.4142235", "0.41321218", "0.4115057", "0.41139987", "0.40988758", "0.4079467", "0.40490967", "0.40485758", "0.40454385", "0.4030844", "0.39980358", "0.39667308", "0.39589235", "0.3958205", "0.39486337", "0.39429504", "0.393801", "0.39241874", "0.39115587", "0.39084545", "0.39076796", "0.38908833", "0.38883892", "0.38708863", "0.3850744", "0.38498735", "0.38486826", "0.38455257", "0.3836043", "0.3828871", "0.3821476", "0.381987", "0.3816508", "0.38141593", "0.3813208", "0.3810658", "0.37971774", "0.37952867", "0.3795164", "0.37886998", "0.37879977", "0.37845102", "0.37803012", "0.37782335", "0.37656587", "0.37644425", "0.37426636", "0.37350234", "0.37342528", "0.3728872", "0.37259936", "0.37251675", "0.37150478", "0.37092215", "0.37062398", "0.37017065", "0.37017065", "0.37009618", "0.3698586", "0.36954612", "0.36948344", "0.36871514", "0.36802337", "0.36801642", "0.36787573", "0.3669771", "0.36682075", "0.3661004", "0.3660198", "0.36597455", "0.36538666", "0.36493084", "0.3647127", "0.36421317", "0.3638481", "0.3627953", "0.36277243", "0.36241183", "0.36204782", "0.36182967", "0.36160862", "0.3615442", "0.36107075", "0.36077172", "0.3605293", "0.360517", "0.3604339", "0.3600714", "0.35996634" ]
0.86533886
0
GetAvailablePostviewImageSize obtains the current and available Post View Image sizes from the camera
GetAvailablePostviewImageSize получает текущий и доступный размер изображения Post View с камеры
func (c *Camera) GetAvailablePostviewImageSize() (current string, available []string, err error) { resp, err := c.newRequest(endpoints.Camera, "getAvailablePostviewImageSize").Do() if err != nil { return } if len(resp.Result) >= 1 { // Current size if err := json.Unmarshal(resp.Result[0], &current); err != nil { return current, available, err } // Available sizes if err := json.Unmarshal(resp.Result[1], &available); err != nil { return current, available, err } } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Camera) GetSupportedPostviewImageSize() (sizes []string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getSupportedPostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) > 0 {\n\t\terr = json.Unmarshal(resp.Result[0], &sizes)\n\t}\n\n\treturn\n}", "func (c *Camera) GetPostviewImageSize() (size string, err error) {\n\tresp, err := c.newRequest(endpoints.Camera, \"getPostviewImageSize\").Do()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(resp.Result) > 0 {\n\t\terr = json.Unmarshal(resp.Result[0], &size)\n\t}\n\n\treturn\n}", "func (c *Camera) SetPostviewImageSize(size PostViewSize) (err error) {\n\t_, err = c.newRequest(endpoints.Camera, \"setPostviewImageSize\", size).Do()\n\treturn\n}", "func (m *wasiSnapshotPreview1Impl) argsSizesGet() (r0 wasiSize, r1 wasiSize, err wasiErrno) {\n\tsize := 0\n\tfor _, s := range m.args {\n\t\tsize += len(s) + 1\n\t}\n\treturn wasiSize(len(m.args)), wasiSize(size), wasiErrnoSuccess\n}", "func (a *PhonebookAccess1) GetFixedImageSize() (bool, error) {\n\tv, err := a.GetProperty(\"FixedImageSize\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v.Value().(bool), nil\n}", "func (m *wasiSnapshotPreview1Impl) environSizesGet() (r0 wasiSize, r1 wasiSize, err wasiErrno) {\n\tsize := 0\n\tfor _, s := range m.env {\n\t\tsize += len(s) + 1\n\t}\n\treturn wasiSize(len(m.env)), wasiSize(size), wasiErrnoSuccess\n}", "func (p *PdfiumImplementation) FPDFBitmap_GetHeight(request *requests.FPDFBitmap_GetHeight) (*responses.FPDFBitmap_GetHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetHeight{\n\t\tHeight: int(height),\n\t}, nil\n}", "func (fc *FacebookClient) GetImageUrlsFromPostId(postId string) []ImageInfo {\n\turl := fmt.Sprintf(fc.attachmentUrl, postId) + \"?access_token=\" + fc.accessToken\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\tresp, err := client.Do(req)\n\n\t// TLS handshake timeout\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn make([]ImageInfo, 0)\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\n\t// Unmarshall response\n\tatt := new(AttachmentResponse)\n\tjson.Unmarshal(body, &att)\n\tret := make([]ImageInfo, 0)\n\tfor _, data := range att.Data {\n\t\t// Since missing values get unmarshalled into their type's 0'd value, make sure the src exists before we make an ImageInfo struct\n\t\tif len(data.Media.Image.Src) > 0 {\n\t\t\tinfo := ImageInfo{}\n\t\t\tinfo.Url = data.Media.Image.Src\n\t\t\tinfo.Id = data.Target.Id\n\t\t\tret = append(ret, info)\n\t\t}\n\t}\n\treturn ret\n}", "func GetBlobSizesR(state kv.KVStoreReader, blobHash hashing.HashValue) *collections.ImmutableMap {\n\treturn collections.NewMapReadOnly(state, sizesMapName(blobHash))\n}", "func (c *Camera) ScreenSize() (int, int) {\n\treturn c.screenW, c.screenH\n}", "func getImageDimensions(imagePath string) (int, int) {\n file, err := os.Open(imagePath)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%v\\n\", err)\n }\n defer file.Close()\n imageConfig, _, err := image.DecodeConfig(file)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%s: %v\\n\", imagePath, err)\n }\n return imageConfig.Width, imageConfig.Height\n}", "func (is ImageSurface) Size() Point {\n\treturn Point{float64(is.width), float64(is.height)}\n}", "func qr_decoder_set_image_size(p _QrDecoderHandle, width, height, depth, channel int) _QrDecoderHandle {\n\tv := C.qr_decoder_set_image_size(C.QrDecoderHandle(p),\n\t\tC.int(width), C.int(height), C.int(depth), C.int(channel),\n\t)\n\treturn _QrDecoderHandle(v)\n}", "func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}", "func GetDimensions(imageData io.Reader) (int, int, error) {\n\tcfg, _, err := image.DecodeConfig(imageData)\n\tif seeker, ok := imageData.(io.ReadSeeker); ok {\n\t\tdefer seeker.Seek(0, 0)\n\t}\n\treturn cfg.Width, cfg.Height, err\n}", "func (t *TargetBuilder) MaxImgSizes() []int {\n\tsz0 := t.bspPkg.FlashMap.Areas[flash.FLASH_AREA_NAME_IMAGE_0].Size\n\tsz1 := t.bspPkg.FlashMap.Areas[flash.FLASH_AREA_NAME_IMAGE_1].Size\n\ttrailerSz := t.bootTrailerSize()\n\n\treturn []int{\n\t\tsz0 - trailerSz,\n\t\tsz1 - trailerSz,\n\t}\n}", "func (size *BitmapSize) Size() int64 {\n\treturn int64(size.handle.size)\n}", "func (canvas *Canvas) Size() (width, height Unit) {\n\tmbox := canvas.page.MediaBox\n\treturn mbox.Dx(), mbox.Dy()\n}", "func (m *BitPrecMat) Size() (w, h int) {\n\treturn m.w, m.h\n}", "func downsamplePostImage(url string, currentStatus, id int, c chan DownsampleResult) {\n\tprf(\"Downsampling image #%d status %d urls %s\\n\", id, currentStatus, url)\n\n\tassert(image_DownsampleError <= currentStatus && currentStatus <= image_DownsampleVersionTarget)\n\n\t//image_Unprocessed\t\t= 0\n\t//image_Downsampled\t\t= 1 // 125 x 75\n\t//image_DownsampledV2 = 2 // NOTE: THIS SHOULD BE THE NEW SIZE! a - 160 x 116 - thumbnail\n\t// // AND b - 160 x 150\n\t//image_DownsampledV3 // V3 += LARGE THUMBNAIL c - 570 x [preserve aspect ratio]\n\t//image_DownsampleError\t= -1\n\n\tbytes, err := downloadImage(url)\n\tif err != nil {\n\t\tprf(\" ERR downsampleImage - could not download image because: %s\", err.Error())\n\t\tc <- DownsampleResult{id, url, err}\n\t\treturn\n\t}\n\n\tif currentStatus < image_DownsampledV2 {\n\t\t// Small thumbnail - a\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"a\", \"jpeg\", 160, 116)\n\t\tif err != nil {\n\t\t\tprVal(\"# A downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t\t// Small thumbnail - b\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"b\", \"jpeg\", 160, 150)\n\t\tif err != nil {\n\t\t\tprVal(\"# B downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tif currentStatus < image_DownsampledV3 {\n\t\t// Large Thumbnail - c\n\t\terr = downsampleImage(bytes, url, \"thumbnails\", int_to_str(id) + \"c\", \"jpeg\", 570, -1)\n\t\tif err != nil {\n\t\t\tprVal(\"# C downsamplePostImage called downsampleImage and then encountered some error\", err.Error())\n\t\t\tc <- DownsampleResult{id, url, err}\n\t\t\treturn\n\t\t}\n\t}\n\tprf(\"Result for #%d image %s: Success\\n\", id, url)\n\tc <- DownsampleResult{id, url, err}\n\treturn\n}", "func (o *ShowAggregatesType) AvailableSize() SizeType {\n\tvar r SizeType\n\tif o.AvailableSizePtr == nil {\n\t\treturn r\n\t}\n\tr = *o.AvailableSizePtr\n\treturn r\n}", "func (r *MachinePoolsListServerRequest) GetSize() (value int, ok bool) {\n\tok = r != nil && r.size != nil\n\tif ok {\n\t\tvalue = *r.size\n\t}\n\treturn\n}", "func (is ImageSize) Size() (width int, height int) {\n\tconst tokensWidthHeightCount = 2\n\n\tsizeTokens := strings.Split(string(is), \"x\")\n\tif len(sizeTokens) != tokensWidthHeightCount {\n\t\treturn 0, 0\n\t}\n\n\tvar err error\n\twidth, err = strconv.Atoi(sizeTokens[0])\n\tswitch {\n\tcase err != nil:\n\t\tfallthrough\n\tcase width <= 0:\n\t\treturn 0, 0\n\t}\n\n\theight, err = strconv.Atoi(sizeTokens[1])\n\tswitch {\n\tcase err != nil:\n\t\tfallthrough\n\tcase height <= 0:\n\t\treturn 0, 0\n\t}\n\n\treturn width, height\n}", "func (o *ViewSampleProject) HasImagePreview() bool {\n\tif o != nil && o.ImagePreview != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r *ImageRef) PageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}", "func GetRenderbufferDepthSize(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_DEPTH_SIZE, &params)\n\treturn params\n}", "func (info *ImageInfoType) Height() float64 {\n\treturn info.h / (info.scale * info.dpi / 72)\n}", "func (i *Image) Size() (int, int) {\n\treturn i.image.Size()\n}", "func getSizeFromAnnotations(sourcePvc *corev1.PersistentVolumeClaim) (int64, bool) {\n\tvirtualImageSize, available := sourcePvc.Annotations[AnnVirtualImageSize]\n\tif available {\n\t\tsourceCapacity, available := sourcePvc.Annotations[AnnSourceCapacity]\n\t\tcurrCapacity := sourcePvc.Status.Capacity\n\t\t// Checks if the original PVC's capacity has changed\n\t\tif available && currCapacity.Storage().Cmp(resource.MustParse(sourceCapacity)) == 0 {\n\t\t\t// Parse the raw string containing the image size into a 64-bit int\n\t\t\timgSizeInt, _ := strconv.ParseInt(virtualImageSize, 10, 64)\n\t\t\treturn imgSizeInt, true\n\t\t}\n\t}\n\n\treturn 0, false\n}", "func (is ImageSurface) Height() int {\n\treturn is.height\n}", "func (r *MachinePoolsListResponse) GetSize() (value int, ok bool) {\n\tok = r != nil && r.size != nil\n\tif ok {\n\t\tvalue = *r.size\n\t}\n\treturn\n}", "func PossibleImageSizeValues() []ImageSize {\n\treturn []ImageSize{\n\t\tImageSize512x512,\n\t\tImageSize1024x1024,\n\t\tImageSize256x256,\n\t}\n}", "func (c Capture) RequestSize() int64 {\n\tif c.rr == nil {\n\t\treturn 0\n\t}\n\treturn c.rr.size\n}", "func (vb *ViewBox2D) SizeRect() image.Rectangle {\n\treturn image.Rect(0, 0, vb.Size.X, vb.Size.Y)\n}", "func (state *State) GetDimensions() (int, int) {\n\treturn state.width, state.height\n}", "func (me *Image) Size() util.Size {\n\tvar s util.Size\n\ts.Width = me.key.width\n\ts.Height = me.key.height\n\treturn s\n}", "func (o *ARVRInterface) GetRenderTargetsize() gdnative.Vector2 {\n\t//log.Println(\"Calling ARVRInterface.GetRenderTargetsize()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ARVRInterface\", \"get_render_targetsize\")\n\n\t// Call the parent method.\n\t// Vector2\n\tretPtr := gdnative.NewEmptyVector2()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewVector2FromPointer(retPtr)\n\treturn ret\n}", "func (r *Reader) Size() int64 {\n\treturn r.xml.ImageSize\n}", "func (np NodePool) AvailableStorage(ebsSize int64, scaleFactor float64) (int64, error) {\n\tinstanceInfo, err := aws.SyntheticInstanceInfo(np.InstanceTypes)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tinstanceStorageSize := scaleFactor * float64(instanceInfo.InstanceStorageDevices*instanceInfo.InstanceStorageDeviceSize)\n\tif instanceStorageSize == 0 {\n\t\treturn ebsSize, nil\n\t}\n\treturn int64(instanceStorageSize), nil\n}", "func (tbd *TermboxDriver) Size() (width int, height int) {\n\treturn tbd.width, tbd.height\n}", "func (w *WebviewWindow) Size() (width int, height int) {\n\tif w.impl == nil {\n\t\treturn 0, 0\n\t}\n\treturn w.impl.size()\n}", "func (o GoogleCloudRetailV2alphaImageOutput) Height() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImage) *int { return v.Height }).(pulumi.IntPtrOutput)\n}", "func getOriginalSizeUrl(flickrOauth FlickrOAuth, photo Photo) (string, string) {\n\n\tif photo.Media == \"photo\" {\n\t\treturn photo.OriginalUrl, \"\"\n\t}\n\n\textras := map[string]string{\"photo_id\": photo.Id}\n\n\tvar err error\n\tvar body []byte\n\n\tbody, err = makeGetRequest(func() string { return generateOAuthUrl(apiBaseUrl, \"flickr.photos.getSizes\", flickrOauth, extras) })\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresponse := PhotoSizeResponse{}\n\terr = xml.Unmarshal(body, &response)\n\tif err != nil {\n\t\tlogMessage(\"Could not unmarshal body, check logs for body detail.\", true)\n\t\tlogMessage(string(body), false)\n\t\treturn \"\", \"\"\n\t}\n\n\tphotoUrl := \"\"\n\tvideoUrl := \"\"\n\tfor _, v := range response.SizesContainer.Sizes {\n\t\tif v.Label == \"Original\" {\n\t\t\tphotoUrl = v.Url\n\t\t}\n\n\t\tif v.Label == \"Video Original\" {\n\t\t\tvideoUrl = v.Url\n\t\t}\n\t}\n\n\treturn photoUrl, videoUrl\n}", "func getImageInfo(image_path string) (w int, h int, kind string, err error) {\n\timf, err := os.Open(image_path)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\tdefer imf.Close()\n\n\tconfig, kind, err := image.DecodeConfig(imf)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\n\treturn config.Width, config.Height, kind, nil\n}", "func (res SearchRes) Size() uint {\n\treturn res.Control.Size() + res.DescriptionB.DeviceHardware.Size() + res.DescriptionB.SupportedServices.Size()\n}", "func (d *Data) GetSizeRange(v dvid.VersionID, minSize, maxSize uint64) (string, error) {\n\tstore, err := storage.MutableStore()\n\tif err != nil {\n\t\treturn \"{}\", fmt.Errorf(\"Data type imagesz had error initializing store: %v\\n\", err)\n\t}\n\n\t// Get the start/end keys for the size range.\n\tfirstKey := NewSizeLabelTKey(minSize, 0)\n\tvar upperBound uint64\n\tif maxSize != 0 {\n\t\tupperBound = maxSize\n\t} else {\n\t\tupperBound = math.MaxUint64\n\t}\n\tlastKey := NewSizeLabelTKey(upperBound, math.MaxUint64)\n\n\t// Grab all keys for this range in one sequential read.\n\tctx := datastore.NewVersionedCtx(d, v)\n\tkeys, err := store.KeysInRange(ctx, firstKey, lastKey)\n\tif err != nil {\n\t\treturn \"{}\", err\n\t}\n\n\t// Convert them to a JSON compatible structure.\n\tlabels := make([]uint64, len(keys))\n\tfor i, key := range keys {\n\t\tlabels[i], _, err = DecodeSizeLabelTKey(key)\n\t\tif err != nil {\n\t\t\treturn \"{}\", err\n\t\t}\n\t}\n\tm, err := json.Marshal(labels)\n\tif err != nil {\n\t\treturn \"{}\", nil\n\t}\n\treturn string(m), nil\n}", "func (r *ImageRef) Height() int {\n\treturn int(r.image.Ysize)\n}", "func (w *MainWindow) GetSize() (int, int) {\n\treturn w.glfwWindow.GetSize()\n}", "func (m *PoolModule) GetSize() util.Map {\n\n\tif m.IsAttached() {\n\t\tres, err := m.Client.Pool().GetSize()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn util.ToMap(res)\n\t}\n\n\treturn util.ToMap(m.mempoolReactor.GetPoolSize())\n}", "func (l PostingList) Size() int32 {\n\treturn l.n\n}", "func qr_decoder_open_with_image_size(width, height, depth, channel int) _QrDecoderHandle {\n\tp := C.qr_decoder_open_with_image_size(\n\t\tC.int(width), C.int(height), C.int(depth), C.int(channel),\n\t)\n\treturn _QrDecoderHandle(p)\n}", "func GetVideoModeCount() int {\n\treturn int(C.freenect_get_video_mode_count())\n}", "func GetSizeInBytes(key string) uint { return viper.GetSizeInBytes(key) }", "func (d *Device) Size() (w, h int16) {\n\tif d.rotation == drivers.Rotation0 || d.rotation == drivers.Rotation180 {\n\t\treturn d.width, d.height\n\t}\n\treturn d.height, d.width\n}", "func (r *MachinePoolsListServerRequest) Size() int {\n\tif r != nil && r.size != nil {\n\t\treturn *r.size\n\t}\n\treturn 0\n}", "func (o *ViewMetaPage) GetPageSizeOk() (*int32, bool) {\n\tif o == nil || o.PageSize == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PageSize, true\n}", "func (info *ImageInfoType) Extent() (wd, ht float64) {\n\treturn info.Width(), info.Height()\n}", "func (v *View) Size() int64 { return v.data.Size() }", "func GetSize() (width, heigth int) {\n\tjsObject := atom.Call(\"getSize\")\n\twidth = jsObject.Get(\"width\").Int()\n\theigth = jsObject.Get(\"heigth\").Int()\n\treturn\n}", "func (r *MachinePoolsListResponse) Size() int {\n\tif r != nil && r.size != nil {\n\t\treturn *r.size\n\t}\n\treturn 0\n}", "func (m *wasiSnapshotPreview1Impl) fdFilestatSetSize(pfd wasiFd, psize wasiFilesize) (err wasiErrno) {\n\tf, err := m.files.getFile(pfd, wasiRightsFdRead)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tif ferr := f.SetSize(psize); ferr != nil {\n\t\treturn fileErrno(ferr)\n\t}\n\treturn wasiErrnoSuccess\n}", "func (kcp *KCP) PeekSize() (size int) {\n\tif len(kcp.recvQueue) <= 0 {\n\t\treturn -1\n\t}\n\n\tseg := kcp.recvQueue[0]\n\tif seg.frg == 0 {\n\t\treturn len(seg.dataBuffer)\n\t}\n\n\tif len(kcp.recvQueue) < int(seg.frg+1) {\n\t\treturn -1\n\t}\n\n\tfor idx := range kcp.recvQueue {\n\t\tseg := kcp.recvQueue[idx]\n\t\tsize += len(seg.dataBuffer)\n\t\tif seg.frg == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func checkSize(img image.Image) image.Image {\n\tif img.Bounds().Dx() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(IMAGE_MAX_SIZE, 0, img, resize.Bilinear)\n\t}\n\n\tif img.Bounds().Dy() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(0, IMAGE_MAX_SIZE, img, resize.Bilinear)\n\t}\n\n\treturn img\n}", "func (m *Manager) GetImageSize(hash string) (int64, error) {\n\tpath := filepath.Join(m.Options.Directory, hash)\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to locate image path: %v\", err)\n\t}\n\n\t// FIXME need a real way to do this\n\treturn 0, nil\n}", "func (mtr *Msmsintprp5Metrics) Size() int {\n\tsz := 0\n\n\tsz += mtr.Read.Size()\n\n\tsz += mtr.Security.Size()\n\n\tsz += mtr.Decode.Size()\n\n\treturn sz\n}", "func GetSize(matches []logol.Match) int {\n\tstart := 0\n\tend := 0\n\tif len(matches) > 0 {\n\t\tstart = matches[0].Start\n\t\tend = matches[len(matches)-1].End\n\t}\n\treturn end - start\n}", "func (kcp *KCP) PeekSize() (length int) {\n\tif len(kcp.rcv_queue) == 0 {\n\t\treturn -1\n\t}\n\n\tseg := &kcp.rcv_queue[0]\n\tif seg.frg == 0 {\n\t\treturn seg.data.Len()\n\t}\n\n\tif len(kcp.rcv_queue) < int(seg.frg+1) {\n\t\treturn -1\n\t}\n\n\tfor k := range kcp.rcv_queue {\n\t\tseg := &kcp.rcv_queue[k]\n\t\tlength += seg.data.Len()\n\t\tif seg.frg == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func (monitor *Monitor) GetPhysicalSize() (widthMM, heightMM int) {\n\tvar cWidth, cHeight C.int\n\tC.glfwGetMonitorPhysicalSize(monitor.c(), &cWidth, &cHeight)\n\twidthMM, heightMM = int(cWidth), int(cHeight)\n\treturn\n}", "func (current OffsetPageBase) getPageSize() (int, error) {\n\tvar pageSize int\n\n\tswitch pb := current.Body.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range pb {\n\t\t\t// ignore xxx_links\n\t\t\tif !strings.HasSuffix(k, \"links\") {\n\t\t\t\t// check the field's type. we only want []interface{} (which is really []map[string]interface{})\n\t\t\t\tswitch vt := v.(type) {\n\t\t\t\tcase []interface{}:\n\t\t\t\t\tpageSize = len(vt)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tpageSize = len(pb)\n\tdefault:\n\t\terr := golangsdk.ErrUnexpectedType{}\n\t\terr.Expected = \"map[string]interface{}/[]interface{}\"\n\t\terr.Actual = fmt.Sprintf(\"%T\", pb)\n\t\treturn 0, err\n\t}\n\n\treturn pageSize, nil\n}", "func (b *Buffer) SizeMax() (int, int) {\n\treturn b.maxWidth, b.maxHeight\n}", "func (s *session) getMaildropSize() uint64 {\n\tvar ret uint64\n\tfor msgID, size := range s.msgSizes {\n\t\tif _, deleted := s.markedDeleted[msgID]; !deleted {\n\t\t\tret += size\n\t\t}\n\t}\n\treturn ret\n}", "func GetSize(fd uintptr) (width, height int, err error) {\n\tinfo := new(consoleScreenBufferInfo)\n\tprocGetConsoleScreenBufferInfo.Call(fd, uintptr(unsafe.Pointer(info)))\n\treturn int(info.window.right - info.window.left), int(info.window.bottom - info.window.top), nil\n}", "func GetBlobSizes(state kv.KVStore, blobHash hashing.HashValue) *collections.Map {\n\treturn collections.NewMap(state, sizesMapName(blobHash))\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 verifyDimensions(t *testing.T, img image.Image, width, height int) {\n\tb := img.Bounds()\n\tw := b.Max.X - b.Min.X\n\th := b.Max.Y - b.Min.Y\n\n\tif w != width || h != height {\n\t\tt.Errorf(\"Merge() produced incorrect output size: %v w x %v h\\nexpected: %v w x %v h\", w, h, width, height)\n\t}\n}", "func (mon *Monitor) GetPhysicalSize() (int, int) {\n\tvar width, height C.int\n\tC.glfwGetMonitorPhysicalSize(mon.internalPtr, &width, &height)\n\treturn int(width), int(height)\n}", "func GetBlogPostDraftCount(ctx context.Context) (int, error) {\n\tquery := datastore.NewQuery(blogPostVersionKind).\n\t\tProject(\"PostID\").\n\t\tDistinct().\n\t\tOrder(\"PostID\").\n\t\tOrder(\"-Published\").\n\t\tOrder(\"-DateCreated\").\n\t\tFilter(\"Published=\", false)\n\n\tvar x []BlogPostVersion\n\tkeys, err := query.GetAll(ctx, &x)\n\n\treturn len(keys), err\n}", "func dim(img image.Image) (w, h int) {\n\tw, h = img.Bounds().Max.X, img.Bounds().Max.Y\n\treturn\n}", "func (c *Canvas) Size() image.Point {\n\treturn c.buffer.Size()\n}", "func GetParameters(maxSize uint, fpProb float64) (m uint, k uint) {\n m = uint(-1 * (float64(maxSize) * math.Log(fpProb)) / math.Pow(math.Log(2), 2))\n k = uint((float64(m) / float64(maxSize)) * math.Log(2))\n return\n}", "func TryToGetSize(r io.Reader) (int64, error) {\n\tswitch f := r.(type) {\n\tcase *os.File:\n\t\tfileInfo, err := f.Stat()\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrap(err, \"os.File.Stat()\")\n\t\t}\n\t\treturn fileInfo.Size(), nil\n\tcase *bytes.Buffer:\n\t\treturn int64(f.Len()), nil\n\tcase *bytes.Reader:\n\t\t// Returns length of unread data only.\n\t\treturn int64(f.Len()), nil\n\tcase *strings.Reader:\n\t\treturn f.Size(), nil\n\tcase ObjectSizer:\n\t\treturn f.ObjectSize()\n\t}\n\treturn 0, errors.Errorf(\"unsupported type of io.Reader: %T\", r)\n}", "func (monitor *Monitor) GetPhysicalSize() (widthMM, heightMM int) {\n\tvar cWidth, cHeight C.int\n\tC.glfwGetMonitorPhysicalSize((*C.GLFWmonitor)(monitor), &cWidth, &cHeight)\n\twidthMM, heightMM = int(cWidth), int(cHeight)\n\treturn\n}", "func (rb *ByProjectKeyImageSearchRequestBuilder) Post(body io.Reader) *ByProjectKeyImageSearchRequestMethodPost {\n\treturn &ByProjectKeyImageSearchRequestMethodPost{\n\t\tbody: body,\n\t\turl: fmt.Sprintf(\"/%s/image-search\", rb.projectKey),\n\t\tclient: rb.client,\n\t}\n}", "func ScreenSize() (w, h float32) {\n\treturn screen.rlWidth, screen.rlHeight\n}", "func (this *Device) GetDisplaySize(display uint16) (uint32, uint32) {\n\treturn bcmGHostGetDisplaySize(display)\n}", "func getScreenSizeRangeRequest(c *xgb.Conn, Window xproto.Window) []byte {\n\tsize := 8\n\tb := 0\n\tbuf := make([]byte, size)\n\n\tc.ExtLock.RLock()\n\tbuf[b] = c.Extensions[\"RANDR\"]\n\tc.ExtLock.RUnlock()\n\tb += 1\n\n\tbuf[b] = 6 // request opcode\n\tb += 1\n\n\txgb.Put16(buf[b:], uint16(size/4)) // write request size in 4-byte units\n\tb += 2\n\n\txgb.Put32(buf[b:], uint32(Window))\n\tb += 4\n\n\treturn buf\n}", "func imgSetWidthHeight(camera int, width int, height int) int {\n\tlog.Printf(\"imgSetWidthHeight - camera:%d width:%d height:%d\", camera, width, height)\n\tvar f = mod.NewProc(\"img_set_wh\")\n\tret, _, _ := f.Call(uintptr(camera), uintptr(width), uintptr(height))\n\treturn int(ret) // retval is cameraID\n}", "func (mw *MagickWand) Size() (columns, rows uint, err error) {\n\treturn mw.Width(), mw.Height(), nil\n}", "func (o *ViewSampleProject) GetImagePreviewOk() (*string, bool) {\n\tif o == nil || o.ImagePreview == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ImagePreview, true\n}", "func GetRenderbufferHeight(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_HEIGHT, &params)\n\treturn params\n}", "func (n *OpenBazaarNode) GetPostCount() int {\n\tindexPath := path.Join(n.RepoPath, \"root\", \"posts.json\")\n\n\t// Read existing file\n\tfile, err := ioutil.ReadFile(indexPath)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tvar index []postData\n\terr = json.Unmarshal(file, &index)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn len(index)\n}", "func Size() (w int, h int) {\n\tw = goterm.Width()\n\th = goterm.Height()\n\treturn\n}", "func Size() (w int, h int) {\n\tw = goterm.Width()\n\th = goterm.Height()\n\treturn\n}", "func (v *Config) GetReadBufferSize() uint32 {\n\tif v == nil || v.ReadBuffer == nil {\n\t\treturn 2 * 1024 * 1024\n\t}\n\treturn v.ReadBuffer.Size\n}", "func (m *ScreenMode) Resolution() (width, height int) {\n\treturn m.width, m.height\n}", "func (t *Link) PreviewLen() (l int) {\n\treturn len(t.preview)\n\n}", "func (w *WidgetImplement) Size() (int, int) {\n\treturn w.w, w.h\n}", "func (size *BitmapSize) Height() int16 {\n\treturn int16(size.handle.height)\n}", "func (o GetReposRepoTagOutput) ImageSize() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetReposRepoTag) int { return v.ImageSize }).(pulumi.IntOutput)\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Size() pulumi.IntOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) int { return v.Size }).(pulumi.IntOutput)\n}" ]
[ "0.7907042", "0.7288901", "0.5191613", "0.46706542", "0.45597464", "0.44490406", "0.44459066", "0.43250227", "0.42954162", "0.42822164", "0.42566746", "0.4238603", "0.42044538", "0.41916734", "0.41730225", "0.4146435", "0.40981996", "0.40936428", "0.4080742", "0.40763035", "0.40692243", "0.40602198", "0.40454927", "0.4041135", "0.4040686", "0.40268517", "0.40125954", "0.40109295", "0.40063322", "0.39979827", "0.3992024", "0.398927", "0.39695168", "0.39633694", "0.39631283", "0.3949634", "0.39470357", "0.39326602", "0.3929508", "0.39282238", "0.39156008", "0.3912566", "0.38836032", "0.38832548", "0.38711008", "0.3870446", "0.38648129", "0.38577548", "0.38545594", "0.38428313", "0.38416764", "0.3840198", "0.38373753", "0.38320735", "0.38297138", "0.38243264", "0.38158992", "0.3813969", "0.3810026", "0.3807941", "0.38062972", "0.38028735", "0.38025352", "0.37996846", "0.37994936", "0.37984824", "0.3792141", "0.37837213", "0.3782444", "0.3780034", "0.37777287", "0.37746555", "0.3774533", "0.37676468", "0.37631354", "0.37619948", "0.37605625", "0.37570176", "0.37566432", "0.37564242", "0.37471148", "0.37466186", "0.374017", "0.3735802", "0.37339717", "0.37248212", "0.3718278", "0.37175366", "0.37090373", "0.3701297", "0.3697821", "0.36977485", "0.36977485", "0.36935538", "0.36916792", "0.36900347", "0.36858496", "0.36857128", "0.3679358", "0.36768848" ]
0.8519555
0
HandleRequest handles incoming request
HandleRequest обрабатывает входящий запрос
func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { _, _ = pretty.Println("parsed:", request.Body) return events.APIGatewayProxyResponse{Body: "response is working", StatusCode: 200}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *Handler) handleRequest(w http.ResponseWriter, r *http.Request) {\n\tmethod := r.Method\n\th.handleCommon(w, r, method)\n}", "func HandleRequest(db *sql.DB) {\n\troutes := chi.NewRouter()\n\t// Route for user API\n\troutes.Get(\"/v1/users\", initRetrieveResolver(db).GetAllUsers)\n\troutes.Post(\"/v1/users/create-user\", initCreateResolver(db).CreateUser)\n\t// Route for relationship API\n\troutes.Post(\"/v1/friend/create-friend\", initCreateResolver(db).MakeFriend)\n\troutes.Post(\"/v1/friend/get-friends-list\", initRetrieveResolver(db).GetFriendsList)\n\troutes.Post(\"/v1/friend/get-common-friends-list\", initRetrieveResolver(db).GetCommonFriends)\n\n\tlog.Fatal(http.ListenAndServe(\":8082\", routes))\n}", "func handleRequest(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\thandleGetRequest(w, r)\n\t\treturn\n\tcase \"POST\":\n\t\thandlePost(w, r)\n\t\treturn\n\tdefault:\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\tw.Write([]byte(\"HTTP methos not allowed.\"))\n\t\treturn\n\t}\n}", "func (c *Core) handleRequest(fctx *fasthttp.RequestCtx) {\n\tctx := c.assignCtx(fctx)\n\tdefer c.releaseCtx(ctx)\n\tif ctx.methodINT == -1 {\n\t\tctx.Status(StatusBadRequest).SendString(\"Invalid http method\")\n\t\treturn\n\t}\n\n\tstart := time.Now()\n\t// Delegate next to handle the request\n\t// Find match in stack\n\tmatch, err := c.next(ctx)\n\tif err != nil {\n\t\t_ = ctx.SendStatus(StatusInternalServerError)\n\t}\n\t// Generate ETag if enabled\n\tif match && c.ETag {\n\t\tsetETag(ctx, false)\n\t}\n\tif c.Debug {\n\t\td := time.Since(start)\n\t\t// d := time.Now().Sub(start).String()\n\t\tLog.D(\"%s %s %d %s\\n\", ctx.method, ctx.path, ctx.Response.StatusCode(), d)\n\t}\n}", "func (srv *server) handleRequest(clt *Client, msg *Message) {\n\treplyPayload, returnedErr := srv.impl.OnRequest(\n\t\tcontext.Background(),\n\t\tclt,\n\t\tmsg,\n\t)\n\tswitch returnedErr.(type) {\n\tcase nil:\n\t\tsrv.fulfillMsg(clt, msg, replyPayload)\n\tcase ReqErr:\n\t\tsrv.failMsg(clt, msg, returnedErr)\n\tcase *ReqErr:\n\t\tsrv.failMsg(clt, msg, returnedErr)\n\tdefault:\n\t\tsrv.errorLog.Printf(\"Internal error during request handling: %s\", returnedErr)\n\t\tsrv.failMsg(clt, msg, returnedErr)\n\t}\n}", "func (kvs *keyValueServer) handleRequest(req *Request) {\n\tvar request []string\n\trequest = kvs.parseRequest(req.input)\n\tif request[0] == \"get\" {\n\t\tclient := kvs.clienter[req.cid]\n\t\tkvs.getFromDB(request, client)\n\t}\n\tif request[0] == \"put\" {\n\t\tkvs.putIntoDB(request)\n\t}\n}", "func (q *eventQ) handleRequest(req *protocol.Request) (*protocol.Response, error) {\n\tvar resp *protocol.Response\n\tvar err error\n\tinternal.Debugf(q.conf, \"request: %s\", &req.Name)\n\n\tswitch req.Name {\n\tcase protocol.CmdBatch:\n\t\tresp, err = q.handleBatch(req)\n\t\tinstrumentRequest(stats.BatchRequests, stats.BatchErrors, err)\n\tcase protocol.CmdRead:\n\t\tresp, err = q.handleRead(req)\n\t\tinstrumentRequest(stats.ReadRequests, stats.ReadErrors, err)\n\tcase protocol.CmdTail:\n\t\tresp, err = q.handleTail(req)\n\t\tinstrumentRequest(stats.TailRequests, stats.TailErrors, err)\n\tcase protocol.CmdStats:\n\t\tresp, err = q.handleStats(req)\n\t\tinstrumentRequest(stats.StatsRequests, stats.StatsErrors, err)\n\tcase protocol.CmdClose:\n\t\tresp, err = q.handleClose(req)\n\t\tinstrumentRequest(stats.CloseRequests, stats.CloseErrors, err)\n\tcase protocol.CmdConfig:\n\t\tresp, err = q.handleConfig(req)\n\t\tinstrumentRequest(stats.ConfigRequests, stats.ConfigErrors, err)\n\tdefault:\n\t\tlog.Printf(\"unhandled request type passed: %v\", req.Name)\n\t\tresp = req.Response\n\t\tcr := req.Response.ClientResponse\n\t\tcr.SetError(protocol.ErrInvalid)\n\t\terr = protocol.ErrInvalid\n\t\tif _, werr := req.WriteResponse(resp, cr); werr != nil {\n\t\t\terr = werr\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (srv *Server) handleRequest(msg *Message) {\n\treplyPayload, err := srv.hooks.OnRequest(\n\t\tcontext.WithValue(context.Background(), Msg, *msg),\n\t)\n\tif err != nil {\n\t\tmsg.fail(*err)\n\t\treturn\n\t}\n\tmsg.fulfill(replyPayload)\n}", "func (importer *BaseRequestImporter) HandleRequest(resp http.ResponseWriter, req *http.Request) {\n\tbody, _ := ioutil.ReadAll(req.Body)\n\tmeshData, status, respData, err := importer.handleQuery(body, req.URL.Path, req.URL.Query())\n\tif err == nil {\n\t\tif len(meshData) > 0 {\n\t\t\timporter.mergeImportedMeshData(meshData)\n\t\t}\n\t} else {\n\t\trespData = []byte(err.Error())\n\t}\n\tresp.WriteHeader(status)\n\t_, _ = resp.Write(respData)\n}", "func (res *Resource) HandleRequest(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodGet && r.Method != http.MethodHead {\n\t\thandleMethodNotAllowed(w, r)\n\t\treturn\n\t}\n\n\treader := bytes.NewReader(res.Content)\n\thttp.ServeContent(w, r, res.FileName, res.ModTime, reader)\n}", "func HandleRequest(ctx context.Context, evt MyEvent) (*MyResponse, error) {\n\t// context\n\tlc, _ := lambdacontext.FromContext(ctx)\n\tlog.Printf(\"AwsRequestID: %s\", lc.AwsRequestID)\n\n\t// environment variables\n\tfor _, e := range os.Environ() {\n\t\tlog.Println(e)\n\t}\n\n\tlog.Printf(\"Key1: %s\", evt.Key1)\n\tlog.Printf(\"Key2: %s\", evt.Key2)\n\tlog.Printf(\"Key3: %s\", evt.Key3)\n\n\tif evt.Key3 == \"\" {\n\t\treturn nil, errors.New(\"key3 is empty\")\n\t}\n\treturn &MyResponse{Message: evt.Key1}, nil\n}", "func HandleRequest(m types.Message) (types.Response, error) {\n\n\tif m.Type != \"get-todo\" {\n\t\te := util.CreateResponse(\"get-todo-response\", \"NOK\", \"Handling incorrect message type - ignoring...\", \"\")\n\t\treturn e, nil\n\t}\n\n\ttableName = os.Getenv(\"TABLE_NAME\")\n\n\tidString := m.Data\n\tif idString == \"\" {\n\t\treturn util.CreateResponse(\"get-todo-response\", \"NOK\", \"No ID provided\", \"\"), nil\n\t}\n\n\tid, _ := uuid.Parse(idString)\n\tt, _ := GetTodo(id)\n\t// TODO(murp): add error checking here\n\n\ttbody, _ := json.Marshal(t)\n\treturn util.CreateResponse(\"get-todo-response\", \"OK\", \"\", string(tbody)), nil\n}", "func handleRequest(request *http.Request, t http.RoundTripper) (rsp *http.Response) {\n\tvar err error\n\n\tif rsp, err = t.RoundTrip(request); err != nil {\n\t\tlog.Println(\"Request failed:\", err)\n\t}\n\n\treturn\n}", "func (r *relay) handleRequest(reqId uint64, req []byte) {\n\trep := r.handler.HandleRequest(req)\n\tif err := r.sendReply(reqId, rep); err != nil {\n\t\tlog.Printf(\"iris: failed to send reply: %v.\", err)\n\t}\n}", "func (app *App) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\r\n\treturn func(w http.ResponseWriter, r *http.Request) {\r\n\t\thandler(app.DB, w, r)\r\n\t}\r\n}", "func (h HTTPHandlerFunc) HandleRequest(c context.Context, fc *fasthttp.RequestCtx) error {\n\treturn h(c, fc)\n}", "func (d *Dependencies) HandleRequest(req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {\n\n\tvar response events.APIGatewayV2HTTPResponse\n\tvar regionNodeResponse RegionNodeResponse\n\n\tvar request RegionRequest\n\n\tif(req.QueryStringParameters == nil){\n\t\tresponse.StatusCode = 500\n\t\ts := []string{fmt.Sprint(\"Oh noes!\")}\n\t\tregionNodeResponse.Errors = s\n\n\t\tb, _ := json.Marshal(regionNodeResponse)\n\t\tresponse.Body = string(b)\n\n\t\treturn response, errors.New(\"error \")\n\t}\n\n\treqMap := req.QueryStringParameters;\n\tfmt.Print(reqMap);\n\n\trequest.LevelType = reqMap[\"lvl\"]\n\trequest.RegionID = reqMap[\"rgn\"]\n\n\tif(request.LevelType == \"\" || request.RegionID == \"\"){\n\t\t//Bad request.\t\n\t\tresponse.StatusCode = 400\n\t\tb, _ := json.Marshal(response)\n\t\tresponse.Body = \"Bad request, missing params\" + string(b)\n\n\n\t}\n\n\t// Request items from DB.\n\tdb := d.ddb\n\ttable := d.tableID\n\n\tregionNodeResponse = getData(request, db, table)\n\t\n\tb, err := json.Marshal(regionNodeResponse)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error with marshalling request\")\n\t\tresponse.StatusCode = 500\n\t\ts := []string{fmt.Sprint(err)}\n\t\tregionNodeResponse.Errors = s\n\n\t} else {\n\t\tresponse.Body = string(b)\n\t\tresponse.StatusCode = 200\n\t}\n\n\treturn response, nil\n}", "func (s *Server) HandleRequest(w dns.ResponseWriter, r *dns.Msg) {\n\tresp := &dns.Msg{}\n\tresp.SetReply(r)\n\n\tfor _, q := range r.Question {\n\t\tans := s.handleQuestion(q)\n\t\tif ans != nil {\n\t\t\tresp.Answer = append(resp.Answer, ans...)\n\t\t}\n\t}\n\n\terr := w.WriteMsg(resp)\n\tif err != nil {\n\t\ts.logger.Println(\"ERROR : \" + err.Error())\n\t}\n\tw.Close()\n\n}", "func (h LogHandler) HandleRequest(c context.Context, fc *fasthttp.RequestCtx) error {\n\treturn logHandle(HTTPHandlerFunc(h), c, fc)\n}", "func (pi *PackageIndexer) HandleRequest(req Request) string {\n\t// bad request made \n\tif req.err != \"\" {\n\t\treturn ERROR \n\t}\n\t// set the name of the package \t\n\tpack := Package{name: req.pack}\t\t\t\t\t\t\t\t\n\t// add package dependencies \n\tfor _, name := range req.dep {\t\t\t\t\t\t\t\t \n\t\tpack.deps = append(pack.deps, &Package{name: name})\n\t}\n\t// check command type \n switch req.comm {\t\t\t\t\t\t\t\t\t\t\t\n case \"INDEX\":\n return pi.Index(&pack)\n case \"REMOVE\":\n return pi.Remove(&pack)\n case \"QUERY\":\n return pi.Query(pack.name)\n }\n\n // otherwise, error with request \n return ERROR \t\t\t\t\t\t\t\t\t\t\t\t\n}", "func (c *BFTChain) HandleRequest(sender uint64, req []byte) {\n\tc.Logger.Debugf(\"HandleRequest from %d\", sender)\n\tif _, err := c.verifier.VerifyRequest(req); err != nil {\n\t\tc.Logger.Warnf(\"Got bad request from %d: %v\", sender, err)\n\t\treturn\n\t}\n\tc.consensus.SubmitRequest(req)\n}", "func (c *Client) HandleRequest(req *http.Request) (res *http.Response, err error) {\n\treq.URL.Path = \"/api/v\" + c.APIVersion + req.URL.Path\n\n\t// Fill out Host and Scheme if it is empty\n\tif req.URL.Host == \"\" {\n\t\treq.URL.Host = c.URLHost\n\t}\n\tif req.URL.Scheme == \"\" {\n\t\treq.URL.Scheme = c.URLScheme\n\t}\n\tif req.Header.Get(\"User-Agent\") == \"\" {\n\t\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\t}\n\tif req.Header.Get(\"Authorization\") == \"\" {\n\t\treq.Header.Set(\"Authorization\", \"Bot \"+c.Token)\n\t}\n\n\tres, err = c.HTTP.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif res.StatusCode == http.StatusUnauthorized {\n\t\terr = errors.New(\"Invalid token passed\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (r *route) handleRequest(w http.ResponseWriter, req *http.Request) {\n pathParams := r.parsePatternParams(req.URL.Path)\n if req.URL.RawQuery != \"\" && pathParams != \"\" {\n req.URL.RawQuery += \"&\"\n }\n req.URL.RawQuery += pathParams\n r.handler.ServeHTTP(w,req)\n}", "func HandleRequest(w http.ResponseWriter, req *http.Request) {\n\trequest := &Request{id: atomic.AddUint64(&counter, 1), response: w, request: req}\n\n\trequests <- request\n\n\tfor {\n\t\tselect {\n\t\tcase result := <-results:\n\t\t\tlogger.Println(result)\n\t\t\treturn\n\t\t}\n\t}\n}", "func handleRequest(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// decode the event parameter\n\tvar data EventData\n\tif err := json.Unmarshal([]byte(event.Body), &data); err != nil {\n\t\treturn events.APIGatewayProxyResponse{StatusCode: 500}, err\n\t}\n\n\t// prepare the response string\n\tcurrentTime := time.Now()\n\tcurrentTimeStr := currentTime.Format(\"2006-01-02 15:04:05\")\n\tresponseStr := fmt.Sprintf(\"Hello from AWS Lambda, %s! Its %s\", data.Name, currentTimeStr)\n\n\t// return the response\n\treturn events.APIGatewayProxyResponse{Body: responseStr, StatusCode: 200}, nil\n}", "func HandleRequest(ctx context.Context) error {\n\tfmt.Println(\"Hello Go from Lambda!\")\n\treturn nil\n}", "func handleRequest() {\n\tmyRouter := mux.NewRouter().StrictSlash(true)\n\tmyRouter.HandleFunc(\"/\", homePage)\n\tmyRouter.HandleFunc(\"/all\", returnAllFacts).Methods(\"GET\")\n\tmyRouter.HandleFunc(\"/fact/{id}\", returnSingleFact).Methods(\"GET\")\n\tmyRouter.HandleFunc(\"/random\", returnRandomFact).Methods(\"GET\")\n\tmyRouter.HandleFunc(\"/fact\", createNewFact).Methods(\"POST\")\n\tmyRouter.HandleFunc(\"/fact/{id}\", updateFact).Methods(\"PUT\")\n\tmyRouter.HandleFunc(\"/fact/{id}\", deleteFact).Methods(\"DELETE\")\n\tlog.Fatal(http.ListenAndServe(\":10000\", myRouter))\n}", "func HandleRequest(w http.ResponseWriter, req *http.Request) {\n\t// Collect request parameters to add them to the entry HTTP span. We also need to make\n\t// sure that a proper span kind is set for the entry span, so that Instana could combine\n\t// it and its children into a call.\n\topts := []opentracing.StartSpanOption{\n\t\text.SpanKindRPCServer,\n\t\topentracing.Tags{\n\t\t\t\"http.host\": req.Host,\n\t\t\t\"http.method\": req.Method,\n\t\t\t\"http.protocol\": req.URL.Scheme,\n\t\t\t\"http.path\": req.URL.Path,\n\t\t},\n\t}\n\n\t// Check if there is an ongoing trace context provided with request and use\n\t// it as a parent for our entry span to ensure continuation.\n\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t)\n\tif err != nil {\n\t\topts = append(opts, ext.RPCServerOption(wireContext))\n\t}\n\n\t// Start the entry span adding collected tags and optional parent. The span name here\n\t// matters, as it allows Instana backend to classify the call as an HTTP one.\n\tspan := opentracing.GlobalTracer().StartSpan(\"g.http\", opts...)\n\tdefer span.Finish()\n\n\ttime.Sleep(300 * time.Millisecond)\n\tw.Write([]byte(\"Hello, world!\\n\"))\n}", "func HandleRequest(request events.APIGatewayProxyRequest) (Response, error) {\n\tlog.Println(\"start\")\n\n\teventsAPIEvent, err := getAPIEvents(request.Body)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn Response{\n\t\t\tStatusCode: 400,\n\t\t}, err\n\t}\n\n\tlog.Printf(\"eventsAPIEvent: %+v\\n\", eventsAPIEvent)\n\tswitch eventsAPIEvent.Type {\n\tcase slackevents.URLVerification:\n\t\treturn getChallengeResponse(request.Body)\n\tcase slackevents.CallbackEvent:\n\t\tinnerEvent := eventsAPIEvent.InnerEvent\n\t\tswitch ev := innerEvent.Data.(type) {\n\t\tcase *slackevents.AppMentionEvent:\n\t\t\treturn getMentionEventResponse(ev)\n\t\tcase *slackevents.MessageEvent:\n\t\t\treturn getDmEventResponse(ev)\n\t\tdefault:\n\t\t\tlog.Printf(\"unsupported event: %+v\\n\", ev)\n\t\t}\n\tdefault:\n\t\tlog.Printf(\"unsupported type: %+v\\n\", eventsAPIEvent)\n\t}\n\tlog.Println(\"no effect.\")\n\treturn Response{\n\t\tStatusCode: 400,\n\t}, nil\n}", "func HandleRequest(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\n\t// Slack sends its parameters as url encoded data in the request body. These need to be parsed to obtain the key/values. A list of the data slack sends can be seen [here](https://api.slack.com/interactivity/slash-commands).\n\n\t// Get slack params\n\tparams, err := url.ParseQuery(req.Body)\n\tif err != nil {\n\t\treturn internalError(fmt.Errorf(\"decoding slack params: %v\", err))\n\t}\n\ttext := params.Get(\"text\")\n\n\t// Do something. Anything you want really\n\t// Some cool code\n\n\t// Construct response data\n\tr := Response{\n\t\tType: \"in_channel\",\n\t\tText: fmt.Sprintf(\"You said '%s'\", text),\n\t}\n\n\tdata, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn events.APIGatewayProxyResponse{\n\t\t\tStatusCode: 500,\n\t\t\tBody: err.Error(),\n\t\t}, nil\n\t}\n\n\treturn events.APIGatewayProxyResponse{\n\t\tStatusCode: 200,\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t},\n\t\tBody: string(data),\n\t}, nil\n}", "func HandleRequest(client github.Client, event *github.GenericRequestEvent) error {\n\treturn plugins.HandleRequest(client, event)\n}", "func HandleRequest(m types.Message) (types.Response, error) {\n\n\tif m.Type != \"list-todos\" {\n\t\te := util.CreateResponse(\"list-todos-response\", \"NOK\", \"Handling incorrect message type - ignoring...\", \"\")\n\t\treturn e, nil\n\t}\n\n\ttableName = os.Getenv(\"TABLE_NAME\")\n\n\t// TODO(murp): add some error handling here\n\ttarray, _ := GetTodos()\n\n\ttbody, _ := json.Marshal(tarray)\n\treturn util.CreateResponse(\"list-todos-response\", \"OK\", \"\", string(tbody)), nil\n}", "func (api *Api) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\thandler(api.DB, w, r)\n\t}\n}", "func handleRequest(pc net.PacketConn, addr net.Addr, pr *PacketRequest, connectionSvc *ConnectionService) {\n\tif pr.Op == OpRRQ { // Read Request\n\t\tLogReadRequest(pr.Filename)\n\t\tdata, err := connectionSvc.openRead(addr.String(), pr.Filename)\n\t\tif err != nil {\n\t\t\tLogFileNotFound(pr.Filename)\n\t\t\tsendResponse(pc, addr, &PacketError{0x1, \"File not found (error opening file read)\"})\n\t\t} else {\n\t\t\tsendResponse(pc, addr, &PacketData{0x1, data})\n\t\t}\n\t} else if pr.Op == OpWRQ { // Write Request\n\t\tLogWriteRequest(pr.Filename)\n\t\tconnectionSvc.openWrite(addr.String(), pr.Filename)\n\t\tsendResponse(pc, addr, &PacketAck{0})\n\t}\n}", "func (srv *Server) handleRequest(msg *Message) {\n\tsrv.opsLock.Lock()\n\t// Reject incoming requests during shutdown, return special shutdown error\n\tif srv.shutdown {\n\t\tsrv.opsLock.Unlock()\n\t\tmsg.failDueToShutdown()\n\t\treturn\n\t}\n\tsrv.currentOps++\n\tsrv.opsLock.Unlock()\n\n\treplyPayload, returnedErr := srv.hooks.OnRequest(\n\t\tcontext.WithValue(context.Background(), Msg, *msg),\n\t)\n\tswitch returnedErr.(type) {\n\tcase nil:\n\t\tmsg.fulfill(replyPayload)\n\tcase ReqErr:\n\t\tmsg.fail(returnedErr)\n\tcase *ReqErr:\n\t\tmsg.fail(returnedErr)\n\tdefault:\n\t\tsrv.errorLog.Printf(\"Internal error during request handling: %s\", returnedErr)\n\t\tmsg.fail(returnedErr)\n\t}\n\n\t// Mark request as done and shutdown the server if scheduled and no ops are left\n\tsrv.opsLock.Lock()\n\tsrv.currentOps--\n\tif srv.shutdown && srv.currentOps < 1 {\n\t\tclose(srv.shutdownRdy)\n\t}\n\tsrv.opsLock.Unlock()\n}", "func HandleRequest(request Event) error {\n\tparams := config.ParseParams()\n\tgithubAPI := &github.APIService{BaseURL: params.GithubBaseURL, Token: params.GithubToken, Client: http.DefaultClient}\n\tslackAPI := &notification.SlackService{Client: http.DefaultClient}\n\n\tbranchService := &service.BranchService{\n\t\tParams: params,\n\t\tAPI: githubAPI,\n\t\tMsg: slackAPI,\n\t\tWg: &sync.WaitGroup{},\n\t}\n\n\t// first check validation token\n\ttoken := request.Query[\"token\"]\n\tif token != params.SlackCommandToken {\n\t\treturn errors.New(\"Incorrect validation token\")\n\t}\n\n\t// then check for respose webhook url\n\tresponseURL := request.Query[\"response_url\"]\n\tif responseURL == \"\" {\n\t\treturn errors.New(\"No response_url provided\")\n\t}\n\n\t// provide response to stop slack command from timing out\n\tslackAPI.Notify(responseURL, \"Processing request...\")\n\n\t// do branch check\n\tif message := branchService.GenerateStatusMessage(); message != \"\" {\n\t\tslackAPI.Notify(responseURL, message)\n\t\treturn nil\n\t}\n\n\terrorMsg := \"Error occurred while processing request\"\n\n\tslackAPI.Notify(responseURL, errorMsg)\n\treturn errors.New(errorMsg)\n}", "func (s *Server) handleRequest(req *SocksRequest, conn net.Conn) error {\n\t// Switch on the command\n\tswitch req.Command {\n\tcase connectCommand:\n\t\treturn s.handleConnect(req)\n\tcase bindCommand:\n\t\treturn s.handleBind(req)\n\tcase associateCommand:\n\t\treturn s.handleAssociate(req)\n\tdefault:\n\t\tif err := sendReply(conn, commandNotSupported, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to send reply: %v\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"Unsupported command: %v\", req.Command)\n\t}\n}", "func handleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\tvar err error\n\tvar resp interface{}\n\theaders := map[string]string{\n\t\t\"Access-Control-Allow-Headers\": \"Content-Type\",\n\t\t\"Access-Control-Allow-Origin\": \"*\",\n\t\t\"Access-Control-Allow-Methods\": \"GET\",\n\t}\n\n\tresp, err = getNovelList()\n\n\tif err != nil {\n\t\treturn events.APIGatewayProxyResponse{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tHeaders: headers,\n\t\t\tBody: err.Error(),\n\t\t}, err\n\t}\n\tformattedResp := formatResp(resp)\n\n\tresponse := events.APIGatewayProxyResponse{\n\t\tStatusCode: http.StatusOK,\n\t\tHeaders: headers,\n\t\tBody: formattedResp,\n\t}\n\treturn response, nil\n}", "func HandleRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodPost {\n\t\thttp.Error(w, fmt.Sprintf(\"Bad method %q\", r.Method), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\taction := r.FormValue(\"action\")\n\tswitch action {\n\tcase \"deleteUser\":\n\t\temail := r.FormValue(\"email\")\n\t\tif err := deleteUser(ctx, email); err != nil {\n\t\t\tlog.Printf(\"Failed deleting %v: %v\", email, err)\n\t\t\thttp.Error(w, fmt.Sprintf(\"Failed deleting %v: %v\", email, err), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"Deleted %v\\n\", email)\n\t\t}\n\tdefault:\n\t\thttp.Error(w, fmt.Sprintf(\"Invalid action %q\", action), http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func HandleRequest(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// TODO: check for cookie\n\n\tdb, err := episodic.NewDataBucket(os.Getenv(\"DATA_BUCKET\"), \"data.json\")\n\tif err != nil {\n\t\treturn events.APIGatewayProxyResponse{StatusCode: 500}, err\n\t}\n\n\tdata, err := db.Get()\n\tif err != nil {\n\t\treturn events.APIGatewayProxyResponse{StatusCode: 500}, err\n\t}\n\n\tidStr, ok := req.QueryStringParameters[\"id\"]\n\tif !ok {\n\t\treturn events.APIGatewayProxyResponse{StatusCode: 500}, errors.New(\"no id param found in query string\")\n\t}\n\n\tid, err := strconv.Atoi(idStr)\n\tif err != nil {\n\t\treturn events.APIGatewayProxyResponse{StatusCode: 500}, err\n\t}\n\n\tif data, err = db.RemoveEpisode(id); err != nil {\n\t\treturn events.APIGatewayProxyResponse{StatusCode: 500}, err\n\t}\n\n\tsort.Sort(episodic.ByAirDate(data.WatchList))\n\n\tjsonStr, err := json.Marshal(&Response{WatchList: data.WatchList})\n\tif err != nil {\n\t\treturn events.APIGatewayProxyResponse{StatusCode: 500}, err\n\t}\n\n\treturn events.APIGatewayProxyResponse{\n\t\tStatusCode: 200,\n\t\tHeaders: map[string]string{\n\t\t\t\"content-type\": \"application/json\",\n\t\t\t\"access-control-allow-origin\": \"*\",\n\t\t},\n\t\tBody: string(jsonStr),\n\t}, nil\n}", "func (auth *AuthManager) HandleRequest(w http.ResponseWriter, r *http.Request) error {\n\n\tlogger := GetLogManager().GetLogger()\n\n\t// remove /auth/ from url and split\n\tparts := strings.Split(r.URL.Path[len(AuthEndpoint)+2:], \"/\")\n\n\t// Check if it is an internal action\n\tif action, ok := auth.authActions[parts[0]]; ok {\n\t\tlogger.Printf(\"API builtin action called %q\", parts[0])\n\t\treturn action(w, r)\n\t}\n\n\treturn errors.New(\"Invalid operation\")\n}", "func HandleRequest(ctx context.Context, msg Message) (data.NewsReport, error) {\n\txray.Configure(xray.Config{LogLevel: \"trace\"})\n\tctx, seg := xray.BeginSegment(ctx, \"news-lambda-handler\")\n\n\t//\tSet the services to call with\n\tservices := []data.NewsService{\n\t\tdata.TwitterCNNService{},\n\t}\n\n\t//\tCall the helper method to get the report:\n\tresponse := data.GetNewsReport(ctx, services)\n\n\t//\tSet the service version information:\n\tresponse.Version = fmt.Sprintf(\"%s.%s\", BuildVersion, CommitID)\n\n\t//\tClose the segment\n\tseg.Close(nil)\n\n\t//\tReturn our response\n\treturn response, nil\n}", "func Handle(ctx context.Context, requestEnv *alexa.RequestEnvelope) (interface{}, error) {\n\treturn a.ProcessRequest(ctx, requestEnv)\n}", "func (d *Delete) HandleRequest(req *web.Request, res *web.Response) {\n\tresp := fmt.Sprintf(\"your method is [%s].\\n\", req.Method)\n\tres.WriteString(resp)\n\tres.Flush()\n}", "func HandleRequest(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\n\tmsg := Message{}\n\tlog.Printf(\"req.Body = %v\\n\", req.Body)\n\tif err := json.Unmarshal([]byte(req.Body), &msg); err != nil {\n\t\tlog.Printf(\"Executing defaultmessage lambda function\\n\")\n\t\treturn events.APIGatewayProxyResponse{\n\t\t\tStatusCode: 500,\n\t\t\tBody: \"Error parsing message\",\n\t\t}, nil\n\t}\n\n\tlog.Printf(\"Successful execution of defaultmessage lambda function\\n\")\n\treturn events.APIGatewayProxyResponse{\n\t\t//Body: msg.Content + \" (echoed)\",\n\t\tBody: \"{\\\"status\\\": 200}\",\n\t\tStatusCode: 200,\n\t}, nil\n}", "func (h ErrorHandler) HandleRequest(c context.Context, fc *fasthttp.RequestCtx) error {\n\treturn errorHandle(HTTPHandlerFunc(h), c, fc)\n}", "func handleRequest(function func() (interface{}, error), functionName string, w http.ResponseWriter, r *http.Request) {\n\tlog.Info(\">>>>> \" + functionName)\n\tdefer log.Info(\"<<<<< \" + functionName)\n\n\tvar chapiResp Response\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\n\terr := validateHost(id)\n\tif err != nil {\n\t\thandleError(w, chapiResp, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdata, err := function()\n\tif err != nil {\n\t\thandleError(w, chapiResp, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tchapiResp.Data = data\n\tjson.NewEncoder(w).Encode(chapiResp)\n}", "func (p *Plain_node) handleRequest(conn net.Conn) error {\n\t// Make a buffer to hold incoming data.\n\tdefer conn.Close()\n\n\tbuf := make([]byte, 1024)\n\n\t// Read the incoming connection into the buffer.\n\t_ , err := conn.Read(buf)\n\n\tif err != nil {\n\t\teprint(err)\n\t\treturn err\n\t}\n\n\tmsg := strings.Trim(string(buf), \"\\x00\")\n\tmsg = strings.Trim(msg, \"\\n\")\n\n\tswitch msg[0] {\n\t\tcase 'J':\n\t\t\tfmt.Println(DHT_PREFIX+\"Joinging Request Received.\")\n\t\t\tp.handle_join(msg, conn)\n\t\tcase 'A':\n\t\t\tfmt.Println(DHT_PREFIX+\"Join Ack Received.\")\n\t\t\tp.handle_join_ack(msg)\n\t\tcase 'B':\n\t\t\tfmt.Println(DHT_PREFIX+\"Newbie joined.\")\n\t\t\tp.add_newbie(msg)\n\t\tcase APP_PREFIX:\n\t\t\tfmt.Println(DHT_PREFIX+\"Application Data Received.\")\n\t\t\tforward_to_app(msg)\n\t\tdefault:\n\t\t\tfmt.Println(DHT_PREFIX+\"Unknown msg format\")\n\t\t//\tconn.Write([]byte(\"Don't Know What You Mean by\"+msg))\n\t}\n\n\treturn nil\n}", "func handleRequest(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, req *http.Request) {\n\t\tfn(rw, req)\n\t}\n}", "func HandleRequest(ctx context.Context, msg Message) (data.WeatherReport, error) {\n\txray.Configure(xray.Config{LogLevel: \"trace\"})\n\tctx, seg := xray.BeginSegment(ctx, \"weather-lambda-handler\")\n\n\t//\tSet the services to call with\n\tservices := []data.WeatherService{\n\t\tdata.OpenWeatherService{},\n\t}\n\n\t//\tCall the helper method to get the report:\n\tresponse := data.GetWeatherReport(ctx, services, msg.Latitude, msg.Longitude)\n\n\t//\tSet the service version information:\n\tresponse.Version = fmt.Sprintf(\"%s.%s\", BuildVersion, CommitID)\n\n\t//\tClose the segment\n\tseg.Close(nil)\n\n\t//\tReturn our response\n\treturn response, nil\n}", "func (h *ProtoHandler) HandleRequest(data []byte) []byte {\n\twrapper := &messages.RequestWrapper{}\n\terr := proto.Unmarshal(data, wrapper)\n\n\tresponse := &messages.ResponseWrapper{Ok: true}\n\n\tif err != nil {\n\t\tlogAndDecorateNegativeResponse(response, ErrorUnhandledRequestCode, ErrorUnhandledRequestMessage, err)\n\t\tbytes, _ := proto.Marshal(response)\n\n\t\treturn bytes\n\t}\n\n\tswitch rType := wrapper.GetRequestType(); rType {\n\tcase RequestTypeUsernamePasswordAuthentication:\n\t\tlog.WithField(\"type\", rType).Info(\"Received UsernamePassword authentication request\")\n\n\t\th.UsernamePasswordHandler.HandleAuthenticationRequest(wrapper, response)\n\t\tbreak\n\tcase RequestTypeUsernamePasswordAddUser:\n\t\tlog.WithField(\"type\", rType).Info(\"Received UsernamePassword add user request\")\n\t\th.UsernamePasswordHandler.HandleAddUserRequest(wrapper, response)\n\tcase RequestTypeTokenDiscover:\n\t\tlog.WithField(\"type\", rType).Info(\"Received TokenDiscover request\")\n\t\th.TokenHandler.HandleTokenDiscoverRequest(wrapper, response)\n\tdefault:\n\t\tlog.WithField(\"type\", rType).Warn(ErrorUnknownRequestTypeMessage)\n\t\tresponse.Ok = false\n\t\tresponse.ErrorCode = ErrorUnknownRequestTypeCode\n\t\tresponse.ErrorMessage = ErrorUnknownRequestTypeMessage\n\t\tbreak\n\t}\n\n\tresponseBytes, _ := proto.Marshal(response)\n\n\treturn responseBytes\n}", "func (p *stats) Handles(req *comm.Request) (res bool) {\n\treturn\n}", "func HandleRequest(process func(), u *User) bool {\n\t// TODO: time out and return false if process() is taking more than the user's\n\t// remaining time.\n\tnow := time.Now()\n\tprocess()\n\tu.TimeUsed += (time.Now().Sub(now))\n\n\treturn true\n}", "func handle(req typhon.Request, service, path string) typhon.Response {\n\turl := fmt.Sprintf(requestFormat, service, path)\n\n\tslog.Trace(req, \"Handling parsed URL: %v\", url)\n\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:80\", service))\n\tif err != nil {\n\t\tslog.Error(req, \"Unable to connect to %s: %v\", service, err)\n\t\treturn typhon.Response{Error: terrors.NotFound(\"service\", fmt.Sprintf(\"Unable to connect to %v\", service), nil)}\n\t}\n\tdefer conn.Close()\n\n\treq.Host = service\n\treq.URL.Scheme = \"http\"\n\treq.URL.Path = \"/\" + strings.TrimPrefix(path, \"/\")\n\treq.URL.Host = service\n\n\treturn req.Send().Response()\n}", "func HandleBufferRequest(op string, fn BufferReqHandler) {\n\tDefaultHandlers.HandleBufferRequest(op, fn)\n}", "func handleRequest(req string) string {\n\tresponse := \"\"\n\n\tif len(req) > 0 {\n\t\ts := strings.Split(req, \":\")\n\t\tif len(s) < 2 {\n\t\t\tresponse = \"0001:Invalid request\"\n\t\t} else {\n\t\t\tresponse = processRequest(s[0], s[1])\n\t\t}\n\t} else {\n\t\tresponse = \"0000:Empty request\"\n\t}\n\n\treturn response\n}", "func (h *MatchlistHandler) ProcessRequest(resp http.ResponseWriter, req *http.Request) {\n\tserverlog.Logger.Println(\"Received match list request\")\n\n\tif req.Method != \"GET\" {\n\t\tserverlog.Logger.Println(\"Wrong HTTP method used in matchlist request\")\n\t\thttp.Error(resp, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// GET parameters need to be parsed on-request\n\treq.ParseForm()\n\n\t// Authenticate user\n\tplayerID, token, err := GetPlayerDataFromGET(req)\n\tif err != nil {\n\t\tserverlog.Logger.Printf(\"Could not obtain player's credentials from GET: %v\", err.Error())\n\t\thttp.Error(resp, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t} else if !h.core.IsLoggedIn(playerID, token) {\n\t\tserverlog.Logger.Printf(\"Failed to authenticate token of player %v\", playerID)\n\t\thttp.Error(resp, \"Could not authenticate player's token\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tserverlog.Logger.Println(\"Retrieving match list\")\n\tmatchlist := h.core.GetMatchlistForJSON()\n\tif err != nil {\n\t\tserverlog.Logger.Printf(\"Could not obtain match list for player %v: %v\", playerID, err.Error())\n\t\thttp.Error(resp, \"Failed to retrieve match list: \"+err.Error(), http.StatusInternalServerError)\n\t}\n\n\tWriteJSONToResponse(resp, matchlist)\n\tserverlog.Logger.Printf(\"Response to matchlist request of player %v dispatched\", playerID)\n}", "func HandleRequest(ctx context.Context, evt *webhooks.Data) (*webhooks.DataResponse, error) {\n\trespCode, err := client.SendEvent(ctx, evt)\n\tif err != nil {\n\t\treturn &webhooks.DataResponse{StatusCode: 0, DeliveredTime: 0, Error: err.Error()}, err\n\t}\n\treturn &webhooks.DataResponse{StatusCode: respCode, DeliveredTime: time.Now().UnixNano()}, nil\n}", "func (h *MatchRoomHandler) ProcessRequest(resp http.ResponseWriter, req *http.Request) {\n\tserverlog.Logger.Println(\"Received match room request, will spawn a separate goroutine to handle communication\")\n\n\t// Obtain the connection object from the request\n\tconn, err := h.upgrader.Upgrade(resp, req, nil)\n\tif err != nil {\n\t\tserverlog.Logger.Printf(\"Failed to obtain connection object from request: %v\", err.Error())\n\t\thttp.Error(resp, \"Failed to obtain connection from request: \"+err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tgo h.handleWebSockConnection(conn)\n}", "func (g GetFamilySummary) HandleRequest(vars map[string]string) (interface{}, error) {\n\tvar loginInfo LoginTokenInfo\n\tvar err error\n\tvar family dbapi.Family\n\tif loginInfo, err = ParseLoginToken(g.Token); err != nil {\n\t\treturn family, err\n\t}\n\n\tfamily, err = dbapi.GetFamily(loginInfo.FamilyID)\n\tif err != nil {\n\t\treturn family, err\n\t}\n\n\tfamily.Kids, err = dbapi.GetKids(loginInfo.FamilyID)\n\tif err != nil {\n\t\treturn family, err\n\t}\n\n\tfor idx := range family.Kids {\n\t\tfamily.Kids[idx].Buckets, err = dbapi.GetBuckets(family.Kids[idx].ID)\n\t\tif err != nil {\n\t\t\treturn family, err\n\t\t}\n\t}\n\n\treturn family, err\n}", "func handleRequest(conn net.Conn, c *C) {\n\tc.Assert(conn, NotNil)\n\tdefer conn.Close()\n\tvar msg msgpb.Message\n\tmsgID, err := util.ReadMessage(conn, &msg)\n\tc.Assert(err, IsNil)\n\tc.Assert(msgID, Greater, uint64(0))\n\tc.Assert(msg.GetMsgType(), Equals, msgpb.MessageType_KvReq)\n\n\treq := msg.GetKvReq()\n\tc.Assert(req, NotNil)\n\tvar resp pb.Response\n\tresp.Type = req.Type\n\tmsg = msgpb.Message{\n\t\tMsgType: msgpb.MessageType_KvResp,\n\t\tKvResp: &resp,\n\t}\n\terr = util.WriteMessage(conn, msgID, &msg)\n\tc.Assert(err, IsNil)\n}", "func (d *Dependencies) HandleRequest(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\n\tvar response events.APIGatewayProxyResponse\n\tvar mapDataResponse MapDataResponse\n\n\tvar request []MapDataRequest\n\tfmt.Println(request)\n\terr := json.Unmarshal([]byte(req.Body), &request)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error with unmarshalling request\")\n\t\tfmt.Println(req.Body)\n\n\t\tresponse.StatusCode = 500\n\t\ts := []string{fmt.Sprint(err)}\n\t\tmapDataResponse.Errors = s\n\n\t\tb, _ := json.Marshal(mapDataResponse)\n\t\tresponse.Body = string(b)\n\n\t\treturn response, errors.New(\"error with unmarshalling request\")\n\t}\n\n\t//Validate Requests and trim long requests\n\tif len(request) >= 100 {\n\t\tfmt.Println(\"Trim request to 100 objects max\")\n\t\trequest = request[:99]\n\n\t}\n\n\t// Request items from DB.\n\tdb := d.ddb\n\ttable := d.tableID\n\n\tmapDataResponse = getBatchData(request, db, table)\n\t//Add name value.\n\tfor i := range mapDataResponse.MapData {\n\t\tmapDataResponse.MapData[i].RegionName = NameIndex[mapDataResponse.MapData[i].RegionID]\n\t}\n\n\t//getMetadata\n\t//This could be a slow point.\n\t//Most likely slow on startup / cold start\n\tfmt.Println(\"get the index that doesn't exists thingy\")\n\n\tif len(request) == 0 {\n\t\tresponse.StatusCode = 500\n\t\ts := []string{fmt.Sprint(\"Empty Request Array\")}\n\t\tmapDataResponse.Errors = s\n\t\treturn response, errors.New(\"error with empty request array\")\n\t}\n\n\tmapDataResponse.Metadata = MetadataMapMap[request[0].PartitionID]\n\n\tb, err := json.Marshal(mapDataResponse)\n\n\tif err != nil {\n\t\tfmt.Println(\"error with marshalling request\")\n\t\tresponse.StatusCode = 500\n\t\ts := []string{fmt.Sprint(err)}\n\t\tmapDataResponse.Errors = s\n\n\t} else {\n\t\tresponse.Body = string(b)\n\t\tresponse.StatusCode = 200\n\t}\n\n\t//fmt.Print(response)\n\t//fmt.Print(response.Body)\n\n\treturn response, nil\n}", "func (s *Server) HandleAccessRequest(w *Response, r *http.Request) *AccessRequest {\n\t// Only allow GET or POST\n\tif r.Method == \"GET\" {\n\t\tif !s.Config.AllowGetAccessRequest {\n\t\t\tw.SetError(E_INVALID_REQUEST, \"\")\n\t\t\tw.InternalError = errors.New(\"Request must be POST\")\n\t\t\treturn nil\n\t\t}\n\t} else if r.Method != \"POST\" {\n\t\tw.SetError(E_INVALID_REQUEST, \"\")\n\t\tw.InternalError = errors.New(\"Request must be POST\")\n\t\treturn nil\n\t}\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tw.SetError(E_INVALID_REQUEST, \"\")\n\t\tw.InternalError = err\n\t\treturn nil\n\t}\n\n\tgrantType := AccessRequestType(r.Form.Get(\"grant_type\"))\n\tif s.Config.AllowedAccessTypes.Exists(grantType) {\n\t\tswitch grantType {\n\t\tcase AUTHORIZATION_CODE:\n\t\t\treturn s.handleAuthorizationCodeRequest(w, r)\n\t\tcase REFRESH_TOKEN:\n\t\t\treturn s.handleRefreshTokenRequest(w, r)\n\t\tcase PASSWORD:\n\t\t\treturn s.handlePasswordRequest(w, r)\n\t\tcase CLIENT_CREDENTIALS:\n\t\t\treturn s.handleClientCredentialsRequest(w, r)\n\t\tcase ASSERTION:\n\t\t\treturn s.handleAssertionRequest(w, r)\n\t\t}\n\t}\n\n\tw.SetError(E_UNSUPPORTED_GRANT_TYPE, \"\")\n\treturn nil\n}", "func (h *Handler) Handle(c *gin.Context) {\n\tvar req Request\n\terr := c.BindJSON(&req)\n\tif err != nil {\n\t\treturn\n\t}\n\tresp := h.process(c, &req)\n\tc.JSON(http.StatusOK, resp)\n}", "func (s *Server) handleRequest(m *cloud.TokenRequest) (*cloud.TokenResponse, error) {\n\treq := request{m: m, ch: make(chan *response)}\n\tdefer close(req.ch)\n\ts.queue.queue <- req\n\tresp := <-req.ch\n\treturn resp.resp, resp.err\n}", "func (this *HTTPHandler) handle(req Request) Response {\n\tname := resources.NewObjectName(req.Namespace, req.Name)\n\tlogctx := this.NewContext(\"object\", name.String())\n\tlogctx.Infof(\"handle request for %s\", req.Resource)\n\tresp := this.webhook.Handle(logctx, req)\n\tif err := resp.Complete(req); err != nil {\n\t\tlogctx.Error(err, \"unable to encode response\")\n\t\treturn ErrorResponse(http.StatusInternalServerError, errUnableToEncodeResponse)\n\t}\n\treturn resp\n}", "func processRequest(rw http.ResponseWriter, req *http.Request) {\n\tif debugMode {\n\t\tlog.Println(fmt.Sprintf(`%s request received`, req.Method))\n\t}\n\tswitch req.Method {\n\tcase `GET`:\n\t\tfmt.Fprintf(rw, allLoggedData)\n\tcase `POST`:\n\t\tlogData(req)\n\tcase `PUT`:\n\t\tlogData(req)\n\tcase `DELETE`:\n\t\tallLoggedData = ``\n\tdefault:\n\t\tfmt.Fprintf(rw, `I don't recognize the request!`)\n\t}\n}", "func (svc *Service) HandleRequest(ctx context.Context, d time.Duration) error {\n\treqscope := svc.makeRequestScope()\n\tdefer reqscope.Exit(context.TODO())\n\n\t// spawn a watchdog agent but have it run more slowly than the request\n\t// processing so that it never fires (need predictable output for the test)\n\terr := spawnRequestWatchdog(ctx, reqscope, 10*d)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"pretending to work by sleeping for %s\\n\", d)\n\n\tselect {\n\tcase <-time.After(d):\n\tcase <-svc.stop:\n\t}\n\t// we don't have to clean up anything here as the deferred scope Exit\n\t// set up above will clean up the background request watchdog.\n\treturn nil\n}", "func HandleRequest(ctx context.Context, sqsEvent events.SQSEvent) error {\n\tlog.Println(\"The event received\")\n\tlog.Println(sqsEvent)\n\tvar messageBody MessageBody\n\tclient := sfn.New(session.Must(session.NewSession()))\n\tfor _, message := range sqsEvent.Records {\n\t\tjson.Unmarshal([]byte(message.Body), &messageBody)\n\t\tmessageTitle, _ := json.Marshal(messageBody.MessageTitle)\n\t\tparams := &sfn.SendTaskSuccessInput{\n\t\t\tOutput: aws.String(string(messageTitle)),\n\t\t\tTaskToken: aws.String(messageBody.TaskToken),\n\t\t}\n\t\t_, err := client.SendTaskSuccess(params)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}", "func (r *router) handle(c *Context) {\n\tn, params := r.getRoute(c.Method, c.Path) //if request method and path exist, return pattern of node and params\n\tif n != nil {\n\t\tc.Params = params\n\t\tc.handlers = append(c.handlers, n.handler) //insert handler after middleware\n\t} else {\n\t\tc.handlers = append(c.handlers, func(c *Context) {\n\t\t\tc.String(http.StatusNotFound, \"404 NOT FOUND: %s\\n\", c.Path)\n\t\t})\n\t}\n\tc.Next()\n}", "func (sr *sapmReceiver) handleRequest(req *http.Request) error {\n\tsapm, err := sapmprotocol.ParseTraceV2Request(req)\n\t// errors processing the request should return http.StatusBadRequest\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := sr.obsrecv.StartTracesOp(req.Context())\n\n\ttd, err := jaeger.ProtoToTraces(sapm.Batches)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif sr.config.AccessTokenPassthrough {\n\t\tif accessToken := req.Header.Get(splunk.SFxAccessTokenHeader); accessToken != \"\" {\n\t\t\trSpans := td.ResourceSpans()\n\t\t\tfor i := 0; i < rSpans.Len(); i++ {\n\t\t\t\trSpan := rSpans.At(i)\n\t\t\t\tattrs := rSpan.Resource().Attributes()\n\t\t\t\tattrs.PutStr(splunk.SFxAccessTokenLabel, accessToken)\n\t\t\t}\n\t\t}\n\t}\n\n\t// pass the trace data to the next consumer\n\terr = sr.nextConsumer.ConsumeTraces(ctx, td)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error passing trace data to next consumer: %w\", err)\n\t}\n\n\tsr.obsrecv.EndTracesOp(ctx, \"protobuf\", td.SpanCount(), err)\n\treturn err\n}", "func (ac *ActivationCheck) HandleRequest() error {\n\terr := ac.loadRequest(activationProtocol, ac)\n\tif err != nil {\n\t\tErrorf(\"loading request failed: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\treply := &ActivationReply{}\n\n\treply.ShouldActivate, err = ac.handler(ac.Agent, ac.config)\n\tif err != nil {\n\t\tErrorf(\"activation handler failed: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = ac.publishReply(reply)\n\tif err != nil {\n\t\tErrorf(\"publishing activation reply failed: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn nil\n}", "func (i Index) HandleRequest(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tpage := 1\n\tkeys, ok := r.URL.Query()[\"page\"]\n\tif ok && len(keys[0]) > 0 {\n\t\ti, err := strconv.Atoi(keys[0])\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\tpage = i\n\t}\n\tarticles, err := i.Repository.Fetch(100, page)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\tjson.NewEncoder(w).Encode(articles)\n}", "func HandleRequest(query []byte, conn *DatabaseConnection) {\n\tlog.Printf(\"Handling raw query: %s\", query)\n\tlog.Printf(\"Parsing request...\")\n\trequest, err := grammar.ParseRequest(query)\n\tlog.Printf(\"Parsed request\")\n\tvar response grammar.Response\n\n\tif err != nil {\n\t\tlog.Printf(\"Error in request parsing! %s\", err.Error())\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_INVALID_QUERY\n\t\tresponse.Data = err.Error()\n\t\tconn.Write(grammar.GetBufferFromResponse(response))\n\t}\n\n\tswitch request.Type {\n\tcase grammar.AUTH_REQUEST:\n\t\t// AUTH {username} {password}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_AUTH_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in AUTH request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\t// bucketname := tokens[2]\n\t\tlog.Printf(\"Client wants to authenticate.<username>:<password> %s:%s\", username, password)\n\n\t\tauthRequest := AuthRequest{Username: username, Password: password, Conn: conn}\n\t\tresponse = processAuthRequest(authRequest)\n\tcase grammar.SET_REQUEST:\n\t\t// SET {key} {value} [ttl] [nooverride]\n\t\trequest.Type = grammar.SET_RESPONSE\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_SET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in SET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tvalue := request.RequestData[1]\n\t\tlog.Printf(\"Setting %s:%s\", key, value)\n\t\tsetRequest := SetRequest{Key: key, Value: value, Conn: conn}\n\t\tresponse = processSetRequest(setRequest)\n\n\tcase grammar.GET_REQUEST:\n\t\t// GET {key}\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_GET_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in GET request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tkey := request.RequestData[0]\n\t\tlog.Printf(\"Client wants to get key '%s'\", key)\n\t\tgetRequest := GetRequest{Key: key, Conn: conn}\n\t\tresponse = processGetRequest(getRequest)\n\n\tcase grammar.DELETE_REQUEST:\n\t\t// DELETE {key}\n\t\tlog.Println(\"Client wants to delete a bucket/key\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_DELETE_REQUEST, true, true)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in DELETE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\t\t// TODO implement\n\tcase grammar.CREATE_BUCKET_REQUEST:\n\t\tlog.Println(\"Client wants to create a bucket\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_BUCKET_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE bucket request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketName := request.RequestData[0]\n\t\tcreateBucketRequest := CreateBucketRequest{BucketName: bucketName, Conn: conn}\n\n\t\tresponse = processCreateBucketRequest(createBucketRequest)\n\tcase grammar.CREATE_USER_REQUEST:\n\t\tlog.Printf(\"Client wants to create a user\")\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_CREATE_USER_REQUEST, false, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in CREATE user request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tusername := request.RequestData[0]\n\t\tpassword := request.RequestData[1]\n\t\tcreateUserRequest := CreateUserRequest{Username: username, Password: password, Conn: conn}\n\n\t\tresponse = processCreateUserRequest(createUserRequest)\n\tcase grammar.USE_REQUEST:\n\t\terrorStatus := checkRequirements(request, conn, grammar.LENGTH_OF_USE_REQUEST, true, false)\n\t\tif errorStatus != 0 {\n\t\t\tlog.Printf(\"Error in USE request! %d\", errorStatus)\n\t\t\tresponse.Status = errorStatus\n\t\t\tbreak\n\t\t}\n\n\t\tbucketname := request.RequestData[0]\n\t\tif bucketname == SALTS_BUCKET || bucketname == USERS_BUCKET {\n\t\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNAUTHORIZED\n\t\t\tbreak\n\t\t}\n\n\t\tuseRequest := UseRequest{BucketName: bucketname, Conn: conn}\n\t\tresponse = processUseRequest(useRequest)\n\tdefault:\n\t\tlog.Printf(illegalRequestTemplate, request.Type)\n\t\tresponse.Type = grammar.UNKNOWN_TYPE_RESPONSE\n\t\tresponse.Status = grammar.RESP_STATUS_ERR_UNKNOWN_COMMAND\n\t}\n\tif response.Status != 0 {\n\t\tlog.Printf(\"Error in request. status: %d\", response.Status)\n\t}\n\tconn.Write(grammar.GetBufferFromResponse(response))\n\tlog.Printf(\"Wrote buffer: %s to client\", grammar.GetBufferFromResponse(response))\n\n}", "func (cli *srvClient) processRequest(ctx context.Context, msgID int, pkt *Packet) error {\n\tctx, cancel := context.WithTimeout(ctx, cli.srv.processingTimeout)\n\tdefer cancel()\n\n\t// TODO: use context for deadlines and cancellations\n\tvar res Response\n\tswitch pkt.Tag {\n\tdefault:\n\t\t// _ = pkt.Format(os.Stdout)\n\t\treturn UnsupportedRequestTagError(pkt.Tag)\n\tcase ApplicationUnbindRequest:\n\t\treturn io.EOF\n\tcase ApplicationBindRequest:\n\t\t// TODO: SASL\n\t\treq, err := parseBindRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Bind(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationSearchRequest:\n\t\treq, err := parseSearchRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif req.BaseDN == \"\" && req.Scope == ScopeBaseObject { // TODO check filter\n\t\t\tres, err = cli.rootDSE(req)\n\t\t} else {\n\t\t\tres, err = cli.srv.Backend.Search(ctx, cli.state, req)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationAddRequest:\n\t\treq, err := parseAddRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Add(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationDelRequest:\n\t\treq, err := parseDeleteRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Delete(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyRequest:\n\t\treq, err := parseModifyRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.Modify(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationModifyDNRequest:\n\t\treq, err := parseModifyDNRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tres, err = cli.srv.Backend.ModifyDN(ctx, cli.state, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase ApplicationExtendedRequest:\n\t\treq, err := parseExtendedRequest(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch req.Name {\n\t\tdefault:\n\t\t\tres, err = cli.srv.Backend.ExtendedRequest(ctx, cli.state, req)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase OIDStartTLS:\n\t\t\tif cli.srv.tlsConfig == nil {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tBaseResponse: BaseResponse{\n\t\t\t\t\t\tCode: ResultUnavailable,\n\t\t\t\t\t\tMessage: \"TLS not configured\",\n\t\t\t\t\t},\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tres = &ExtendedResponse{\n\t\t\t\t\tName: OIDStartTLS,\n\t\t\t\t}\n\t\t\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := cli.wr.Flush(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcli.cn = tls.Server(cli.cn, cli.srv.tlsConfig)\n\t\t\t\tcli.wr.Reset(cli.cn)\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase OIDPasswordModify:\n\t\t\tvar r *PasswordModifyRequest\n\t\t\tif len(req.Value) != 0 {\n\t\t\t\tp, _, err := ParsePacket(req.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tr, err = parsePasswordModifyRequest(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr = &PasswordModifyRequest{}\n\t\t\t}\n\t\t\tgen, err := cli.srv.Backend.PasswordModify(ctx, cli.state, r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp := NewPacket(ClassUniversal, false, TagSequence, nil)\n\t\t\tif gen != nil {\n\t\t\t\tp.AddItem(NewPacket(ClassContext, true, 0, gen))\n\t\t\t}\n\t\t\tb, err := p.Encode()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: b,\n\t\t\t}\n\t\tcase OIDWhoAmI:\n\t\t\tv, err := cli.srv.Backend.Whoami(ctx, cli.state)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tres = &ExtendedResponse{\n\t\t\t\tValue: []byte(v),\n\t\t\t}\n\t\t}\n\t}\n\tif err := cli.cn.SetWriteDeadline(time.Now().Add(cli.srv.responseTimeout)); err != nil {\n\t\treturn fmt.Errorf(\"failed to set deadline for write: %w\", err)\n\t}\n\tdefer func() {\n\t\tif err := cli.cn.SetWriteDeadline(time.Time{}); err != nil {\n\t\t\tlog.Printf(\"failed to clear deadline for write: %s\", err)\n\t\t}\n\t}()\n\tif res != nil {\n\t\tif err := res.WritePackets(cli.wr, msgID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn cli.wr.Flush()\n}", "func HandleStreamRequest(op string, fn StreamReqHandler) {\n\tDefaultHandlers.HandleStreamRequest(op, fn)\n}", "func (p *Plugins) HandleRequest(client github.Client, event *github.GenericRequestEvent) error {\n\tcommands, err := ParseCommands(event.GetMessage())\n\tif err != nil {\n\t\treturn pluginerr.Wrap(err, \"Internal parse error\")\n\t}\n\n\tfor _, args := range commands {\n\t\tp.runPlugin(client, event, args)\n\t}\n\n\treturn nil\n}", "func HandleRequest(ctx context.Context, event events.APIGatewayProxyRequest) (\n\tevents.APIGatewayProxyResponse, error) {\n\n\t// make sure content-type is set to application/json\n\t// (any text type is fine, but can cause problems if no type specified)\n\tif event.Headers[\"content-type\"] != \"application/json\" {\n\t\treturn events.APIGatewayProxyResponse{\n\t\t\tBody: \"Request content-type header must be application/json.\",\n\t\t\tStatusCode: 400,\n\t\t}, nil\n\t}\n\n\t// make sure input json is valid\n\tvar payload PresignEvent\n\terr := json.Unmarshal([]byte(event.Body), &payload)\n\tif err != nil {\n\t\treturn events.APIGatewayProxyResponse{\n\t\t\tBody: \"Invalid JSON.\",\n\t\t\tStatusCode: 400,\n\t\t}, nil\n\t}\n\n\t// make sure key is specified\n\tif payload.Key == \"\" && payload.Type == \"GET\" {\n\t\treturn events.APIGatewayProxyResponse{\n\t\t\tBody: \"Input field 'key' must not be empty for GET request.\",\n\t\t\tStatusCode: 400,\n\t\t}, nil\n\t}\n\n\t// make sure type is specified\n\tpayload.Type = strings.ToUpper(payload.Type)\n\tif payload.Type != \"PUT\" && payload.Type != \"GET\" {\n\t\treturn events.APIGatewayProxyResponse{\n\t\t\tBody: \"Input field 'type' must be 'PUT' or 'GET'.\",\n\t\t\tStatusCode: 400,\n\t\t}, nil\n\t}\n\n\tif payload.Type == \"PUT\" {\n\t\treturn getPresignedPutUrl(event, payload)\n\t}\n\treturn getPresignedGetUrl(event, payload)\n}", "func handleRequests() {\n\thttp.HandleFunc(\"/\", homePage)\n\thttp.HandleFunc(\"/movies\", getAllMoviesSortedDetails)\n\tlog.Fatal(http.ListenAndServe(\":8081\", nil))\n}", "func (m *MockServer) HandleRequest(w http.ResponseWriter, r *http.Request) {\n\n\tvar response *MockResponse\n\tfor _, resp := range m.Responses {\n\t\tif !resp.satisfied && resp.Method == r.Method {\n\t\t\tresponse = resp\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif response == nil {\n\n\t\tif m.Checker != nil {\n\t\t\terrstr := fmt.Sprintf(\"Mock server: no matching response to request for %s:%s\\n\", r.Method, r.RequestURI)\n\t\t\tm.Checker.Fatal(errstr)\n\t\t}\n\n\t\tw.WriteHeader(http.StatusTeapot)\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tfmt.Fprintf(w, \"no matching response to request for %s:%s\\n\", r.Method, r.RequestURI)\n\n\t\treturn\n\t}\n\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tresponse.Hits++\n\tif !response.Persistant {\n\t\tresponse.satisfied = true\n\t}\n\n\tresponse.Request = r\n\tresponse.RequestBody = string(body)\n\n\tif response.CheckFn != nil {\n\t\tresponse.CheckFn(r, response.RequestBody)\n\t}\n\n\tm.Requests = append(m.Requests, r)\n\n\tw.WriteHeader(response.Code)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprintln(w, response.Body)\n}", "func (h *Handler) handleRequests() {\n\thttp.HandleFunc(\"/\", homePage)\n\thttp.HandleFunc(\"/customers\", h.returnAllCustomers)\n\tlog.Fatal(http.ListenAndServe(frontendPort, nil))\n}", "func Handle(req gohttp.Request) (gohttp.Response, error) {\n\tvar err error\n\n\tlogrus.Info(\"Value of body: \", string(req.GetBody()))\n\n\tmessage := fmt.Sprintf(\"Body: %s\", string(req.GetBody()))\n\n\treturn gohttp.FunctionResponse{\n\t\tBody: []byte(message),\n\t\tStatusCode: http.StatusAccepted,\n\t\tHeader: http.Header{\"Content-Type\": []string{\"text/plain\"}}}, err\n}", "func HandleRequest(request events.APIGatewayProxyRequest) (response events.APIGatewayProxyResponse, err error) {\n\tresponse.Headers = map[string]string{\"Access-Control-Allow-Origin\": \"*\"}\n\n\tvar (\n\t\tp TreeParam\n\t\tbuffer *bytes.Buffer\n\t)\n\n\tif err = json.Unmarshal([]byte(request.Body), &p); err != nil {\n\t\tresponse.StatusCode = 400\n\t\treturn\n\t}\n\tbuffer, err = createTree(p)\n\tif err != nil {\n\t\tresponse.StatusCode = 500\n\t\treturn\n\t}\n\n\tfileName := fmt.Sprintf(\"lambda-go-tree-%d.png\", time.Now().Unix())\n\t// Create a S3 client\n\tsession := session.Must(session.NewSession())\n\tsvc := s3.New(session)\n\n\treader := bytes.NewReader(buffer.Bytes())\n\tputInput := s3.PutObjectInput{\n\t\tBucket: aws.String(\"nicolasknoebber.com\"),\n\t\tBody: reader,\n\t\tKey: aws.String(fmt.Sprintf(\"/posts/images/trees/%s\", fileName)),\n\t}\n\n\t_, err = svc.PutObject(&putInput)\n\tif err != nil {\n\t\tresponse.StatusCode = 500\n\t\treturn\n\t}\n\n\tresponse.StatusCode = 200\n\tresponse.Body = fmt.Sprintf(`{\"message\":\"%s\"}`, fileName)\n\treturn\n}", "func (fH *FileHandler) HandleSearchRequest(packet core.GossipPacket, sender string) {\n\tsearchRequest := packet.SearchRequest\n\tif fH.isDuplicate(*searchRequest) {\n\t\treturn\n\t}\n\tgo fH.cacheRequest(*searchRequest)\n\tlocalMatches, found := fH.performLocalSearch(searchRequest.Keywords)\n\tif found {\n\t\tsearchReply := &core.SearchReply{\n\t\t\tOrigin: fH.ctx.Name,\n\t\t\tDestination: searchRequest.Origin,\n\t\t\tHopLimit: fH.ctx.GetHopLimit(),\n\t\t\tResults: localMatches,\n\t\t}\n\t\tgo fH.handleSearchReply(searchReply)\n\t}\n\tgo fH.forwardSearchRequest(sender, searchRequest, searchRequest.Budget-1)\n}", "func (o *OciServiceControl) HandleRequest(op string) error {\n\tswitch op {\n\tcase opStart, opStop, opRestart, opEnable, opDisable:\n\t\treturn o.do(op)\n\t// NOTE: INSTALL and UNINSTALL (REMOVE) is being handling via main()\n\tdefault:\n\t\treturn fmt.Errorf(\"Unsupported service request: %s\", op)\n\t}\n}", "func (handler *InterceptorRequestHandler) Handle(request string) (string, error) {\n\tlogrus.Debugf(\"Handle: %+v\", request)\n\tvar response *Response = nil\n\tselect {\n\tcase <-handler.Ctx.Done():\n\t\tresponse = ReturnFail(Code[HandlerClosed], Code[HandlerClosed].Msg)\n\tdefault:\n\t\t// decode\n\t\treq := &Request{}\n\t\terr := json.Unmarshal([]byte(request), req)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar ok = true\n\t\t// interceptor\n\t\tinterceptor := handler.Interceptor\n\t\tif interceptor != nil && !meta.Info.Debugging {\n\t\t\tresponse, ok = interceptor.Handle(req)\n\t\t}\n\t\tif ok {\n\t\t\t// Call Handler only when passing the interceptor\n\t\t\tresponse = handler.Handler.Handle(req)\n\t\t}\n\t}\n\t// encode\n\tbytes, err := json.Marshal(response)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes), nil\n}", "func (room *Room) HandleRequest(conn *Connection, rr *RoomRequest) {\n\tif room.done() {\n\t\treturn\n\t}\n\troom.wGroup.Add(1)\n\tdefer func() {\n\t\troom.wGroup.Done()\n\t}()\n\n\tif room == nil {\n\t\treturn\n\t}\n\n\tconn.debug(\"room handle conn\")\n\tif rr.IsGet() {\n\t\t//go room.greet(conn)\n\t} else if rr.IsSend() {\n\t\t//done := false\n\t\tswitch {\n\t\tcase rr.Send.Messages != nil:\n\t\t\tMessages(conn, rr.Send.Messages, room.Messages())\n\t\tcase rr.Send.Cell != nil:\n\t\t\tif room.isAlive(conn) {\n\t\t\t\tgo room.CellHandle(conn, rr.Send.Cell)\n\t\t\t}\n\t\tcase rr.Send.Action != nil:\n\t\t\troom.ActionHandle(conn, *rr.Send.Action)\n\t\t}\n\t} else if rr.Message != nil {\n\t\tif conn.Index() < 0 {\n\t\t\trr.Message.Status = models.StatusObserver\n\t\t} else {\n\t\t\trr.Message.Status = models.StatusPlayer\n\t\t}\n\t\tMessage(room.lobby, conn, rr.Message, room.appendMessage,\n\t\t\troom.setMessage, room.removeMessage, room.findMessage,\n\t\t\troom.send, room.InGame, true, room.ID)\n\t}\n}", "func (r *Router) ProcessRequest(req *http.Request) {\n\n\tp := req.URL.Path\n\tq := req.URL.Query()\n\n\tr.process2(p, q, req)\n\n}", "func (c CreateKid) HandleRequest(vars map[string]string) (interface{}, error) {\n\tvar loginInfo LoginTokenInfo\n\tvar err error\n\tif loginInfo, err = ParseLoginToken(c.Token); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkid, err := dbapi.CreateKid(loginInfo.FamilyID, c.KidName, c.KidEmail, c.WeeklyAllowance, c.Buckets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn createKidResponse{kid.ID}, nil\n}", "func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\tm.verifyHandler(w, r)\n\t\treturn\n\t}\n\n\tvar rec Receive\n\n\t// consume a *copy* of the request body\n\tbody, _ := ioutil.ReadAll(r.Body)\n\tr.Body = ioutil.NopCloser(bytes.NewBuffer(body))\n\n\terr := json.Unmarshal(body, &rec)\n\tif err != nil {\n\t\terr = xerrors.Errorf(\"could not decode response: %w\", err)\n\t\tfmt.Println(err)\n\t\tfmt.Println(\"could not decode response:\", err)\n\t\trespond(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif rec.Object != \"page\" {\n\t\tfmt.Println(\"Object is not page, undefined behaviour. Got\", rec.Object)\n\t\trespond(w, http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tif m.verify {\n\t\tif err := m.checkIntegrity(r); err != nil {\n\t\t\tfmt.Println(\"could not verify request:\", err)\n\t\t\trespond(w, http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t}\n\n\tm.dispatch(rec)\n\n\trespond(w, http.StatusAccepted) // We do not return any meaningful response immediately so it should be 202\n}", "func HandlePostRequest(w http.ResponseWriter, r *http.Request) {\n\n}", "func handleGetRequest(w http.ResponseWriter, r *http.Request) {\n\tapiPrefix := \"/api/\"\n\tmenuID := r.URL.Path[len(apiPrefix):]\n\tif menuID == \"\" {\n\t\thandleGetAllMenus(w, r)\n\t} else {\n\t\thandleGetMenu(w, r, menuID)\n\t}\n}", "func handleRequest(\n\tr *ssh.Request,\n\tsr func(\n\t\tname string,\n\t\twantReply bool,\n\t\tpayload []byte,\n\t) (bool, []byte, error),\n\tcl func() error,\n\tinfo string) {\n\t/* If this is the wrong sort of request, respond no */\n\tif s, ok := delayedReqs[r.Type]; ok {\n\t\tlog.Printf(\n\t\t\t\"%v Type:%v Delay:%v\",\n\t\t\tinfo,\n\t\t\tr.Type,\n\t\t\ts,\n\t\t)\n\t\ttime.Sleep(s)\n\t}\n\tlogRequest(r, info)\n\t/* Ask the other side */\n\tok, data, err := sr(r.Type, r.WantReply, r.Payload)\n\tif nil != err {\n\t\tlog.Printf(\n\t\t\t\"%v Unable to receive reply for %v request: %v\",\n\t\t\tinfo,\n\t\t\tr.Type,\n\t\t\terr,\n\t\t)\n\t\tcl()\n\t\treturn\n\t}\n\tlogRequestResponse(r, ok, data, info)\n\t/* Proxy back */\n\tif err := r.Reply(ok, nil); nil != err {\n\t\tlog.Printf(\n\t\t\t\"%v Unable to reply to %v request: %v\",\n\t\t\tinfo,\n\t\t\tr.Type,\n\t\t\terr,\n\t\t)\n\t\tcl()\n\t}\n}", "func (h *proxyHandler) processRequest(readBytes []byte) (rb replyBuf, terminate bool, err error) {\n\tvar req request\n\n\t// Parse the request JSON\n\tif err = json.Unmarshal(readBytes, &req); err != nil {\n\t\terr = fmt.Errorf(\"invalid request: %v\", err)\n\t\treturn\n\t}\n\t// Dispatch on the method\n\tswitch req.Method {\n\tcase \"Initialize\":\n\t\trb, err = h.Initialize(req.Args)\n\tcase \"OpenImage\":\n\t\trb, err = h.OpenImage(req.Args)\n\tcase \"OpenImageOptional\":\n\t\trb, err = h.OpenImageOptional(req.Args)\n\tcase \"CloseImage\":\n\t\trb, err = h.CloseImage(req.Args)\n\tcase \"GetManifest\":\n\t\trb, err = h.GetManifest(req.Args)\n\tcase \"GetConfig\":\n\t\trb, err = h.GetConfig(req.Args)\n\tcase \"GetFullConfig\":\n\t\trb, err = h.GetFullConfig(req.Args)\n\tcase \"GetBlob\":\n\t\trb, err = h.GetBlob(req.Args)\n\tcase \"GetLayerInfo\":\n\t\trb, err = h.GetLayerInfo(req.Args)\n\tcase \"FinishPipe\":\n\t\trb, err = h.FinishPipe(req.Args)\n\tcase \"Shutdown\":\n\t\tterminate = true\n\t// NOTE: If you add a method here, you should very likely be bumping the\n\t// const protocolVersion above.\n\tdefault:\n\t\terr = fmt.Errorf(\"unknown method: %s\", req.Method)\n\t}\n\treturn\n}", "func Handle(req []byte) string {\n\tlog.SetOutput(os.Stderr)\n\tvar n interface{}\n\terr := json.Unmarshal(req, &n)\n\tif err != nil {\n\t\tlog.Printf(\"unable to Unmarshal request. %v\", err)\n\t\treturn \"\"\n\t}\n\n\tdata := n.(map[string]interface{})\n\n\tlog.Println(data[\"Type\"])\n\tif data[\"Type\"].(string) == confirmation {\n\t\tsubscribeURL := data[\"SubscribeURL\"].(string)\n\t\tlog.Printf(\"SubscribeURL %v\", subscribeURL)\n\t\tconfirmSubscription(subscribeURL)\n\t\treturn \"just subscribed to \" + subscribeURL\n\t} else if data[\"Type\"].(string) == notification {\n\t\tmessage := data[\"Message\"].(string)\n\t\tlog.Println(\"Received this message : \", message)\n\t\treturn message\n\t}\n\n\tlog.Printf(\"Unknown data type %v\", data[\"Type\"])\n\treturn fmt.Sprintf(\"Unknown data type %v\", data[\"Type\"])\n}", "func handleRequests() {\n\n\thttp.HandleFunc(\"/\", home)\n\thttp.HandleFunc(\"/greet-me/\", greetMe)\n\thttp.HandleFunc(\"/books\", getBooks)\n\thttp.HandleFunc(\"/book\", createBook)\n\thttp.HandleFunc(\"/book/\", getBookById)\n\thttp.HandleFunc(\"/books/title/\", getBookByTitle)\n\n\tlog.Fatal(http.ListenAndServe(\":10000\", nil))\n}", "func (handler *AuthenticationHandler) HandleRequest(mapper map[string]string, redis redis.Redis, db dbsql.DB) model.Response {\n\tusername := mapper[model.CodeUsername]\n\tpassword := mapper[model.CodePassword]\n\terr := authentication.Authenticate(username, password, db)\n\tmapperResp := make(map[string]string)\n\tif err != nil {\n\t\tif err.Error() == authentication.ErrorNotAuthenticated {\n\t\t\tmapperResp[model.ResponseCode] = authentication.ErrorNotAuthenticated\n\t\t}\n\n\t\tmapperResp[model.ResponseCode] = err.Error()\n\t\treturn model.Response{ResponseID: model.ResponseOK, Data: mapperResp}\n\t}\n\n\tsessionID := stringutil.CreateRandomString(32)\n\tredis.Set(sessionID, username, 5*time.Hour)\n\tmapperResp[model.ResponseCode] = sessionID\n\n\treturn model.Response{ResponseID: model.ResponseOK, Data: mapperResp}\n}", "func (proxy *proxyService) handleRequest(\n\tw gohttp.ResponseWriter, r *gohttp.Request,\n) {\n\tlogger := proxy.logger\n\n\t// Per the stdlib docs, \"It is an error to set this field in an HTTP client\n\t// request\". Therefore, we ensure it is empty in case the client set it.\n\tr.RequestURI = \"\"\n\n\t// Send request to target service\n\n\tresp, err := proxy.transport.RoundTrip(r)\n\tif err != nil {\n\t\tlogger.Debugf(\"Error: %v\\n\", err)\n\t\tgohttp.Error(w, err.Error(), 503)\n\t\treturn\n\t}\n\n\t// Send response to client (everything below)\n\n\tlogger.Debugf(\"Received response status: %s\\n\", resp.Status)\n\n\tcopyHeaders(w.Header(), resp.Header)\n\n\tw.WriteHeader(resp.StatusCode)\n\n\t_, err = io.Copy(w, resp.Body)\n\tif err != nil {\n\t\tlogger.Errorf(\"Can't write response to body: %s\\n\", err)\n\t}\n\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\tlogger.Debugf(\"Can't close response body %v\\n\", err)\n\t}\n}", "func (d *ResourceHandler) ProcessRequest(request *Request, callback *Callback) int32 {\n\treturn lookupResourceHandlerProxy(d.Base()).ProcessRequest(d, request, callback)\n}", "func Handle(req []byte) string {\n\tlog.Println(\"Request with \", req)\n\tapi = CreateAPI()\n\tresult, err := api.All()\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\tjsonBytes, err := json.Marshal(result)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn string(jsonBytes)\n}" ]
[ "0.74420005", "0.72612906", "0.7180297", "0.7127764", "0.7055004", "0.70397246", "0.6982768", "0.6969357", "0.6969128", "0.69621074", "0.6961445", "0.6941809", "0.69207567", "0.6908853", "0.6908045", "0.68994975", "0.68979985", "0.6867785", "0.6861937", "0.6854056", "0.6848813", "0.6836692", "0.6836137", "0.68348485", "0.68311864", "0.68303263", "0.6828148", "0.68249947", "0.6815044", "0.67985725", "0.67795956", "0.67742765", "0.67542386", "0.6728119", "0.6714806", "0.67079794", "0.66977096", "0.6693502", "0.6685236", "0.6626948", "0.66208637", "0.6616571", "0.66112536", "0.6606251", "0.65933526", "0.65282863", "0.6527776", "0.65261734", "0.6524842", "0.6516669", "0.6503925", "0.6490972", "0.647121", "0.6464578", "0.6463264", "0.64615184", "0.64325523", "0.6424898", "0.64184356", "0.6401519", "0.6391168", "0.6382703", "0.6375487", "0.63716733", "0.6369161", "0.63645875", "0.6341701", "0.6323931", "0.6323704", "0.6318831", "0.6311951", "0.6307789", "0.6303051", "0.6297943", "0.6292859", "0.62846637", "0.6275514", "0.6266945", "0.625539", "0.6247774", "0.6243914", "0.62362474", "0.62362134", "0.62346226", "0.6217247", "0.6215442", "0.62133706", "0.6205728", "0.61949056", "0.6180447", "0.6165753", "0.6155166", "0.6145754", "0.61324465", "0.612965", "0.6123388", "0.61159265", "0.61093205", "0.6105851", "0.6068093" ]
0.73736703
1
New creates and returns (but does not start) a new KeyValueServer.
New создает и возвращает (но не запускает) новый KeyValueServer.
func New(store kvstore.KVStore) KeyValueServer { // TODO: implement this! var server keyValueServer server.clientNum = 0 server.listener = nil server.readChan = make(chan []byte) server.channelMap = make(map[net.Conn]chan []byte) // 使用接口时,返回接口类型变量, 参考 book p113 return &server }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New() KeyValueServer {\n\treturn &keyValueServer{\n\t\tnil,\n\t\tmake([]*client, 0),\n\t\tmake(chan *request),\n\t\tmake(chan *request),\n\t\tmake(chan []byte),\n\t\tmake(chan net.Conn),\n\t\tmake(chan int),\n\t\tmake(chan int),\n\t\tmake(chan *client),\n\t\tmake(chan int),\n\t\tmake(chan int)}\n}", "func New() KeyValueServer {\n\tinit_db()\n\tkvs := &keyValueServer{\n\t\tclienter: make(map[int]*Clienter),\n\t\tconnectedClients: -1,\n\t\tconnChannel: make(chan net.Conn),\n\t\tclose_signal: make(chan bool),\n\t\tcnt_signal_in: make(chan bool),\n\t\tcnt_signal_out: make(chan int),\n\t\tdelete: make(chan *Clienter),\n\t\treq: make(chan *Request),\n\t}\n\treturn kvs\n}", "func newServer(notifier *notifier, key string) *server {\n\treturn &server{\n\t\tnotifier: notifier,\n\t\tkey: key,\n\t}\n}", "func New(token string) *Server {\n\treturn &Server{\n\t\ttoken: token,\n\t\tproviders: make(map[string]provider),\n\t}\n}", "func New() *Server {\n\tdlog.Server.Info(\"Starting server\", version.String())\n\n\ts := Server{\n\t\tsshServerConfig: &gossh.ServerConfig{\n\t\t\tConfig: gossh.Config{\n\t\t\t\tKeyExchanges: config.Server.KeyExchanges,\n\t\t\t\tCiphers: config.Server.Ciphers,\n\t\t\t\tMACs: config.Server.MACs,\n\t\t\t},\n\t\t},\n\t\tcatLimiter: make(chan struct{}, config.Server.MaxConcurrentCats),\n\t\ttailLimiter: make(chan struct{}, config.Server.MaxConcurrentTails),\n\t\tsched: newScheduler(),\n\t\tcont: newContinuous(),\n\t}\n\n\ts.sshServerConfig.PasswordCallback = s.Callback\n\ts.sshServerConfig.PublicKeyCallback = server.PublicKeyCallback\n\n\tprivate, err := gossh.ParsePrivateKey(server.PrivateHostKey())\n\tif err != nil {\n\t\tdlog.Server.FatalPanic(err)\n\t}\n\ts.sshServerConfig.AddHostKey(private)\n\n\treturn &s\n}", "func New(srv *cmutation.Server) *Server {\n\treturn &Server{srv}\n}", "func New(prefix string, gIndex *osm.Data, styles map[string]map[string]config.Style) *Server {\n\treturn &Server{\n\t\tprefix: prefix,\n\t\tgIndex: gIndex,\n\t\tstyles: styles,\n\t}\n}", "func NewServer() *Server {}", "func New(path, listen string) (*Server, error) {\n\tcs, err := transport.Encode(listen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsqlPath := filepath.Join(path, \"storage.sql\")\n\tutil.EnsureAbsent(sqlPath)\n\n\ts := &Server{\n\t\tpath: path,\n\t\tlisten: listen,\n\t\tsql: sql.NewSQL(sqlPath),\n\t\trouter: mux.NewRouter(),\n\t\tclient: transport.NewClient(),\n\t\tcluster: NewCluster(path, cs),\n\t}\n\n\treturn s, nil\n}", "func New(m int, k int) *Server {\n\treturn &Server{bf: bloom.New(uint(m), uint(k))}\n}", "func New(path, listen string) (*Server, error) {\n\n\tcs, err := transport.Encode(listen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"Starting server at\" + cs)\n\n\tsqlPath := filepath.Join(path, \"storage.sql\")\n\tutil.EnsureAbsent(sqlPath)\n\n\ts := &Server{\n\t\tpath: path,\n\t\tlisten: listen,\n\t\tsql: sql.NewSQL(sqlPath),\n\t\trouter: mux.NewRouter(),\n\t\tclient: transport.NewClient(),\n block: false,\n\t}\n\n\treturn s, nil\n}", "func New() *Server {\n\treturn &Server{\n\t\tsystems: make(map[string]*system),\n\t}\n}", "func New(path string) (*KV, error) {\n\tb, err := bolt.Open(path, 0644, nil)\n\treturn &KV{db: b}, err\n}", "func New(st Storage) *Server {\n\tsrv := &Server{\n\t\tst: st,\n\t}\n\tsrv.setupRouter()\n\treturn srv\n}", "func New() *Server {\n\treturn &Server{}\n}", "func New() *Server {\n\treturn &Server{}\n}", "func New(\n\tserverID string,\n\ttracer *zipkin.Tracer,\n\tfS fetching.Service,\n\taS adding.Service,\n\tmS modifying.Service,\n\trS removing.Service,\n) Server {\n\ta := &server{\n\t\tserverID: serverID,\n\t\ttracer: tracer,\n\t\tfetching: fS,\n\t\tadding: aS,\n\t\tmodifying: mS,\n\t\tremoving: rS}\n\trouter(a)\n\n\treturn a\n}", "func New(\n\tserverID string,\n\ttracer *zipkin.Tracer,\n\tfS fetching.Service,\n\taS adding.Service,\n\tmS modifying.Service,\n\trS removing.Service,\n) Server {\n\ta := &server{\n\t\tserverID: serverID,\n\t\ttracer: tracer,\n\t\tfetching: fS,\n\t\tadding: aS,\n\t\tmodifying: mS,\n\t\tremoving: rS}\n\trouter(a)\n\n\treturn a\n}", "func New(addr string, password string) *KVStore {\n\tconst maxRetries = 5\n\n\tclient := redis.NewClient(&redis.Options{\n\t\tAddr: addr,\n\t\tMaxRetries: maxRetries,\n\t\tPassword: password,\n\t})\n\n\treturn &KVStore{client: client}\n}", "func New() *Server {\n\treturn &Server{\n\t\tusers: make(map[string]*User),\n\t}\n}", "func New() (*Server, error) {\n\treturn &Server{}, nil\n}", "func (t *OpenconfigSystem_System_Ntp_Servers) NewServer(Address string) (*OpenconfigSystem_System_Ntp_Servers_Server, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Server == nil {\n\t\tt.Server = make(map[string]*OpenconfigSystem_System_Ntp_Servers_Server)\n\t}\n\n\tkey := Address\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Server[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Server\", key)\n\t}\n\n\tt.Server[key] = &OpenconfigSystem_System_Ntp_Servers_Server{\n\t\tAddress: &Address,\n\t}\n\n\treturn t.Server[key], nil\n}", "func New(path, listen string) (*Server, error) {\n\tlog.Printf(\"Listen string %s\", listen)\n\n\tcs, err := transport.Encode(listen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsqlPath := filepath.Join(path, \"storage.sql\")\n\tutil.EnsureAbsent(sqlPath)\n\tpathParts := strings.Split(path, \"/\")\n\n\ts := &Server{\n\t\tpath: path,\n\t\tlisten: listen,\n\t\tsql: sql.NewSQL(sqlPath),\n\t\trouter: mux.NewRouter(),\n\t\tclient: transport.NewClient(),\n\t\tname: pathParts[3],\n\t\tconnectionString: cs,\n\t\tsqlCache: make(map[string][]byte),\n\t\tsequenceNumber: 0,\n\t}\n\n\treturn s, nil\n}", "func New(path string, host string, port int) *Server {\n\ts := &Server{\n\t\thost: host,\n\t\tport: port,\n\t\tpath: path,\n\t\t//\tfs: db.NewFs(),\n\t\trouter: mux.NewRouter(),\n\t\trecvQueryReqQ:make(chan *ServerRequestItem, 100000),\n\t\trecvUpdateReqQ:make(chan *ServerRequestItem, 100000),\n\t\tsendRespQ:make(chan *ServerResponceItem, 100000),\n\t}\n\ts.fs = db.NewFs(s.fsNotifyCb)\n\n\ts.facade = NewEventDispatcher(s)\n\ts.facade.AddEventListener(kEventLeaderChanged, s.eventListener)\n\n\tlog.Printf(\"filePath:%v\", filepath.Join(path, \"name\"))\n\t// Read existing name or generate a new one.\n\tif b, err := ioutil.ReadFile(filepath.Join(path, \"name\")); err == nil {\n\t\ts.name = string(b)\n\t} else {\n\t\ts.name = fmt.Sprintf(\"%07x\", rand.Int())[0:7]\n\t\tif err = ioutil.WriteFile(filepath.Join(path, \"name\"), []byte(s.name), 0644); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn s\n}", "func New(config Config) *Server {\n // templates\n tMutex := sync.RWMutex{}\n templates := make(map[string]*template.Template)\n\n return &Server{config: config,\n tMutex: tMutex,\n templates: templates,\n }\n}", "func New(bind string) *Server {\n\treturn &Server{bind}\n}", "func (t *OpenconfigSystem_System_Dns_Servers) NewServer(Address string) (*OpenconfigSystem_System_Dns_Servers_Server, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Server == nil {\n\t\tt.Server = make(map[string]*OpenconfigSystem_System_Dns_Servers_Server)\n\t}\n\n\tkey := Address\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Server[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Server\", key)\n\t}\n\n\tt.Server[key] = &OpenconfigSystem_System_Dns_Servers_Server{\n\t\tAddress: &Address,\n\t}\n\n\treturn t.Server[key], nil\n}", "func New(pipeName string, hnd daemon.Handler) *Server {\n\treturn nil\n}", "func New(addr string) *Server {\n if addr == \"\" {\n addr = DefaultAddr\n }\n return &Server{\n addr: DefaultAddr,\n ds: newDataStore(),\n done: make(chan struct{}),\n }\n}", "func New(basepath string, addr []string) *Server {\n\ts := server.NewServer()\n\tstore := make(map[string]fn)\n\n\tbasepath = strings.Trim(basepath, \"/\")\n\tbasepath = \"/\" + basepath\n\n\treturn &Server{store, s, basepath, addr, ModeDebug}\n}", "func NewServer() *server {\n\ts := &server{\n\t\tstore: make(map[string]*string),\n\t\tops: make(chan func()),\n\t}\n\tgo s.loop()\n\treturn s\n}", "func New(cfg config.ServerConfig, db database.Database) *Server {\n\treturn &Server{\n\t\trouter: gin.Default(),\n\t\tport: cfg.Port,\n\t\tdb: db,\n\t}\n}", "func New(bikeAccessor bike.Accessor) *Server {\n\treturn &Server{bikeAccessor: bikeAccessor}\n}", "func New(swaggerStore string, hugoStore string, runMode string, externalIP string, hugoDir string) (*Server, error) {\n\t// Return a new struct\n\treturn &Server{\n\t\tServiceMap: make(map[string]string),\n\t\tSwaggerStore: swaggerStore,\n\t\tHugoStore: hugoStore,\n\t\tRunMode: runMode,\n\t\tExternalIP: externalIP,\n\t\tHugoDir: hugoDir,\n\t}, nil\n}", "func New(name, group, address string) *Server {\n\ts := &Server{\n\t\tname: name,\n\t\tgroup: group,\n\t\taddress: address,\n\t}\n\n\treturn s\n}", "func New() *Server {\n\tr := gin.Default()\n\treturn &Server{Engine: r}\n}", "func (t *OpenconfigOfficeAp_System_Ntp_Servers) NewServer(Address string) (*OpenconfigOfficeAp_System_Ntp_Servers_Server, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Server == nil {\n\t\tt.Server = make(map[string]*OpenconfigOfficeAp_System_Ntp_Servers_Server)\n\t}\n\n\tkey := Address\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Server[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Server\", key)\n\t}\n\n\tt.Server[key] = &OpenconfigOfficeAp_System_Ntp_Servers_Server{\n\t\tAddress: &Address,\n\t}\n\n\treturn t.Server[key], nil\n}", "func (c *Client) New(serverKey string, env midtrans.EnvironmentType) {\n\tc.Env = env\n\tc.ServerKey = serverKey\n\tc.Options = &midtrans.ConfigOptions{}\n\tc.HttpClient = midtrans.GetHttpClient(env)\n}", "func (t *OpenconfigOfficeAp_System_Dns_Servers) NewServer(Address string) (*OpenconfigOfficeAp_System_Dns_Servers_Server, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Server == nil {\n\t\tt.Server = make(map[string]*OpenconfigOfficeAp_System_Dns_Servers_Server)\n\t}\n\n\tkey := Address\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Server[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Server\", key)\n\t}\n\n\tt.Server[key] = &OpenconfigOfficeAp_System_Dns_Servers_Server{\n\t\tAddress: &Address,\n\t}\n\n\treturn t.Server[key], nil\n}", "func New() *Server {\n\tcommandChannelsProducer := channels.CommandChannelsProducer{}\n\tcommandChannels := commandChannelsProducer.Produce()\n\n\tdataStreamerProducer := datastream.TcpDataStreamProducer{}\n\tdataStreamer := dataStreamerProducer.Produce()\n\n\tprotocolParserProducer := &protocol.ProtocolParserProducer{}\n\n\treturn &Server{\n\t\tcommandChannels: commandChannels,\n\t\tclientMutex: &sync.Mutex{},\n\t\tprotocolParserProducer: protocolParserProducer,\n\t\tdataStreamer: dataStreamer}\n}", "func New(\n\tdomain string,\n\tmachines []string,\n\toptions map[string]string,\n) (kvdb.Kvdb, error) {\n\tif len(machines) == 0 {\n\t\tmachines = defaultMachines\n\t} else {\n\t\tif strings.HasPrefix(machines[0], \"http://\") {\n\t\t\tmachines[0] = strings.TrimPrefix(machines[0], \"http://\")\n\t\t} else if strings.HasPrefix(machines[0], \"https://\") {\n\t\t\tmachines[0] = strings.TrimPrefix(machines[0], \"https://\")\n\t\t}\n\t}\n\tconfig := api.DefaultConfig()\n\tconfig.HttpClient = http.DefaultClient\n\tconfig.Address = machines[0]\n\tconfig.Scheme = \"http\"\n\n\tclient, err := api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &consulKV{\n\t\tclient,\n\t\tconfig,\n\t\tdomain,\n\t}, nil\n}", "func New(\n\tname string,\n\tkvdbName string,\n\tkvdbBase string,\n\tkvdbMachines []string,\n\tclusterID string,\n\tkvdbOptions map[string]string,\n) (AlertClient, error) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif _, ok := instances[name]; ok {\n\t\treturn nil, ErrExist\n\t}\n\tif initFunc, exists := drivers[name]; exists {\n\t\tdriver, err := initFunc(\n\t\t\tkvdbName,\n\t\t\tkvdbBase,\n\t\t\tkvdbMachines,\n\t\t\tclusterID,\n\t\t\tkvdbOptions,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinstances[name] = driver\n\t\treturn driver, err\n\t}\n\treturn nil, ErrNotSupported\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 New(address string) *Server {\n\treturn &Server{\n\t\taddress: address,\n\t\thandlerGet: NewGetHandler(&get.Getter{}),\n\t\thandlerList: NewListHandler(&list.Lister{}),\n\t\thandlerNotFound: notFoundHandler,\n\t\thandlerRegister: NewRegisterHandler(&register.Registerer{}),\n\t}\n}", "func newDummyKeyServer() *server {\n\tdummy, _ := storagetest.DummyStorage(nil)\n\treturn &server{storage: dummy}\n}", "func New() *Server {\n\tsv := &Server{\n\t\tE: echo.New(),\n\t\tH: handlers.New(),\n\t}\n\tsv.routes()\n\treturn sv\n}", "func New(addr string) *Server {\n\tsrv := new(Server)\n\tsrv.Context = new(Context)\n\tsrv.Context.Channels = make(map[string]*channel.Channel)\n\tsrv.Address = addr\n\treturn srv\n}", "func New(pathToUnixSocketFile string) (*KMSServiceServer, error) {\n\tkmsServiceServer := new(KMSServiceServer)\n\tkmsServiceServer.pathToUnixSocket = pathToUnixSocketFile\n\tfmt.Println(kmsServiceServer.pathToUnixSocket)\n\tkmsServiceServer.azConfig, _ = GetAzureAuthConfig(configFilePath)\n\tif kmsServiceServer.azConfig.SubscriptionID == \"\" {\n\t\treturn nil, fmt.Errorf(\"Missing SubscriptionID in azure config\")\n\t}\n\tvaultName, keyName, keyVersion, err := GetKMSProvider(configFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkmsServiceServer.providerVaultName = vaultName\n\tkmsServiceServer.providerKeyName = keyName\n\tkmsServiceServer.providerKeyVersion = keyVersion\n\n\treturn kmsServiceServer, nil\n}", "func New(config Config, storageConfig storage.Config) *Server {\n\tstore, err := storage.New(storageConfig)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\thandler := NewHandler(config, store)\n\thandler.RegisterRoutes()\n\n\treturn &Server{\n\t\tconfig: config,\n\t\tserver: http.Server{\n\t\t\tHandler: handler.Router,\n\t\t\tWriteTimeout: config.WriteTimeout,\n\t\t\tReadTimeout: config.ReadTimeout,\n\t\t\tIdleTimeout: config.IdleTimeout,\n\t\t},\n\t\tstore: store,\n\t}\n}", "func newConfigServer() *ConfigServer {\n\treturn &ConfigServer{}\n}", "func New(config Config) *Server {\n\treturn &Server{\n\t\tconfig: config,\n\t\tregistrars: make([]Registration, 0, 1),\n\t}\n}", "func New(db datalog.DB) *Server {\n\treturn &Server{\n\t\tDB: db,\n\t}\n}", "func New(client remote.Client) (*Server, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := Server{\n\t\tctx: ctx,\n\t\tctxCancel: &cancel,\n\t\tclient: client,\n\t\tinstalling: system.NewAtomicBool(false),\n\t\ttransferring: system.NewAtomicBool(false),\n\t\trestoring: system.NewAtomicBool(false),\n\t\tpowerLock: system.NewLocker(),\n\t\tsinks: map[system.SinkName]*system.SinkPool{\n\t\t\tsystem.LogSink: system.NewSinkPool(),\n\t\t\tsystem.InstallSink: system.NewSinkPool(),\n\t\t},\n\t}\n\tif err := defaults.Set(&s); err != nil {\n\t\treturn nil, errors.Wrap(err, \"server: could not set default values for struct\")\n\t}\n\tif err := defaults.Set(&s.cfg); err != nil {\n\t\treturn nil, errors.Wrap(err, \"server: could not set defaults for server configuration\")\n\t}\n\ts.resources.State = system.NewAtomicString(environment.ProcessOfflineState)\n\treturn &s, nil\n}", "func NewServer(config *Config, serverConfig *ServerConfig) *Server {\n\tformat := serverConfig.Format\n\tif format == nil {\n\t\tformat = config.DefaultFormat\n\t}\n\n\tserver := &Server{\n\t\tid: serverConfig.ID,\n\t\tlock: sync.Mutex{},\n\t\tstopper: gstop.New(),\n\t\tformat: format,\n\t\trouters: make(map[int64]*Router, defaultMapSize),\n\t\tworkers: make(map[string]*worker, defaultMapSize),\n\t}\n\n\tif existsServer, ok := serverDB[server.id]; ok {\n\t\t_ = existsServer.Stop()\n\n\t\tdelete(serverDB, server.id)\n\t}\n\n\tserverDB[server.id] = server\n\n\tserver.initial(config, serverConfig)\n\n\treturn server\n}", "func New(h *handler.Handler, c *config.Config) {\n\ttokenAuth = jwtauth.New(\"HS256\", []byte(c.Token), nil)\n\tr := chi.NewRouter()\n\ts := &server{\n\t\thand: h,\n\t\trouter: r,\n\t\taddress: c.Address,\n\t}\n\ts.makeHandlers()\n\ts.startServer()\n}", "func (t *OpenconfigSystem_System_Aaa_ServerGroups_ServerGroup_Servers) NewServer(Address string) (*OpenconfigSystem_System_Aaa_ServerGroups_ServerGroup_Servers_Server, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Server == nil {\n\t\tt.Server = make(map[string]*OpenconfigSystem_System_Aaa_ServerGroups_ServerGroup_Servers_Server)\n\t}\n\n\tkey := Address\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Server[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Server\", key)\n\t}\n\n\tt.Server[key] = &OpenconfigSystem_System_Aaa_ServerGroups_ServerGroup_Servers_Server{\n\t\tAddress: &Address,\n\t}\n\n\treturn t.Server[key], nil\n}", "func New(config *config.ConsulConfig) (*KVHandler, error) {\n\tclient, err := newAPIClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger := log.WithFields(log.Fields{\n\t\t\"caller\": \"consul\",\n\t})\n\n\tkv := client.KV()\n\n\thandler := &KVHandler{\n\t\tAPI: kv,\n\t\tKVTxnOps: nil,\n\t\tlogger: logger,\n\t}\n\n\treturn handler, nil\n}", "func New() *Server {\n\ts := &Server{\n\t\thandlers: map[string][]HandlerFunc{},\n\t\tclosing: make(chan struct{}),\n\t\tclosed: make(chan struct{}),\n\t}\n\ts.pool.New = func() interface{} {\n\t\treturn s.allocateContext()\n\t}\n\treturn s\n}", "func NewKeyValue(name string, newType StorageType) *KeyValue {\n\tswitch newType {\n\n\tcase MEMORY:\n\t\t// TODO: No Merkle tree?\n\t\treturn &KeyValue{\n\t\t\tType: newType,\n\t\t\tName: name,\n\t\t\tmemory: db.NewMemDB(),\n\t\t}\n\n\tcase PERSISTENT:\n\t\tfullname := \"OneLedger-\" + name\n\n\t\tif FileExists(fullname, global.DatabaseDir()) {\n\t\t\t//log.Debug(\"Appending to database\", \"name\", fullname)\n\t\t} else {\n\t\t\tlog.Info(\"Creating new database\", \"name\", fullname)\n\t\t}\n\n\t\tstorage, err := db.NewGoLevelDB(fullname, global.DatabaseDir())\n\t\tif err != nil {\n\t\t\tlog.Error(\"Database create failed\", \"err\", err)\n\t\t\tpanic(\"Can't create a database \" + global.DatabaseDir() + \"/\" + fullname)\n\t\t}\n\n\t\ttree := iavl.NewMutableTree(storage, 100)\n\n\t\t// Note: the tree is empty, until at least one version is loaded\n\t\ttree.LoadVersion(0)\n\n\t\treturn &KeyValue{\n\t\t\tType: newType,\n\t\t\tName: name,\n\t\t\tFile: fullname,\n\t\t\ttree: tree,\n\t\t\tdatabase: storage,\n\t\t\tversion: tree.Version64(),\n\t\t}\n\tdefault:\n\t\tpanic(\"Unknown Type\")\n\n\t}\n\treturn nil\n}", "func New(conf *Settings) (s *Server, err error) {\n\tif conf == nil {\n\t\tif conf, err = Config(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Set the global level\n\tzerolog.SetGlobalLevel(zerolog.Level(conf.LogLevel))\n\n\t// Set human readable logging if specified\n\tif conf.ConsoleLog {\n\t\tlog.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})\n\t}\n\n\ts = &Server{conf: conf, echan: make(chan error, 1)}\n\tif s.db, err = gorm.Open(sqlite.Open(conf.DatabaseDSN), &gorm.Config{}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = MigrateDB(s.db); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: mark the VASP local based on name or configuration rather than erroring\n\tif err = s.db.Where(\"is_local = ?\", true).First(&s.vasp).Error; err != nil {\n\t\treturn nil, fmt.Errorf(\"could not fetch local VASP info from database: %s\", err)\n\t}\n\n\tif s.conf.Name != s.vasp.Name {\n\t\treturn nil, fmt.Errorf(\"expected name %q but have database name %q\", s.conf.Name, s.vasp.Name)\n\t}\n\n\t// Create the TRISA service\n\tif s.trisa, err = NewTRISA(s); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create TRISA service: %s\", err)\n\t}\n\n\t// Create the remote peers using the same credentials as the TRISA service\n\ts.peers = peers.New(s.trisa.certs, s.trisa.chain, s.conf.DirectoryServiceURL)\n\ts.updates = NewUpdateManager()\n\treturn s, nil\n}", "func New() kv.Store {\n\treturn newStore(newMapStore())\n}", "func New(cfg *Config) *Server {\n\tdefaultConfig(cfg)\n\tlog.Printf(\"%+v\\n\", cfg)\n\treturn &Server{\n\t\tcfg: cfg,\n\t\thandlers: make([]connectionHandler, cfg.Count),\n\t\tevents: make(chan eventWithData, cfg.Count),\n\t}\n}", "func CreateNewServer() *exchangeServer {\n\treturn &exchangeServer{make(map[string]Endpoint), nil}\n}", "func New(host, port string, handlers handler.Param) *Kyma {\n\tsrv := server.New(host, port, handlers)\n\treturn &Kyma{\n\t\tServing: srv,\n\t\tConnector: connector.New(srv, \"/kyma\"),\n\t}\n}", "func New(config *Config) *Keystore {\n\tif config == nil {\n\t\tconfig = defaultConfig\n\t}\n\treturn &Keystore{config}\n}", "func New(cfg Config) (a APIServer, err error) {\n\tvar ds datastore.DataStore\n\tswitch cfg.Datastore.Type {\n\tcase \"mongodb\":\n\t\tds, err = mongodb.New(context.Background(), cfg.Datastore)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"create mongodb datastore instance failure %w\", err)\n\t\t}\n\tcase \"kubeapi\":\n\t\tds, err = kubeapi.New(context.Background(), cfg.Datastore)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"create kubeapi datastore instance failure %w\", err)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"not support datastore type %s\", cfg.Datastore.Type)\n\t}\n\n\ts := &restServer{\n\t\twebContainer: restful.NewContainer(),\n\t\tcfg: cfg,\n\t\tdataStore: ds,\n\t}\n\treturn s, nil\n}", "func New(path string, host string, port int) *Server {\r\n\ts := &Server{\r\n\t\thost: host,\r\n\t\tport: port,\r\n\t\tpath: path,\r\n\t\trouter: mux.NewRouter(),\r\n\t}\r\n\r\n\t// Read existing name or generate a new one.\r\n\tif b, err := ioutil.ReadFile(filepath.Join(path, \"name\")); err == nil {\r\n\t\ts.name = string(b)\r\n\t} else {\r\n\t\ts.name = fmt.Sprintf(\"%07x\", rand.Int())[0:7]\r\n\t\tif err = ioutil.WriteFile(filepath.Join(path, \"name\"), []byte(s.name), 0644); err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t}\r\n\r\n\treturn s\r\n}", "func NewServer() *Server {\n return &Server{\n Addr: DefaultAddr,\n }\n}", "func New(conf *Config) (*Server, error) {\n\t// Ensure we have at least one authentication method enabled\n\tif len(conf.authMethods) == 0 {\n\t\tif conf.credentials != nil {\n\t\t\tconf.authMethods = []authenticator{&UserPassAuthenticator{conf.credentials}}\n\t\t} else {\n\t\t\tconf.authMethods = []authenticator{&NoAuthAuthenticator{}}\n\t\t}\n\t}\n\n\tserver := &Server{\n\t\tconfig: conf,\n\t}\n\n\tserver.authMethods = make(map[uint8]authenticator)\n\n\tfor _, a := range conf.authMethods {\n\t\tserver.authMethods[a.getCode()] = a\n\t}\n\n\treturn server, nil\n}", "func New(dir string) *Server {\n\tsrv := &Server{\n\t\tquit: make(chan int),\n\t\tcookies: make(map[string]*http.Cookie),\n\t\tsessions: make(map[string]*DB),\n\t\tdir: dir,\n\t}\n\n\tgo srv.run()\n\treturn srv\n}", "func New(config *Config) *Server {\n\ts := &Server{\n\t\tconfig: config,\n\t\trouter: chi.NewRouter(),\n\t\tlogger: newLogger(config.LogDebug),\n\t}\n\n\treturn s\n}", "func New(cfg *viper.Viper) *Server {\n\tsrv := &Server{cfg: cfg}\n\n\t// Create App Context\n\tsrv.runCtx, srv.runCancel = context.WithCancel(context.Background())\n\n\t// Initiate a new logger\n\tsrv.log = logrus.New()\n\tif srv.cfg.GetBool(\"debug\") {\n\t\tsrv.log.Level = logrus.DebugLevel\n\t\tsrv.log.Debug(\"Enabling Debug Logging\")\n\t}\n\tif srv.cfg.GetBool(\"trace\") {\n\t\tsrv.log.Level = logrus.TraceLevel\n\t\tsrv.log.Debug(\"Enabling Trace Logging\")\n\t}\n\tif srv.cfg.GetBool(\"disable_logging\") {\n\t\tsrv.log.Level = logrus.FatalLevel\n\t}\n\n\treturn srv\n\n}", "func New(addr string, port int) *Server {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Server{\n\t\taddr: addr,\n\t\tport: port,\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\t}\n}", "func New(factory func() interface{}) *Server {\n\tt := topic.New()\n\tt.AddSubscriber(1, &subscriber{state: factory()})\n\treturn &Server{topic: t}\n}", "func New(e *todo.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tGetH: NewGetHandler(e.Get, uh),\n\t\tListH: NewListHandler(e.List, uh),\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t\tRemoveH: NewRemoveHandler(e.Remove, uh),\n\t}\n}", "func (t *OpenconfigOfficeAp_System_Aaa_ServerGroups_ServerGroup_Servers) NewServer(Address string) (*OpenconfigOfficeAp_System_Aaa_ServerGroups_ServerGroup_Servers_Server, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Server == nil {\n\t\tt.Server = make(map[string]*OpenconfigOfficeAp_System_Aaa_ServerGroups_ServerGroup_Servers_Server)\n\t}\n\n\tkey := Address\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Server[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Server\", key)\n\t}\n\n\tt.Server[key] = &OpenconfigOfficeAp_System_Aaa_ServerGroups_ServerGroup_Servers_Server{\n\t\tAddress: &Address,\n\t}\n\n\treturn t.Server[key], nil\n}", "func New(sto store.Service) *server {\n\ts := &server{sto: sto}\n\n\trouter := mux.NewRouter()\n\n\trouter.Handle(\"/todo\", allowedMethods(\n\t\t[]string{\"OPTIONS\", \"GET\", \"POST\"},\n\t\thandlers.MethodHandler{\n\t\t\t\"GET\": http.HandlerFunc(s.getTodos),\n\t\t\t\"POST\": http.HandlerFunc(s.createTodo),\n\t\t}))\n\n\trouter.Handle(\"/todo/{id}\", idMiddleware(allowedMethods(\n\t\t[]string{\"OPTIONS\", \"GET\", \"PUT\", \"PATCH\", \"DELETE\"},\n\t\thandlers.MethodHandler{\n\t\t\t\"GET\": http.HandlerFunc(s.getTodo),\n\t\t\t\"PUT\": http.HandlerFunc(s.putTodo),\n\t\t\t\"PATCH\": http.HandlerFunc(s.patchTodo),\n\t\t\t\"DELETE\": http.HandlerFunc(s.deleteTodo),\n\t\t})))\n\n\ts.handler = limitBody(defaultHeaders(router))\n\n\treturn s\n}", "func New(cfg *config.Config, store *jot.JotStore, manager *auth.PasswordManager) *Server {\n\treturn &Server{\n\t\tmanager: manager,\n\t\tstore: store,\n\t\tcfg: cfg,\n\t}\n}", "func New(\n\taddr string,\n\thandler Handler,\n\tlog *log.Logger,\n\tworkersCount uint8,\n) (srv *Server) {\n\tsrv = &Server{\n\t\taddr: addr,\n\t\thandler: handler,\n\t\tlog: log,\n\t\tClients: newClients(),\n\t\tchStop: make(chan bool, 1),\n\t\tchRequest: make(chan *tRequest, workersCount),\n\t}\n\n\treturn\n}", "func New(key string) Context {\n\treturn NewWithKind(DefaultKind, key)\n}", "func New(auth Authorizer, errorWriter ErrorWriter, clean CleanCredentials) *Server {\n\treturn &Server{\n\t\tpeers: map[string]peer{},\n\t\tauthorizer: auth,\n\t\tcleanCredentials: clean,\n\t\terrorWriter: errorWriter,\n\t\tsessions: newSessionManager(),\n\t}\n}", "func New(appStateUpdater env.AppStateUpdater, config libkbfs.Config) (\n\ts *Server, err error) {\n\tlogger := config.MakeLogger(\"HTTP\")\n\ts = &Server{\n\t\tappStateUpdater: appStateUpdater,\n\t\tconfig: config,\n\t\tlogger: logger,\n\t\tvlog: config.MakeVLogger(logger),\n\t}\n\tif s.fs, err = lru.New(fsCacheSize); err != nil {\n\t\treturn nil, err\n\t}\n\tif err = s.restart(); err != nil {\n\t\treturn nil, err\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo s.monitorAppState(ctx)\n\ts.cancel = cancel\n\tlibmime.Patch(additionalMimeTypes)\n\treturn s, nil\n}", "func New() Server {\n\thost := os.Getenv(\"OPENWEATHERMAP_HOST\")\n\tapiKey := os.Getenv(\"OPENWEATHERMAP_APIKEY\")\n\n\tunit := os.Getenv(\"OPENWEATHERMAP_UNIT\")\n\tif unit == \"\" {\n\t\tunit = \"metric\"\n\t}\n\n\tcacheDuration := 2\n\td := os.Getenv(\"CACHE_DURATION\")\n\tif d != \"\" {\n\t\tcacheDuration, _ = strconv.Atoi(d)\n\t}\n\n\tservice := service.New(host, apiKey, unit, cacheDuration)\n\ts := Server{gin.New(), service}\n\n\tregisterRoutes(s)\n\treturn s\n}", "func New(ca CertificateAuthority, ttl time.Duration,\n\tauthenticators []security.Authenticator,\n) (*Server, error) {\n\tcertBundle := ca.GetCAKeyCertBundle()\n\tif len(certBundle.GetRootCertPem()) != 0 {\n\t\trecordCertsExpiry(certBundle)\n\t}\n\tserver := &Server{\n\t\tAuthenticators: authenticators,\n\t\tserverCertTTL: ttl,\n\t\tca: ca,\n\t\tmonitoring: newMonitoringMetrics(),\n\t}\n\treturn server, nil\n}", "func New(storage Storage) Server {\n\ts := &server{\n\t\tstorage: storage,\n\t\tr: chi.NewMux(),\n\t}\n\ts.routes()\n\treturn s\n}", "func NewServer(config common.Config, store db.Store) (*Server, error) {\n\ttokenMaker, err := token.NewPasetoMaker(config.TokenSymmetricKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create token maker: %w\", err)\n\t}\n\n\tlog := logger.New(true)\n\tserver := &Server{\n\t\tconfig: config,\n\t\tstore: store,\n\t\ttokenMaker: tokenMaker,\n\t\tlogger: log,\n\t}\n\tserver.setupRouter()\n\treturn server, nil\n}", "func (k *Keybase) NewKV(team string) KV {\n\treturn KV{\n\t\tkeybase: k,\n\t\tTeam: team,\n\t}\n}", "func New(ctx resource.Context, ns namespace.Instance) (Server, error) {\n\treturn newKubeServer(ctx, ns)\n}", "func newServer(ctx context.Context, logger zerolog.Logger, dsn datastore.PGDatasourceName) (*server.Server, func(), error) {\n\t// This will be filled in by Wire with providers from the provider sets in\n\t// wire.Build.\n\twire.Build(\n\t\twire.InterfaceValue(new(trace.Exporter), trace.Exporter(nil)),\n\t\tgoCloudServerSet,\n\t\tapplicationSet,\n\t\tappHealthChecks,\n\t\twire.Struct(new(server.Options), \"HealthChecks\", \"TraceExporter\", \"DefaultSamplingPolicy\", \"Driver\"),\n\t\tdatastore.NewDB,\n\t\twire.Bind(new(datastore.Datastorer), new(*datastore.Datastore)),\n\t\tdatastore.NewDatastore)\n\treturn nil, nil, nil\n}", "func New(router *mux.Router, db db.PGManager) Server {\n\t// This creates a new *server struct instance. Notice the pointer (&): this means when\n\t// the server is returned it will be the same place in memory when used elsewhere (i.e.\n\t// the struct isn't copied).\n\tserver := &server{\n\t\tHandler: router,\n\t\tdb: db,\n\t}\n\t// We set up our routes as part of the constructor function.\n\tserver.routes(router)\n\treturn server\n}", "func (c CompletedConfig) New(name string) (*GenericServer, error) {\n\thandlerChainBuilder := func(handler http.Handler) http.Handler {\n\t\treturn c.BuildHandlerChainFunc(handler, c.Config)\n\t}\n\thandler := NewServerHandler(name, handlerChainBuilder, nil)\n\ts := &GenericServer{\n\t\tHandlerChainWaitGroup: c.HandlerChainWaitGroup,\n\n\t\tSecureServingInfo: c.SecureServingInfo,\n\t\tExternalAddress: c.ExternalAddress,\n\t\tHandler: handler,\n\n\t\tpostStartHooks: map[string]postStartHookEntry{},\n\t\tpreShutdownHooks: map[string]preShutdownHookEntry{},\n\n\t\thealthzChecks: c.HealthzChecks,\n\t}\n\n\tinstallAPI(s, c.Config)\n\n\treturn s, nil\n}", "func NewServer() *Server {\n\treturn &Server{\n\t\tcodecs: make(map[string]Codec),\n\t\tservices: new(serviceMap),\n\t}\n}", "func New(database *mongo.Database) *Server {\n\tif database == nil {\n\t\tdatabase = db.Connect()\n\t}\n\n\treturn &Server{\n\t\te: echo.New(),\n\t\tdb: database,\n\t}\n}", "func New(middleware ...Handler) *Server {\n\tdebugPrintWARNINGNew()\n\tserv := &Server{\n\t\trouter: make(tree.Trees, 0, 9),\n\t\tnotFound: []Handler{default404Handler},\n\t\tnoMethod: []Handler{default405Handler},\n\t\tmiddleware: middleware,\n\t\tRedirectTrailingSlash: true,\n\t\tRedirectFixedPath: false,\n\t\tMaxMultipartMemory: defaultMultipartMemory,\n\t}\n\n\tserv.pool.New = func() interface{} {\n\t\treturn serv.allocateContext()\n\t}\n\treturn serv\n}", "func New(text string) (Key, error) {\n\treturn decode(nil, []byte(text))\n}", "func New(c *Config, logger *zap.Logger) *Server {\n\treturn &Server{\n\t\tlogger,\n\t}\n}", "func New(config *configuration.Config, vs *library.Library, auth *auth.Manager) *Server {\n\treturn &Server{\n\t\tBase: subapp.NewBase(AppName),\n\t\tconfig: config,\n\t\tlibrary: vs,\n\t\tauthManager: auth,\n\t\trender: render.New(),\n\t}\n}", "func newServer(handler connHandler, logger *zap.Logger) *server {\n\ts := &server{\n\t\thandler: handler,\n\t\tlogger: logger.With(zap.String(\"sector\", \"server\")),\n\t}\n\treturn s\n}", "func New(cfg *config.Config) (*Server, error) {\n\tstorageMgr, err := storage.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create storage manager\")\n\t}\n\n\tsourceClient, err := source.NewSourceClient()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create source client\")\n\t}\n\t// progress manager\n\tprogressMgr, err := progress.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create progress manager\")\n\t}\n\n\t// cdn manager\n\tcdnMgr, err := cdn.NewManager(cfg, storageMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create cdn manager\")\n\t}\n\n\t// task manager\n\ttaskMgr, err := task.NewManager(cfg, cdnMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create task manager\")\n\t}\n\tstorageMgr.SetTaskMgr(taskMgr)\n\tstorageMgr.InitializeCleaners()\n\tprogressMgr.SetTaskMgr(taskMgr)\n\t// gc manager\n\tgcMgr, err := gc.NewManager(cfg, taskMgr, cdnMgr)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create gc manager\")\n\t}\n\n\treturn &Server{\n\t\tConfig: cfg,\n\t\tTaskMgr: taskMgr,\n\t\tGCMgr: gcMgr,\n\t}, nil\n}", "func NewServer(tokens []string, handlers []Handler) *Server {\n\tt := make(map[string]bool)\n\tfor _, v := range tokens {\n\t\tt[v] = true\n\t}\n\treturn &Server{\n\t\ttokens: t,\n\t\thandlers: handlers,\n\t}\n}" ]
[ "0.80415136", "0.7734398", "0.6711053", "0.6413338", "0.64029986", "0.6365256", "0.6311367", "0.63072085", "0.63063824", "0.62676656", "0.6260089", "0.6259903", "0.62559277", "0.62521654", "0.624715", "0.624715", "0.6245179", "0.6245179", "0.6236103", "0.6229519", "0.6223292", "0.62006605", "0.6186056", "0.6174765", "0.61697996", "0.61642325", "0.6142142", "0.61251986", "0.611597", "0.61137444", "0.60760766", "0.60661006", "0.60599357", "0.60583615", "0.60438204", "0.6023576", "0.6022207", "0.60219073", "0.59924155", "0.59924144", "0.5973379", "0.5973198", "0.59633136", "0.5953235", "0.59518224", "0.59456503", "0.5933074", "0.5920162", "0.5913212", "0.5911279", "0.5910266", "0.59003216", "0.5895707", "0.58936", "0.58917004", "0.58825195", "0.5874644", "0.58710855", "0.5861235", "0.585899", "0.58554125", "0.5853839", "0.585221", "0.58416367", "0.58226705", "0.58077824", "0.57840323", "0.5778004", "0.5773071", "0.5770094", "0.57660604", "0.5763862", "0.5731419", "0.5727652", "0.5714101", "0.5711651", "0.5708596", "0.5707975", "0.5707168", "0.57030964", "0.57022285", "0.5700926", "0.56984705", "0.56885785", "0.5687778", "0.567362", "0.567237", "0.5670403", "0.56664133", "0.56611514", "0.5660482", "0.5659542", "0.56524104", "0.5648827", "0.5648616", "0.56368816", "0.56254387", "0.5625329", "0.56243324", "0.5624312" ]
0.814005
0
InterceptRequest creates new request interceptor
InterceptRequest создает новый интерсептор запроса
func InterceptRequest(f func(http.Header)) *RequestInterceptor { return &RequestInterceptor{Intercept: f} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *APITest) Intercept(interceptor Intercept) *APITest {\n\ta.request.interceptor = interceptor\n\treturn a\n}", "func (this Interceptor) Intercept(url string, exec rack.Middleware) error {\n\tif this[url] != nil {\n\t\treturn PreExistingInterceptorError{url}\n\t}\n\tthis[url] = exec\n\treturn nil\n}", "func (c *UrlReplaceHandler) Intercept(pipeline Pipeline, middlewareIndex int, req *http.Request) (*http.Response, error) {\n\treqOption, ok := req.Context().Value(urlReplaceOptionKey).(urlReplaceOptionsInt)\n\tif !ok {\n\t\treqOption = &c.options\n\t}\n\n\tobsOptions := GetObservabilityOptionsFromRequest(req)\n\tctx := req.Context()\n\tvar span trace.Span\n\tif obsOptions != nil {\n\t\tctx, span = otel.GetTracerProvider().Tracer(obsOptions.GetTracerInstrumentationName()).Start(ctx, \"UrlReplaceHandler_Intercept\")\n\t\tspan.SetAttributes(attribute.Bool(\"com.microsoft.kiota.handler.url_replacer.enable\", true))\n\t\tdefer span.End()\n\t\treq = req.WithContext(ctx)\n\t}\n\n\tif !reqOption.IsEnabled() || len(reqOption.GetReplacementPairs()) == 0 {\n\t\treturn pipeline.Next(req, middlewareIndex)\n\t}\n\n\treq.URL.Path = ReplacePathTokens(req.URL.Path, reqOption.GetReplacementPairs())\n\n\tif span != nil {\n\t\tspan.SetAttributes(attribute.String(\"http.request_url\", req.RequestURI))\n\t}\n\n\treturn pipeline.Next(req, middlewareIndex)\n}", "func NewMockRequestInterceptor(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *MockRequestInterceptor {\n\tmock := &MockRequestInterceptor{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func ApplyInterceptor(ctx context.Context, req *Request) (*Request, error) {\n\tif registeredInterceptor == nil {\n\t\treturn req, nil\n\t}\n\treturn registeredInterceptor.Apply(ctx, req)\n}", "func LogRequest() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar (\n\t\t\terr error\n\t\t\tbuf bytes.Buffer\n\t\t)\n\n\t\tclone := c.Request.Clone(context.TODO())\n\n\t\tbuf.ReadFrom(c.Request.Body)\n\t\tc.Request.Body = ioutil.NopCloser(&buf)\n\t\tclone.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"[MIDDLEWARE] error getting request body in verbose request logger:\", err.Error())\n\t\t} else {\n\t\t\tb, _ := ioutil.ReadAll(clone.Body)\n\t\t\tbuffer := &bytes.Buffer{}\n\n\t\t\tbuffer.WriteString(bold(\"REQUEST: [\"+time.Now().In(time.UTC).Format(time.RFC3339)) + bold(\"]\"))\n\t\t\tbuffer.WriteByte('\\n')\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"%s %s %s\", clone.Method, clone.URL, clone.Proto))\n\t\t\tbuffer.WriteByte('\\n')\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"Host: %s\", clone.Host))\n\t\t\tbuffer.WriteByte('\\n')\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"Accept: %s\", clone.Header.Get(\"Accept\")))\n\t\t\tbuffer.WriteByte('\\n')\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"User-Agent: %s\", clone.Header.Get(\"User-Agent\")))\n\t\t\tbuffer.WriteByte('\\n')\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"Headers: %s\", clone.Header))\n\t\t\tbuffer.WriteByte('\\n')\n\t\t\tif len(b) > 0 {\n\t\t\t\tj, err := json.MarshalIndent(b, \"\", \" \")\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(\"[MIDDLEWARE] failed to generate json\", err)\n\t\t\t\t} else {\n\t\t\t\t\tbody, _ := base64.StdEncoding.DecodeString(string(j[1 : len(j)-1]))\n\t\t\t\t\tbuffer.Write(body)\n\t\t\t\t\tbuffer.WriteByte('\\n')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfmt.Println(buffer.String())\n\t\t}\n\n\t\tc.Next() // execute all the handlers\n\t}\n}", "func InjectTrace(ctx context.Context, incomingReq *restful.Request,\n\toutgoingReq *http.Request) (*http.Request, opentracing.Span, context.Context) {\n\tspan, newCtx := StartSpanFromContext(ctx, \"outgoing request\")\n\tif span != nil {\n\t\text.HTTPUrl.Set(span, outgoingReq.Host+outgoingReq.RequestURI)\n\t\text.HTTPMethod.Set(span, outgoingReq.Method)\n\t\t_ = span.Tracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(outgoingReq.Header))\n\n\t\tfor _, header := range forwardHeaders {\n\t\t\tif value := incomingReq.Request.Header.Get(header); value != \"\" {\n\t\t\t\toutgoingReq.Header.Set(header, value)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn outgoingReq, nil, nil\n\t}\n\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range outgoingReq.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\n\t\tlogrus.Debug(\"outgoing header : \", header)\n\t}\n\n\tif abTraceID := incomingReq.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\toutgoingReq.Header.Set(event.TraceIDKey, abTraceID)\n\t}\n\n\treturn outgoingReq, span, newCtx\n}", "func Interceptor(opts ...Option) gin.HandlerFunc {\n\tset := newOptionSet(opts...)\n\n\treturn func(ctx *gin.Context) {\n\t\tctx.Set(rkgininter.RpcEntryNameKey, set.EntryName)\n\n\t\trequestId := rkcommon.GenerateRequestId()\n\t\tctx.Header(rkginctx.RequestIdKey, requestId)\n\n\t\tevent := rkginctx.GetEvent(ctx)\n\t\tevent.SetRequestId(requestId)\n\t\tevent.SetEventId(requestId)\n\n\t\tctx.Header(set.AppNameKey, rkentry.GlobalAppCtx.GetAppInfoEntry().AppName)\n\t\tctx.Header(set.AppVersionKey, rkentry.GlobalAppCtx.GetAppInfoEntry().Version)\n\n\t\tnow := time.Now()\n\t\tctx.Header(set.AppUnixTimeKey, now.Format(time.RFC3339Nano))\n\t\tctx.Header(set.ReceivedTimeKey, now.Format(time.RFC3339Nano))\n\n\t\tctx.Next()\n\t}\n}", "func AddToRequest(app *App) server.PreHandlerFunc {\n\treturn func(req *http.Request) *http.Request {\n\t\tnewCtx := With(req.Context(), app)\n\t\treturn req.Clone(newCtx)\n\t}\n}", "func (ssec *SSEClient) wrapRequest(req *http.Request) *http.Request {\n\tssec.request = req\n\treturn req\n}", "func (bas *BaseService) OnRequest(ctx context.Context, args Args) {}", "func NewRequest(headersToSend []string) func(*gin.Context, []string) *proxy.Request {\n\tif len(headersToSend) == 0 {\n\t\theadersToSend = router.HeadersToSend\n\t}\n\n\treturn func(c *gin.Context, queryString []string) *proxy.Request {\n\t\tparams := make(map[string]string, len(c.Params))\n\t\tfor _, param := range c.Params {\n\t\t\tparams[strings.Title(param.Key[:1])+param.Key[1:]] = param.Value\n\t\t}\n\n\t\theaders := make(map[string][]string, 3+len(headersToSend))\n\n\t\tfor _, k := range headersToSend {\n\t\t\tif k == requestParamsAsterisk {\n\t\t\t\theaders = c.Request.Header\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif h, ok := c.Request.Header[textproto.CanonicalMIMEHeaderKey(k)]; ok {\n\t\t\t\theaders[k] = h\n\t\t\t}\n\t\t}\n\n\t\theaders[\"X-Forwarded-For\"] = []string{c.ClientIP()}\n\t\theaders[\"X-Forwarded-Host\"] = []string{c.Request.Host}\n\t\t// if User-Agent is not forwarded using headersToSend, we set\n\t\t// the KrakenD router User Agent value\n\t\tif _, ok := headers[\"User-Agent\"]; !ok {\n\t\t\theaders[\"User-Agent\"] = router.UserAgentHeaderValue\n\t\t} else {\n\t\t\theaders[\"X-Forwarded-Via\"] = router.UserAgentHeaderValue\n\t\t}\n\n\t\tquery := make(map[string][]string, len(queryString))\n\t\tqueryValues := c.Request.URL.Query()\n\t\tfor i := range queryString {\n\t\t\tif queryString[i] == requestParamsAsterisk {\n\t\t\t\tquery = c.Request.URL.Query()\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif v, ok := queryValues[queryString[i]]; ok && len(v) > 0 {\n\t\t\t\tquery[queryString[i]] = v\n\t\t\t}\n\t\t}\n\n\t\treturn &proxy.Request{\n\t\t\tMethod: c.Request.Method,\n\t\t\tQuery: query,\n\t\t\tBody: c.Request.Body,\n\t\t\tParams: params,\n\t\t\tHeaders: headers,\n\t\t}\n\t}\n}", "func RegisterInterceptor(newRI RequestInterceptor) (restore func()) {\n\toldRI := registeredInterceptor\n\tregisteredInterceptor = newRI\n\treturn func() {\n\t\tregisteredInterceptor = oldRI\n\t}\n}", "func InjectRequestLogger(l Logger) Middleware {\n\treturn func(inner HandlerFunc) HandlerFunc {\n\t\treturn func(rw http.ResponseWriter, req *http.Request) error {\n\t\t\tif l != nil {\n\t\t\t\treq = Inject(req, ctxKeyLogger, l)\n\t\t\t}\n\n\t\t\treturn inner(rw, req)\n\t\t}\n\t}\n}", "func NewInboundRequest(\n baseRequest *http.Request,\n pathParams PathParams,\n) *InboundRequest {\n req := &InboundRequest{\n Request: *baseRequest,\n PathParams: pathParams,\n }\n return req\n}", "func LogRequest(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t// Start timer\n\t\tstart := time.Now()\n\n\t\t// Add a requestID field to logger\n\t\tuid, _ := ulid.NewFromTime(start)\n\t\tl := log.With(zap.String(\"requestID\", uid.String()))\n\t\t// Add logger to context\n\t\tctx := context.WithValue(r.Context(), requestIDKey, l)\n\t\t// Request with this new context.\n\t\tr = r.WithContext(ctx)\n\n\t\t// wrap the ResponseWriter\n\t\tlw := &basicWriter{ResponseWriter: w}\n\n\t\t// Get the real IP even behind a proxy\n\t\trealIP := r.Header.Get(http.CanonicalHeaderKey(\"X-Forwarded-For\"))\n\t\tif realIP == \"\" {\n\t\t\t// if no content in header \"X-Forwarded-For\", get \"X-Real-IP\"\n\t\t\tif xrip := r.Header.Get(http.CanonicalHeaderKey(\"X-Real-IP\")); xrip != \"\" {\n\t\t\t\trealIP = xrip\n\t\t\t} else {\n\t\t\t\trealIP = r.RemoteAddr\n\t\t\t}\n\t\t}\n\n\t\t// Process request\n\t\tnext.ServeHTTP(lw, r)\n\t\tlw.maybeWriteHeader()\n\n\t\t// Stop timer\n\t\tend := time.Now()\n\t\tlatency := end.Sub(start)\n\t\tstatusCode := lw.Status()\n\n\t\tl.Info(\"request\",\n\t\t\tzap.String(\"method\", r.Method),\n\t\t\tzap.String(\"url\", r.RequestURI),\n\t\t\tzap.Int(\"code\", statusCode),\n\t\t\tzap.String(\"clientIP\", realIP),\n\t\t\tzap.Int(\"bytes\", lw.bytes),\n\t\t\tzap.Int64(\"duration\", int64(latency)/int64(time.Microsecond)),\n\t\t)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func incrInterceptedRequestStatDelta() {\n\tStatMu.Mutex.Lock()\n\n\t// increment the requests counter\n\t*(StatMu.InstanceStat.InterceptedRequests) = *(StatMu.InstanceStat.InterceptedRequests) + uint64(1)\n\tStatMu.Mutex.Unlock()\n\n}", "func InterceptWithReqModifier(method string, modifier SafeLoggingModifier) InterceptOption {\n\treturn func(cfg *interceptConfig) {\n\t\tcfg.reqModifiers[method] = modifier\n\t}\n}", "func (r *Router) AppendInterceptor(i func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {\n\tif i == nil {\n\t\treturn\n\t}\n\tr.interceptors = append(r.interceptors, i)\n}", "func New() *Interceptor {\n\treturn &Interceptor{}\n}", "func WithRequestHijack(h func(*http.Request)) Option {\n\treturn func(o *option) {\n\t\to.reqChain = append(o.reqChain, h)\n\t}\n}", "func interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\n\tif err := auth(ctx); err != nil {\n\t\tfmt.Println(\"111\")\n\t\treturn nil, err\n\t}\n\t//继续处理请求\n\treturn handler(ctx, req)\n\n}", "func (c *IRacing) BeforeRequest(f BeforeFunc) {\n\tc.BeforeFuncs = append(c.BeforeFuncs, f)\n}", "func (tunnel *TunnelHandler) OnRequest(filters ...Filter) *ReqFilterGroup {\n\treturn &ReqFilterGroup{ctx: tunnel.Ctx, filters: filters}\n}", "func TraceRequest(header string, nextRequestID IdGenerator) mux.MiddlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx := r.Context()\n\n\t\t\tvar err error\n\n\t\t\t// If request has the id then use it else generate one\n\t\t\trequestID := r.Header.Get(header)\n\t\t\tif requestID == \"\" {\n\t\t\t\trequestID, err = nextRequestID()\n\t\t\t}\n\n\t\t\t// No error then set it in the context & response\n\t\t\tif err == nil {\n\t\t\t\tctx = context.WithValue(ctx, header, requestID)\n\n\t\t\t\tw.Header().Set(header, requestID)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"oops\", err)\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func Inject(span opentracing.Span, request *http.Request) error {\n\treturn span.Tracer().Inject(\n\t\tspan.Context(),\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(request.Header))\n}", "func (tracer Tracer) WithRequest(r *http.Request) *http.Request {\n\tif !tracer.IsSampled() {\n\t\treturn r\n\t}\n\tctx := r.Context()\n\tctx = httptrace.WithClientTrace(ctx, tracer.trace)\n\treturn r.WithContext(ctx)\n}", "func ToHTTPRequest(tracer opentracing.Tracer) RequestFunc {\n\treturn func(req *http.Request) *http.Request {\n\t\t// Retrieve the Span from context.\n\t\tif span := opentracing.SpanFromContext(req.Context()); span != nil {\n\n\t\t\t// We are going to use this span in a client request, so mark as such.\n\t\t\text.SpanKindRPCClient.Set(span)\n\n\t\t\t// Add some standard OpenTracing tags, useful in an HTTP request.\n\t\t\text.HTTPMethod.Set(span, req.Method)\n\t\t\tspan.SetTag(zipkincore.HTTP_HOST, req.URL.Host)\n\t\t\tspan.SetTag(zipkincore.HTTP_PATH, req.URL.Path)\n\t\t\text.HTTPUrl.Set(\n\t\t\t\tspan,\n\t\t\t\tfmt.Sprintf(\"%s://%s%s\", req.URL.Scheme, req.URL.Host, req.URL.Path),\n\t\t\t)\n\n\t\t\t// Add information on the peer service we're about to contact.\n\t\t\tif host, portString, err := net.SplitHostPort(req.URL.Host); err == nil {\n\t\t\t\text.PeerHostname.Set(span, host)\n\t\t\t\tif port, err := strconv.Atoi(portString); err != nil {\n\t\t\t\t\text.PeerPort.Set(span, uint16(port))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\text.PeerHostname.Set(span, req.URL.Host)\n\t\t\t}\n\n\t\t\t// Inject the Span context into the outgoing HTTP Request.\n\t\t\tif err := tracer.Inject(\n\t\t\t\tspan.Context(),\n\t\t\t\topentracing.TextMap,\n\t\t\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t\t\t); err != nil {\n\t\t\t\tfmt.Printf(\"error encountered while trying to inject span: %+v\\n\", err)\n\t\t\t}\n\t\t}\n\t\treturn req\n\t}\n}", "func ReplicateRequest(request *http.Request) (*http.Request, error) {\n\treplicatedRequest := new(http.Request)\n\t*replicatedRequest = *request\n\treplicatedRequest.URL = &url.URL{}\n\t*replicatedRequest.URL = *request.URL\n\treplicatedRequest.Header = http.Header{}\n\n\tif request.Body != nil {\n\t\tbodyReader, err := request.GetBody()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treplicatedRequest.Body = bodyReader\n\t\treplicatedRequest.GetBody = func() (io.ReadCloser, error) {\n\t\t\treturn request.GetBody()\n\t\t}\n\t}\n\treplicatedRequest.Header = http.Header{}\n\tfor headerName, headerValues := range request.Header {\n\t\tfor idx := range headerValues {\n\t\t\treplicatedRequest.Header.Add(headerName, headerValues[idx])\n\t\t}\n\t}\n\treturn replicatedRequest.WithContext(request.Context()), nil\n}", "func New() Interceptor {\n\treturn make(Interceptor)\n}", "func Request(ctx context.Context) *events.APIGatewayProxyRequest {\n\trequest, _ := ctx.Value(ctxKeyEventContext).(*events.APIGatewayProxyRequest)\n\treturn request\n}", "func newRequestRecorder(req *http.Request, method, strPath string, fnHandler httprouter.Handle) *httptest.ResponseRecorder {\n\trouter := httprouter.New()\n\trouter.Handle(method, strPath, fnHandler)\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\treturn rr\n}", "func WrapProxyRequest(src *http.Request) *http.Request {\n\t// disable content encode\n\tsrc.Header.Del(\"Accept-Encoding\")\n\treturn src\n}", "func LoggingInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\tstart := time.Now()\n\th, err := handler(ctx, req)\n\tp, ok := peer.FromContext(ctx)\n\tif !ok {\n\t\tlog.Warn().Msg(\"unable to log grpc request\")\n\n\t\treturn h, err\n\t}\n\n\tlog.Info().\n\t\tStr(\"method\", info.FullMethod).\n\t\tStr(\"latency\", time.Since(start).String()).\n\t\tStr(\"ip\", p.Addr.String()).\n\t\tMsg(\"\")\n\n\treturn h, err\n}", "func NewLogInterceptor(request configs.WsMessage) *LogInterceptor {\n\t// TODO: determine if we're only getting stub responses and if we don't have to pick things out that we care about\n\t// This is a stub response used by the writer to kick out messages to the UI\n\tresponse := configs.WsMessage{\n\t\tType: configs.UI,\n\t\tComponent: configs.Log,\n\t\tSessionID: request.SessionID,\n\t}\n\n\treturn &LogInterceptor{\n\t\tresponse: response,\n\t}\n}", "func (r *Reflector) SetRequest(o *Operation, input interface{}, httpMethod string) error {\n\treturn r.SetupRequest(OperationContext{\n\t\tOperation: o,\n\t\tInput: input,\n\t\tHTTPMethod: httpMethod,\n\t})\n}", "func Interceptor(opts ...Option) gin.HandlerFunc {\n\tset := newOptionSet(opts...)\n\n\treturn func(ctx *gin.Context) {\n\t\tctx.Set(rkgininter.RpcEntryNameKey, set.EntryName)\n\n\t\tbefore(ctx, set)\n\n\t\tctx.Next()\n\n\t\tafter(ctx)\n\t}\n}", "func newRequestScope(now time.Time, logger *logrus.Logger, request *http.Request) RequestScope {\n\tl := NewLogger(logger, logrus.Fields{})\n\trequestID := request.Header.Get(\"X-Request-Id\")\n\tif requestID != \"\" {\n\t\tl.SetField(\"RequestID\", requestID)\n\t}\n\treturn &requestScope{\n\t\tLogger: l,\n\t\tnow: now,\n\t\trequestID: requestID,\n\t}\n}", "func (self *Proxy) NewProxyRequest(wri http.ResponseWriter, req *http.Request) *ProxyRequest {\n\n\tpr := &ProxyRequest{}\n\n\tpr.Proxy = self\n\tpr.ResponseWriter = wri\n\tpr.Request = req\n\tpr.Id = pr.requestId()\n\tpr.FileName = pr.fileName()\n\n\treturn pr\n}", "func newRequest(w http.ResponseWriter, rq *http.Request) request {\n\tr := request{\n\t\tpath: rq.URL.Path,\n\t\tctx: rq.Context(),\n\t\tr: rq,\n\t\tw: w,\n\t\tstart: time.Now(),\n\t\trid: rand.Uint64(),\n\t}\n\tr.rid |= 1 << 63 // sacrifice one bit of entropy so they always have the same # digits\n\tr.ip = r.r.Header.Get(\"X-Forwarded-For\")\n\tr.port = r.r.Header.Get(\"X-Forwarded-Port\")\n\tif r.ip == \"\" {\n\t\tr.ip, r.port, _ = net.SplitHostPort(r.r.RemoteAddr)\n\t}\n\tr.log(\n\t\t\"ip\", r.ip,\n\t\t\"port\", r.port,\n\t\t\"raddr\", r.r.RemoteAddr,\n\t\t\"method\", r.r.Method,\n\t\t\"path\", r.r.URL.Path,\n\t\t\"ref\", r.r.Referer(),\n\t\t\"ua\", r.r.UserAgent(),\n\t)\n\treturn r\n}", "func NewCreateanewInterceptionRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/interceptions\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}", "func (_e *MockRequestInterceptor_Expecter) InterceptReadRequest(ctx interface{}, readRequest interface{}) *MockRequestInterceptor_InterceptReadRequest_Call {\n\treturn &MockRequestInterceptor_InterceptReadRequest_Call{Call: _e.mock.On(\"InterceptReadRequest\", ctx, readRequest)}\n}", "func (self *Commands) Intercept(match string, args *InterceptArgs) error {\n\tif args == nil {\n\t\targs = &InterceptArgs{}\n\t}\n\n\tdefaults.SetDefaults(args)\n\n\tif filename := args.File; filename != `` {\n\t\tif file, err := self.browser.GetReaderForPath(filename); err == nil {\n\t\t\tdefer file.Close()\n\n\t\t\tbuf := bytes.NewBuffer(nil)\n\n\t\t\tif _, err := io.Copy(buf, file); err == nil {\n\t\t\t\targs.Body = buf\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else if contents, ok := args.Body.(string); ok {\n\t\targs.Body = bytes.NewBufferString(contents)\n\t} else if reader, ok := args.Body.(io.Reader); ok {\n\t\targs.Body = reader\n\t} else if contents, ok := args.Body.([]byte); ok {\n\t\targs.Body = bytes.NewBuffer(contents)\n\t} else if contents, ok := args.Body.([]uint8); ok {\n\t\targs.Body = bytes.NewBuffer([]byte(contents))\n\t} else {\n\t\treturn fmt.Errorf(\"Must specify a filename or reader\")\n\t}\n\n\treturn self.browser.Tab().AddNetworkIntercept(match, args.WaitForHeaders, func(tab *browser.Tab, pattern *browser.NetworkRequestPattern, event *browser.Event) *browser.NetworkInterceptResponse {\n\t\tresponse := &browser.NetworkInterceptResponse{\n\t\t\tAutoremove: !args.Persistent,\n\t\t}\n\n\t\tif reader, ok := args.Body.(io.Reader); ok {\n\t\t\tlog.Debugf(\"Setting request body override\")\n\t\t\tresponse.Body = reader\n\t\t}\n\n\t\tif status := event.P().Int(`responseStatusCode`); len(args.Statuses) == 0 || sliceutil.Contains(args.Statuses, status) {\n\t\t\tif args.Reject {\n\t\t\t\tresponse.Error = errors.New(`Aborted`)\n\t\t\t}\n\n\t\t\tif method := args.Method; method != `` {\n\t\t\t\tresponse.Method = method\n\t\t\t}\n\n\t\t\tif url := args.URL; url != `` {\n\t\t\t\tresponse.URL = url\n\t\t\t}\n\n\t\t\tif hdr := args.Headers; len(hdr) > 0 {\n\t\t\t\tresponse.Header = make(http.Header)\n\n\t\t\t\tfor k, v := range hdr {\n\t\t\t\t\tresponse.Header.Set(k, stringutil.MustString(v))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif data := args.PostData; len(data) > 0 {\n\t\t\t\tresponse.PostData = data\n\t\t\t}\n\n\t\t\tif origin := event.P().String(`authChallenge.origin`); origin != `` {\n\t\t\t\tif args.Realm == `` || args.Realm == event.P().String(`authChallenge.realm`) {\n\t\t\t\t\tu := args.Username\n\t\t\t\t\tp := args.Password\n\n\t\t\t\t\tif u == `` && p == `` {\n\t\t\t\t\t\tresponse.AuthResponse = `Cancel`\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.AuthResponse = `ProvideCredentials`\n\t\t\t\t\t\tresponse.Username = u\n\t\t\t\t\t\tresponse.Password = p\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn response\n\t})\n}", "func LogRequest(nextHandler http.Handler) http.Handler {\n\treturn http.HandlerFunc(\n\t\tfunc(writer http.ResponseWriter, request *http.Request) {\n\t\t\tlogRequestHandler(writer, request, nextHandler)\n\t\t})\n}", "func (this *RedirectorMiddleware) RequestModifier(request *http.Request, ctx ChainContext) error {\n\n\t// mangle the request in various ways\n\trequest.Header.Del(\"X-Forwarded-For\")\n\trequest.Header.Del(\"Upgrade-Insecure-Requests\")\n\n\t// don't forward any cookies from the client\n\trequest.Header.Del(\"Cookie\")\n\tfor _, cookie := range this.Cookies.Cookies(this.TargetServer) {\n\t\trequest.AddCookie(cookie)\n\t}\n\n\t// Fix various headers that may contain a URL\n\tthis.RetargetMap.Retarget(&request.Header, \"Origin\", this.TargetServer)\n\tthis.RetargetMap.Retarget(&request.Header, \"Referer\", this.TargetServer)\n\trequest.Header.Set(\"Host\", this.TargetServer.Host)\n\n\t// retarget the request itself\n\tctx[\"maskcxt_host\"] = request.Host\n\trequest.Host = this.TargetServer.Host\n\trequest.URL.Host = this.TargetServer.Host\n\trequest.URL.Scheme = this.TargetServer.Scheme\n\treturn nil\n}", "func (p *Proxy) onRequest(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {\n\tresChan := make(chan *http.Response)\n\terrChan := make(chan error, 1)\n\n\t// Rotate proxy IP for every AFTER request\n\tif (rotate == \"\") || (ok >= p.Options.Rotate) {\n\t\tif p.Options.Method == \"sequent\" {\n\t\t\trotate = p.Options.ProxyManager.NextProxy()\n\t\t}\n\n\t\tif p.Options.Method == \"random\" {\n\t\t\trotate = p.Options.ProxyManager.RandomProxy()\n\t\t}\n\n\t\tif ok >= p.Options.Rotate {\n\t\t\tok = 1\n\t\t}\n\t} else {\n\t\tok++\n\t}\n\n\tgo func() {\n\t\tif (req.URL.Scheme != \"http\") && (req.URL.Scheme != \"https\") {\n\t\t\terrChan <- fmt.Errorf(\"Unsupported protocol scheme: %s\", req.URL.Scheme)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debugf(\"%s %s %s\", req.RemoteAddr, req.Method, req.URL)\n\n\t\ttr, err := mubeng.Transport(rotate)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tproxy := &mubeng.Proxy{\n\t\t\tAddress: rotate,\n\t\t\tTransport: tr,\n\t\t}\n\n\t\tclient, req = proxy.New(req)\n\t\tclient.Timeout = p.Options.Timeout\n\t\tif p.Options.Verbose {\n\t\t\tclient.Transport = dump.RoundTripper(tr)\n\t\t}\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t// Copying response body\n\t\tbuf, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\n\t\tresChan <- resp\n\t}()\n\n\tselect {\n\tcase err := <-errChan:\n\t\tlog.Errorf(\"%s %s\", req.RemoteAddr, err)\n\t\treturn req, goproxy.NewResponse(req, mime, http.StatusBadGateway, \"Proxy server error\")\n\tcase resp := <-resChan:\n\t\tlog.Debug(req.RemoteAddr, \" \", resp.Status)\n\t\treturn req, resp\n\t}\n}", "func (self *Proxy) AddInterceptor(dir Interceptor) {\n\tself.Interceptors = append(self.Interceptors, dir)\n}", "func LogRequest(c *gin.Context) string {\n\treqMethod := c.Request.Method\n\treqPath := c.Request.URL.Path\n\tbuf, _ := ioutil.ReadAll(c.Request.Body)\n\tc.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\n\treturn string(reqMethod) + \" -> \" + reqPath\n}", "func BeforeRequest(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"BeforeRequest called in example plugin\")\n}", "func (l *StandardLogger) MiddlewareRequest(r *http.Request) {\n\trequestData := logrus.Fields{\n\t\t\"URL\": r.URL,\n\t\t\"Header\": r.Header,\n\t\t\"Body\": r.Body,\n\t}\n\tl.WithFields(requestData).Infof(requestingData.message)\n}", "func (d *domainClient) SetRequestInterception(ctx context.Context, args *SetRequestInterceptionArgs) (err error) {\n\tif args != nil {\n\t\terr = rpcc.Invoke(ctx, \"Network.setRequestInterception\", args, nil, d.conn)\n\t} else {\n\t\terr = rpcc.Invoke(ctx, \"Network.setRequestInterception\", nil, nil, d.conn)\n\t}\n\tif err != nil {\n\t\terr = &internal.OpError{Domain: \"Network\", Op: \"SetRequestInterception\", Err: err}\n\t}\n\treturn\n}", "func FromHTTPRequest(tracer opentracing.Tracer, operationName string,\n) HandlerFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t// Try to join to a trace propagated in `req`.\n\t\t\twireContext, err := tracer.Extract(\n\t\t\t\topentracing.TextMap,\n\t\t\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"error encountered while trying to extract span: %+v\\n\", err)\n\t\t\t}\n\n\t\t\t// create span\n\t\t\tspan := tracer.StartSpan(operationName, ext.RPCServerOption(wireContext))\n\t\t\tdefer span.Finish()\n\n\t\t\t// store span in context\n\t\t\tctx := opentracing.ContextWithSpan(req.Context(), span)\n\n\t\t\t// update request context to include our new span\n\t\t\treq = req.WithContext(ctx)\n\n\t\t\t// next middleware or actual request handler\n\t\t\tnext.ServeHTTP(w, req)\n\t\t})\n\t}\n}", "func NewCreateanewInterceptionRequest(server string, body CreateanewInterceptionJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewInterceptionRequestWithBody(server, \"application/json\", bodyReader)\n}", "func StreamServerRequestInterceptor() grpc.StreamServerInterceptor {\n\treturn func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\t\tnewCtx, err := setUpRequestInfoToContext(stream.Context())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\twrapped := grpc_middleware.WrapServerStream(stream)\n\t\twrapped.WrappedContext = newCtx\n\t\treturn handler(srv, wrapped)\n\t}\n}", "func (mod *Module) ProcessRequest(reqCtx *rproxymod.RequestContext, inReq *http.Request, proxyReq *http.Request) (res *http.Response, err error) {\n\tif len(mod.RequestHeader) >= 1 {\n\t\treqCtx.EnsureWritableHeader(proxyReq, inReq)\n\t\tfor k, v := range mod.RequestHeader {\n\t\t\tproxyReq.Header.Set(k, v)\n\t\t\tif f, ok := log.DEBUGok(); ok {\n\t\t\t\tf(fmt.Sprintf(\"Setting Request Header %s:%s\", k, v))\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func Interceptor(opts ...Option) gin.HandlerFunc {\n\tset := newOptionSet(opts...)\n\n\treturn func(ctx *gin.Context) {\n\t\tctx.Set(rkgininter.RpcEntryNameKey, set.EntryName)\n\n\t\t// start timer\n\t\tstartTime := time.Now()\n\n\t\tctx.Next()\n\n\t\t// end timer\n\t\telapsed := time.Now().Sub(startTime)\n\n\t\t// ignoring /rk/v1/assets, /rk/v1/tv and /sw/ path while logging since these are internal APIs.\n\t\tif rkgininter.ShouldLog(ctx) {\n\t\t\tif durationMetrics := GetServerDurationMetrics(ctx); durationMetrics != nil {\n\t\t\t\tdurationMetrics.Observe(float64(elapsed.Nanoseconds()))\n\t\t\t}\n\t\t\tif len(ctx.Errors) > 0 {\n\t\t\t\tif errorMetrics := GetServerErrorMetrics(ctx); errorMetrics != nil {\n\t\t\t\t\terrorMetrics.Inc()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif resCodeMetrics := GetServerResCodeMetrics(ctx); resCodeMetrics != nil {\n\t\t\t\tresCodeMetrics.Inc()\n\t\t\t}\n\t\t}\n\t}\n}", "func OpenTelemetryMiddleware(next http.Handler) http.Handler {\n\ttracer := global.Tracer(\"covidshield/request\")\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tattrs, entries, spanCtx := httptrace.Extract(r.Context(), r)\n\n\t\tr = r.WithContext(correlation.ContextWithMap(r.Context(), correlation.NewMap(correlation.MapUpdate{\n\t\t\tMultiKV: entries,\n\t\t})))\n\t\t_, span := tracer.Start(\n\t\t\ttrace.ContextWithRemoteSpanContext(r.Context(), spanCtx),\n\t\t\t\"HTTP Request\",\n\t\t\ttrace.WithAttributes(attrs...),\n\t\t)\n\t\tdefer span.End()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func modifyRequest(req *http.Request) {\n\treq.Header.Add(\"apikey\", Client.apiKey)\n}", "func OpenTracingServerInterceptor(parentSpan opentracing.Span) grpc.UnaryServerInterceptor {\n\ttracingInterceptor := otgrpc.OpenTracingServerInterceptor(\n\t\t// Use the globally installed tracer\n\t\topentracing.GlobalTracer(),\n\t\t// Log full payloads along with trace spans\n\t\totgrpc.LogPayloads(),\n\t)\n\tif parentSpan == nil {\n\t\treturn tracingInterceptor\n\t}\n\tspanContext := parentSpan.Context()\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,\n\t\thandler grpc.UnaryHandler) (interface{}, error) {\n\n\t\tmd, ok := metadata.FromIncomingContext(ctx)\n\t\tif !ok {\n\t\t\tmd = metadata.New(nil)\n\t\t}\n\t\tcarrier := metadataReaderWriter{md}\n\t\t_, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, carrier)\n\t\tif err == opentracing.ErrSpanContextNotFound {\n\t\t\tcontract.IgnoreError(opentracing.GlobalTracer().Inject(spanContext, opentracing.HTTPHeaders, carrier))\n\t\t}\n\t\treturn tracingInterceptor(ctx, req, info, handler)\n\t}\n\n}", "func InterceptResponse(f ResponseInterceptFunc) *ResponseInterceptor {\n\treturn &ResponseInterceptor{Intercept: f}\n}", "func newRequestRecorder(req *http.Request, fnHandler func(w http.ResponseWriter, r *http.Request)) *httptest.ResponseRecorder {\n\trr := httptest.NewRecorder()\n\thandler := http.HandlerFunc(fnHandler)\n\thandler.ServeHTTP(rr, req)\n\treturn rr\n}", "func NewRequest(r *http.Request) *Request {\n\tvar request Request\n\trequest.ID = atomic.AddUint32(&requestID, 1)\n\trequest.Method = r.Method\n\trequest.Body = r.Body\n\trequest.BodyBuff = new(bytes.Buffer)\n\trequest.BodyBuff.ReadFrom(r.Body)\n\trequest.RemoteAddr = r.Header.Get(\"X-Forwarded-For\")\n\trequest.Header = r.Header\n\tif request.RemoteAddr == \"\" {\n\t\trequest.RemoteAddr = r.RemoteAddr\n\t}\n\trequest.UrlParams = mux.Vars(r)\n\trequest.QueryParams = r.URL.Query()\n\treturn &request\n}", "func (proxy *ProxyHttpServer) OnRequest(conds ...ReqCondition) *ReqProxyConds {\n\treturn &ReqProxyConds{proxy, conds}\n}", "func NewRequestRecorder(r *http.Request) RequestRecorder {\n\tb, err := io.ReadAll(r.Body)\n\tif err == nil {\n\t\t_ = r.Body.Close()\n\t\tr.Body = io.NopCloser(bytes.NewReader(b))\n\t}\n\treturn RequestRecorder{\n\t\tRequest: r,\n\t\tPayload: b,\n\t}\n}", "func (adm AdminClient) newRequest(method string, reqData requestData) (req *http.Request, err error) {\n\t// If no method is supplied default to 'POST'.\n\tif method == \"\" {\n\t\tmethod = \"POST\"\n\t}\n\n\t// Default all requests to \"\"\n\tlocation := \"\"\n\n\t// Construct a new target URL.\n\ttargetURL, err := adm.makeTargetURL(reqData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize a new HTTP request for the method.\n\treq, err = http.NewRequest(method, targetURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tadm.setUserAgent(req)\n\tfor k, v := range reqData.customHeaders {\n\t\treq.Header.Set(k, v[0])\n\t}\n\tif length := len(reqData.content); length > 0 {\n\t\treq.ContentLength = int64(length)\n\t}\n\treq.Header.Set(\"X-Amz-Content-Sha256\", hex.EncodeToString(sum256(reqData.content)))\n\treq.Body = ioutil.NopCloser(bytes.NewReader(reqData.content))\n\n\treq = s3signer.SignV4(*req, adm.accessKeyID, adm.secretAccessKey, \"\", location)\n\treturn req, nil\n}", "func LogRequest(span opentracing.Span, r *http.Request) {\n\tif span != nil && r != nil {\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(span, r.URL.String())\n\t\tspan.SetTag(\"http.host\", r.Host)\n\t}\n}", "func newRequest(req *http.Request) *Request {\n\trequest := &Request{\n\t\tRequest: req,\n\t}\n\n\treturn request\n}", "func newRequestScope(now time.Time, logger *logrus.Logger, request *http.Request, db *mongo.Database) RequestScope {\n\tl := log.NewLogger(logger, logrus.Fields{})\n\trequestID := request.Header.Get(\"X-Request-Id\")\n\tif requestID != \"\" {\n\t\tl.SetField(\"RequestID\", requestID)\n\t}\n\n\treturn &requestScope{\n\t\tLogger: l,\n\t\tnow: now,\n\t\trequestID: requestID,\n\t\tdb: db,\n\t\trequest: request,\n\t}\n}", "func (m RequestInterceptor) ServeHandler(h http.Handler) http.Handler {\n\tif m.Intercept == nil {\n\t\treturn h\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tm.Intercept(r.Header)\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func (c *CustomContext) injectRequestID(prev zerolog.Logger) zerolog.Logger {\n\tid := c.Response().Header().Get(echo.HeaderXRequestID)\n\treturn prev.With().Str(\"requestId\", id).Logger()\n}", "func cloneRequest(orig *http.Request) *http.Request {\n\tmod := new(http.Request)\n\t*mod = *orig\n\tmod.Header = make(http.Header, len(orig.Header))\n\tfor k, s := range orig.Header {\n\t\tmod.Header[k] = append([]string(nil), s...)\n\t}\n\treturn mod\n}", "func InjectRequestHeaders(r *http.Request) {\n\tif span := GetSpan(r); span != nil {\n\t\terr := opentracing.GlobalTracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\tHTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n}", "func (_e *MockWriteRequestInterceptor_Expecter) InterceptWriteRequest(ctx interface{}, writeRequest interface{}) *MockWriteRequestInterceptor_InterceptWriteRequest_Call {\n\treturn &MockWriteRequestInterceptor_InterceptWriteRequest_Call{Call: _e.mock.On(\"InterceptWriteRequest\", ctx, writeRequest)}\n}", "func RequestLifetimeLogger() Middleware {\n\treturn func(h http.HandlerFunc) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlogger := log.FromContextWithPackageName(r.Context(), \"go-common/middleware/request\").\n\t\t\t\tWith(log.String(LogKeyRemoteIP, request.IPFromAddr(r.RemoteAddr))).\n\t\t\t\tWith(log.String(LogKeyRequestURL, r.RequestURI))\n\t\t\tlogger.Info(LogMsgStartRequest)\n\t\t\th(w, r)\n\t\t\tlogger.Info(LogMsgFinishRequest)\n\t\t}\n\t}\n}", "func newRequest(req *http.Request) *Request {\n\treturn &Request{\n\t\tRequest: req,\n\t}\n}", "func HandleRequest(w http.ResponseWriter, req *http.Request) {\n\t// Collect request parameters to add them to the entry HTTP span. We also need to make\n\t// sure that a proper span kind is set for the entry span, so that Instana could combine\n\t// it and its children into a call.\n\topts := []opentracing.StartSpanOption{\n\t\text.SpanKindRPCServer,\n\t\topentracing.Tags{\n\t\t\t\"http.host\": req.Host,\n\t\t\t\"http.method\": req.Method,\n\t\t\t\"http.protocol\": req.URL.Scheme,\n\t\t\t\"http.path\": req.URL.Path,\n\t\t},\n\t}\n\n\t// Check if there is an ongoing trace context provided with request and use\n\t// it as a parent for our entry span to ensure continuation.\n\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t)\n\tif err != nil {\n\t\topts = append(opts, ext.RPCServerOption(wireContext))\n\t}\n\n\t// Start the entry span adding collected tags and optional parent. The span name here\n\t// matters, as it allows Instana backend to classify the call as an HTTP one.\n\tspan := opentracing.GlobalTracer().StartSpan(\"g.http\", opts...)\n\tdefer span.Finish()\n\n\ttime.Sleep(300 * time.Millisecond)\n\tw.Write([]byte(\"Hello, world!\\n\"))\n}", "func RequestLogger() wago.MiddleWareHandler {\n\treturn func(c *wago.Context) {\n\t\tlogger.WithFields(logger.Fields{\n\t\t\twago.REQUEST_ID: c.GetString(wago.REQUEST_ID),\n\t\t\t\"path\": c.Request.URL.Path,\n\t\t\t\"host\": c.Request.Host,\n\t\t\t\"header\": c.Request.Header,\n\t\t}).Debug(\"before-handle\")\n\n\t\tc.Next()\n\n\t\tlogger.WithFields(logger.Fields{\n\t\t\twago.REQUEST_ID: c.GetString(wago.REQUEST_ID),\n\t\t\t\"path\": c.Request.URL.Path,\n\t\t\t\"host\": c.Request.Host,\n\t\t\t\"header\": c.Request.Header,\n\t\t}).Debug(\"after-handle\")\n\t}\n}", "func RequestCapturingMockHttpClient(f RequestToResponse) (*http.Client, *http.Request) {\n\tvar capture http.Request\n\treturn &http.Client{\n\t\tTransport: RequestToResponse(func(req *http.Request) (*http.Response, error) {\n\t\t\tcapture = *req.Clone(req.Context())\n\t\t\treturn f(req)\n\t\t}),\n\t}, &capture\n}", "func Trace(name string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar tracer trace.Trace\n\t\tif id := c.Request.Header.Get(\"x-request-id\"); len(id) > 0 {\n\t\t\ttracer = trace.WithID(name, id)\n\t\t} else {\n\t\t\ttracer = trace.New(name)\n\t\t}\n\t\tc.Writer.Header().Set(\"x-request-id\", tracer.ID())\n\n\t\tlastRoute, ip := func(r *http.Request) (string, string) {\n\t\t\tlastRoute := strings.Split(r.RemoteAddr, \":\")[0]\n\t\t\tif ip, exists := r.Header[\"X-Real-IP\"]; exists && len(ip) > 0 {\n\t\t\t\treturn lastRoute, ip[0]\n\t\t\t}\n\t\t\tif ips, exists := r.Header[\"X-Forwarded-For\"]; exists && len(ips) > 0 {\n\t\t\t\treturn lastRoute, ips[0]\n\t\t\t}\n\t\t\treturn lastRoute, lastRoute\n\t\t}(c.Request)\n\n\t\ttracer.Infof(\"event=[request-in] remote=[%s] route=[%s] method=[%s] url=[%s]\", ip, lastRoute, c.Request.Method, c.Request.URL.String())\n\t\tdefer tracer.Info(\"event=[request-out]\")\n\n\t\tctx := context.WithValue(c.Request.Context(), tracerLogHandlerID, tracer)\n\t\tctx = context.WithValue(ctx, realIPValueID, ip)\n\t\tc.Request = c.Request.WithContext(ctx)\n\n\t\tc.Next()\n\t}\n}", "func (s *MockStorage) InjectRequestFault(fn MockRequestFault) {\n\ts.requestFn = append(s.requestFn, fn)\n}", "func createRequest(t *testing.T, method string, path string, body io.Reader) (*http.Request, *httptest.ResponseRecorder, *bytes.Buffer) {\n\trecorder := httptest.NewRecorder()\n\treq, err := http.NewRequest(method, path, body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tlogger, output := NewFakeLogger()\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.LoggerKey, &logger))\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.AuthUserKey, \"test@draupnir\"))\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.RefreshTokenKey, \"refresh-token\"))\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.UserIPAddressKey, \"1.2.3.4\"))\n\n\treturn req, recorder, output\n}", "func RegisterInterceptor(f InterceptorFactory) {\n\tfactories = append(factories, f)\n}", "func (f *httpForwarder) modifyRequest(outReq *http.Request, target *url.URL) {\n\toutReq.URL = utils.CopyURL(outReq.URL)\n\toutReq.URL.Scheme = target.Scheme\n\toutReq.URL.Host = target.Host\n\n\tu := f.getUrlFromRequest(outReq)\n\n\toutReq.URL.Path = u.Path\n\toutReq.URL.RawPath = u.RawPath\n\toutReq.URL.RawQuery = u.RawQuery\n\toutReq.RequestURI = \"\" // Outgoing request should not have RequestURI\n\n\toutReq.Proto = \"HTTP/1.1\"\n\toutReq.ProtoMajor = 1\n\toutReq.ProtoMinor = 1\n\n\tif f.rewriter != nil {\n\t\tf.rewriter.Rewrite(outReq)\n\t}\n\n\t// Do not pass client Host header unless optsetter PassHostHeader is set.\n\tif !f.passHost {\n\t\toutReq.Host = target.Host\n\t}\n}", "func InjectLoggerInterceptor(rootLogger *zerolog.Logger) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\t\tctx = rootLogger.With().Timestamp().Logger().Hook(sourceLocationHook).WithContext(ctx)\n\n\t\tmd, ok := metadata.FromIncomingContext(ctx)\n\t\tif !ok {\n\t\t\treturn handler(ctx, req)\n\t\t}\n\t\tvalues := md.Get(\"x-cloud-trace-context\")\n\t\tif len(values) != 1 {\n\t\t\treturn handler(ctx, req)\n\t\t}\n\n\t\ttraceID, _ := traceContextFromHeader(values[0])\n\t\tif traceID == \"\" {\n\t\t\treturn handler(ctx, req)\n\t\t}\n\t\ttrace := fmt.Sprintf(\"projects/%s/traces/%s\", projectID, traceID)\n\n\t\tlog.Ctx(ctx).UpdateContext(func(c zerolog.Context) zerolog.Context {\n\t\t\treturn c.Str(\"logging.googleapis.com/trace\", trace)\n\t\t})\n\n\t\treturn handler(ctx, req)\n\t}\n}", "func NewRequestMetrics(registerer prometheus.Registerer) alice.Constructor {\n\treturn func(next http.Handler) http.Handler {\n\t\t// Counter for all requests\n\t\t// This is bucketed based on the response code we set\n\t\tcounterHandler := func(next http.Handler) http.Handler {\n\t\t\treturn promhttp.InstrumentHandlerCounter(registerRequestsCounter(registerer), next)\n\t\t}\n\n\t\t// Gauge to all requests currently being handled\n\t\tinFlightHandler := func(next http.Handler) http.Handler {\n\t\t\treturn promhttp.InstrumentHandlerInFlight(registerInflightRequestsGauge(registerer), next)\n\t\t}\n\n\t\t// The latency of all requests bucketed by HTTP method\n\t\tdurationHandler := func(next http.Handler) http.Handler {\n\t\t\treturn promhttp.InstrumentHandlerDuration(registerRequestsLatencyHistogram(registerer), next)\n\t\t}\n\n\t\treturn alice.New(counterHandler, inFlightHandler, durationHandler).Then(next)\n\t}\n}", "func initRequestLog(c *CompositeMultiHandler, basePath string, config *config.Context) {\n\t// Request logging to a separate output handler\n\t// This takes the InfoHandlers and adds a MatchAbHandler handler to it to direct\n\t// context with the word \"section=requestlog\" to that handler.\n\t// Note if request logging is not enabled the MatchAbHandler will not be added and the\n\t// request log messages will be sent out the INFO handler\n\toutputRequest := \"stdout\"\n\tif config != nil {\n\t\toutputRequest = config.StringDefault(\"log.request.output\", \"\")\n\t}\n\toldInfo := c.InfoHandler\n\tc.InfoHandler = nil\n\tif outputRequest != \"\" {\n\t\tinitHandlerFor(c, outputRequest, basePath, NewLogOptions(config, false, nil, LvlInfo))\n\t}\n\tif c.InfoHandler != nil || oldInfo != nil {\n\t\tif c.InfoHandler == nil {\n\t\t\tc.InfoHandler = oldInfo\n\t\t} else {\n\t\t\tc.InfoHandler = MatchAbHandler(\"section\", \"requestlog\", c.InfoHandler, oldInfo)\n\t\t}\n\t}\n}", "func NewRequestLogger() heimdall.Plugin {\n return &requestLogger{}\n}", "func (s *StaticModifier) ModifyRequest(req *http.Request) error {\n\tctx := NewContext(req.Context())\n\tctx.SkipRoundTrip()\n\n\tif req.URL.Scheme == \"https\" {\n\t\treq.URL.Scheme = \"http\"\n\t}\n\n\t*req = *req.WithContext(ctx)\n\n\treturn nil\n}", "func ServerInterceptor(keys ...interface{}) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tnewContextForHandleRequestID(ctx, keys...)\n\t\tctx.Next() // execute all the handlers\n\t}\n}", "func (r Resource) ProxyRequest(request *restful.Request, response *restful.Response) {\n\tparsedURL, err := url.Parse(request.Request.URL.String())\n\tif err != nil {\n\t\tutils.RespondError(response, err, http.StatusNotFound)\n\t\treturn\n\t}\n\n\turi := request.PathParameter(\"subpath\") + \"?\" + parsedURL.RawQuery\n\n\tif secretsURIPattern.Match([]byte(uri)) {\n\t\tforwardRequest := r.K8sClient.CoreV1().RESTClient().Verb(request.Request.Method).RequestURI(uri).Body(request.Request.Body)\n\t\tforwardRequest.SetHeader(\"Content-Type\", request.HeaderParameter(\"Content-Type\"))\n\t\tforwardResponse := forwardRequest.Do()\n\t\thandleSecretsResponse(response, forwardResponse)\n\t\treturn\n\t}\n\n\tif statusCode, err := utils.Proxy(request.Request, response, r.Config.Host+\"/\"+uri, r.HttpClient); err != nil {\n\t\tutils.RespondError(response, err, statusCode)\n\t}\n}", "func cloneRequest(t *tee, req *http.Request) (*http.Request, io.ReadCloser, error) {\n\tu := new(url.URL)\n\t*u = *req.URL\n\tu.Host = t.host\n\tu.Scheme = t.scheme\n\tif t.typ == pathModified {\n\t\tu.Path = t.rx.ReplaceAllString(u.Path, t.replacement)\n\t}\n\n\th := make(http.Header)\n\tfor k, v := range req.Header {\n\t\th[k] = v\n\t}\n\n\tfor _, k := range hopHeaders {\n\t\th.Del(k)\n\t}\n\n\tvar teeBody io.ReadCloser\n\tmainBody := req.Body\n\n\t// see proxy.go:231\n\tif req.ContentLength != 0 {\n\t\tpr, pw := io.Pipe()\n\t\tteeBody = pr\n\t\tmainBody = &teeTie{mainBody, pw}\n\t}\n\n\tclone, err := http.NewRequest(req.Method, u.String(), teeBody)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclone.Header = h\n\tclone.Host = t.host\n\tclone.ContentLength = req.ContentLength\n\n\treturn clone, mainBody, nil\n}", "func (_e *MockRequestInterceptor_Expecter) InterceptWriteRequest(ctx interface{}, writeRequest interface{}) *MockRequestInterceptor_InterceptWriteRequest_Call {\n\treturn &MockRequestInterceptor_InterceptWriteRequest_Call{Call: _e.mock.On(\"InterceptWriteRequest\", ctx, writeRequest)}\n}", "func (app *application) logRequest(next http.Handler) http.Handler {\r\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n\t\tapp.infoLog.Printf(\"%s - %s %s %s\", r.RemoteAddr, r.Proto, r.Method, r.URL.RequestURI())\r\n\r\n\t\tnext.ServeHTTP(w, r)\r\n\t})\r\n}", "func newRequest(method, url string, body string) *http.Request {\n\treq, err := http.NewRequest(method, url, strings.NewReader(body))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-API-Token\", \"token1\")\n\treturn req\n}", "func LogRequest(req http.Request, statusCode int, lenContent int, reqID string, cached bool, cachedLabel string) {\n\t// NOTE: THIS IS FOR EVERY DOMAIN, NO DOMAIN OVERRIDE.\n\t// WHEN SHARING SAME PORT NO CUSTOM OVERRIDES ON CRITICAL SETTINGS.\n\tlogLine := config.Config.Log.Format\n\n\tprotocol := strings.Trim(req.Proto, \" \")\n\tif protocol == \"\" {\n\t\tprotocol = \"?\"\n\t}\n\n\tmethod := strings.Trim(req.Method, \" \")\n\tif method == \"\" {\n\t\tmethod = \"?\"\n\t}\n\n\tr := strings.NewReplacer(\n\t\t`$host`, req.Host,\n\t\t`$remote_addr`, req.RemoteAddr,\n\t\t`$remote_user`, \"-\",\n\t\t`$time_local`, time.Now().Local().Format(config.Config.Log.TimeFormat),\n\t\t`$protocol`, protocol,\n\t\t`$request_method`, method,\n\t\t`$request`, req.URL.String(),\n\t\t`$status`, strconv.Itoa(statusCode),\n\t\t`$body_bytes_sent`, strconv.Itoa(lenContent),\n\t\t`$http_referer`, req.Referer(),\n\t\t`$http_user_agent`, req.UserAgent(),\n\t\t`$cached_status_label`, cachedLabel,\n\t\t`$cached_status`, fmt.Sprintf(\"%v\", cached),\n\t)\n\n\tlogLine = r.Replace(logLine)\n\n\tlogrus.WithFields(logrus.Fields{\"ReqID\": reqID}).Info(logLine)\n}", "func UnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\tlocalHub := sentry.CurrentHub().Clone()\n\n\tlocalHub.ConfigureScope(func(scope *sentry.Scope) {\n\t\tscope.SetExtra(\"req\", req)\n\n\t\tid := reqid.Extract(ctx)\n\t\tif id != \"\" {\n\t\t\tscope.SetExtra(\"request_id\", id)\n\t\t}\n\t})\n\n\tctx = set(ctx, localHub)\n\n\treturn func() (resp interface{}, err error) {\n\t\tdefer func() {\n\t\t\terr := recover()\n\t\t\tif err != nil {\n\t\t\t\tlocalHub.RecoverWithContext(ctx, err)\n\t\t\t}\n\t\t}()\n\n\t\tres, err := handler(ctx, req)\n\t\tif err != nil {\n\t\t\tReport(ctx, err)\n\t\t}\n\n\t\treturn res, err\n\t}()\n}", "func (p Products) MiddlewareLogRequest(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\tp.logger.Printf(\"Handle %s Product\\n\", r.Method)\n\t\tnext.ServeHTTP(rw, r)\n\t})\n}", "func traceWrap(c *gin.Context) {\n\tappIDKey, err := tag.NewKey(\"fn.app_id\")\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tfnKey, err := tag.NewKey(\"fn.fn_id\")\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tctx, err := tag.New(c.Request.Context(),\n\t\ttag.Insert(appIDKey, c.Param(api.AppID)),\n\t\ttag.Insert(fnKey, c.Param(api.FnID)),\n\t)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\t// TODO inspect opencensus more and see if we need to define a header ourselves\n\t// to trigger per-request spans (we will want this), we can set sampler here per request.\n\n\tctx, span := trace.StartSpan(ctx, \"serve_http\")\n\tdefer span.End()\n\n\t// spans like these, not tags\n\tspan.AddAttributes(\n\t\ttrace.StringAttribute(\"fn.app_id\", c.Param(api.AppID)),\n\t\ttrace.StringAttribute(\"fn.fn_id\", c.Param(api.FnID)),\n\t)\n\n\tc.Request = c.Request.WithContext(ctx)\n\tc.Next()\n}", "func (c *APIGateway) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\t// Run custom request initialization if present\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}", "func (dl DefaultLogger) LogRequest(*http.Request) {\n}" ]
[ "0.71772784", "0.6711371", "0.6566157", "0.65058345", "0.63735974", "0.6020365", "0.5849495", "0.58412755", "0.5832512", "0.5831639", "0.58202237", "0.5789917", "0.5758646", "0.57329756", "0.5705637", "0.57048255", "0.56965905", "0.56952894", "0.56863815", "0.56753355", "0.5670503", "0.56413406", "0.5604584", "0.5591556", "0.55828243", "0.5566225", "0.5560431", "0.5531029", "0.5512576", "0.550626", "0.5505341", "0.55029964", "0.5481316", "0.54760146", "0.547362", "0.54714787", "0.5466705", "0.54611075", "0.545753", "0.54533523", "0.54367095", "0.543209", "0.5428256", "0.5425784", "0.5417444", "0.5409251", "0.54032254", "0.5402988", "0.540233", "0.53975254", "0.5394442", "0.5389744", "0.53889436", "0.5372817", "0.53708357", "0.53477746", "0.5347576", "0.53470117", "0.53434914", "0.5334988", "0.5331379", "0.5331368", "0.5330374", "0.5329437", "0.53007495", "0.5292078", "0.52884394", "0.52837944", "0.52801865", "0.52665895", "0.52659714", "0.5257154", "0.5250725", "0.5249509", "0.52396363", "0.52238196", "0.52205205", "0.52191794", "0.5216679", "0.52119535", "0.5192211", "0.5184399", "0.5172035", "0.5163597", "0.515476", "0.5152994", "0.5144967", "0.51410264", "0.5138096", "0.51221204", "0.5120557", "0.5117454", "0.5114839", "0.51111203", "0.5110342", "0.5107883", "0.5107868", "0.5107468", "0.5104417", "0.50962394" ]
0.7859327
0
InterceptResponse creates new response interceptor
InterceptResponse создает новый перехватчик ответа
func InterceptResponse(f ResponseInterceptFunc) *ResponseInterceptor { return &ResponseInterceptor{Intercept: f} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *middleware) InterceptResponse(ctx context.Context, next gqlgen.ResponseHandler) *gqlgen.Response {\n\tresp := next(ctx)\n\n\toperations, ok := FromCtx(ctx)\n\tif !ok {\n\t\treturn resp\n\t}\n\n\tlocations := make([]string, 0)\n\tfor _, operation := range *operations {\n\t\toperationURL := fmt.Sprintf(\"%s/%s/%s\", m.directorURL, operation.ResourceType, operation.ResourceID)\n\t\tlocations = append(locations, operationURL)\n\t}\n\n\tif len(locations) > 0 {\n\t\treqCtx := gqlgen.GetOperationContext(ctx)\n\t\tgqlgen.RegisterExtension(ctx, LocationsParam, locations)\n\t\tresp.Extensions = gqlgen.GetExtensions(ctx)\n\n\t\tjsonPropsToDelete := make([]string, 0)\n\t\tfor _, gqlOperation := range reqCtx.Doc.Operations {\n\t\t\tfor _, gqlSelection := range gqlOperation.SelectionSet {\n\t\t\t\tgqlField, ok := gqlSelection.(*ast.Field)\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.C(ctx).Errorf(\"Unable to prepare final response: gql field has unexpected type %T instead of *ast.Field\", gqlSelection)\n\t\t\t\t\treturn gqlgen.ErrorResponse(ctx, \"unable to prepare final response\")\n\t\t\t\t}\n\n\t\t\t\tmutationAlias := gqlField.Alias\n\t\t\t\tfor _, gqlArgument := range gqlField.Arguments {\n\t\t\t\t\tif gqlArgument.Name == ModeParam && gqlArgument.Value.Raw == string(graphql.OperationModeAsync) {\n\t\t\t\t\t\tjsonPropsToDelete = append(jsonPropsToDelete, mutationAlias)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnewData, err := cleanupFields(resp, jsonPropsToDelete)\n\t\tif err != nil {\n\t\t\tlog.C(ctx).WithError(err).Errorf(\"Unable to process and delete unnecessary bytes from response body: %v\", err)\n\t\t\treturn gqlgen.ErrorResponse(ctx, \"failed to prepare response body\")\n\t\t}\n\n\t\tresp.Data = newData\n\t}\n\n\treturn resp\n}", "func (m ResponseInterceptor) ServeHandler(h http.Handler) http.Handler {\n\tif m.Intercept == nil {\n\t\treturn h\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tnw := interceptRW{\n\t\t\tResponseWriter: w,\n\t\t\tf: m.Intercept,\n\t\t\tstatus: http.StatusOK,\n\t\t}\n\t\tdefer nw.intercept()\n\n\t\th.ServeHTTP(&nw, r)\n\t})\n}", "func WrapResponse(w http.ResponseWriter, request types.InterxRequest, response types.ProxyResponse, statusCode int, saveToCache bool) {\n\tif statusCode == 0 {\n\t\tstatusCode = 503 // Service Unavailable Error\n\t}\n\tif saveToCache {\n\t\t// GetLogger().Info(\"[gateway] Saving in the cache\")\n\n\t\tchainIDHash := GetBlake2bHash(response.Chainid)\n\t\tendpointHash := GetBlake2bHash(request.Endpoint)\n\t\trequestHash := GetBlake2bHash(request)\n\t\tif conf, ok := RPCMethods[request.Method][request.Endpoint]; ok {\n\t\t\terr := PutCache(chainIDHash, endpointHash, requestHash, types.InterxResponse{\n\t\t\t\tResponse: response,\n\t\t\t\tStatus: statusCode,\n\t\t\t\tExpireAt: time.Now().Add(time.Duration(conf.CachingDuration) * time.Second),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\t// GetLogger().Error(\"[gateway] Failed to save in the cache: \", err.Error())\n\t\t\t}\n\t\t\t// GetLogger().Info(\"[gateway] Save finished\")\n\t\t}\n\t}\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tw.Header().Add(\"Interx_chain_id\", response.Chainid)\n\tw.Header().Add(\"Interx_block\", strconv.FormatInt(response.Block, 10))\n\tw.Header().Add(\"Interx_blocktime\", response.Blocktime)\n\tw.Header().Add(\"Interx_timestamp\", strconv.FormatInt(response.Timestamp, 10))\n\tw.Header().Add(\"Interx_request_hash\", response.RequestHash)\n\tif request.Endpoint == config.QueryDataReference {\n\t\treference, err := database.GetReference(string(request.Params))\n\t\tif err == nil {\n\t\t\tw.Header().Add(\"Interx_ref\", \"/download/\"+reference.FilePath)\n\t\t}\n\t}\n\n\tif response.Response != nil {\n\t\tresponse.Signature, response.Hash = GetResponseSignature(response)\n\n\t\tw.Header().Add(\"Interx_signature\", response.Signature)\n\t\tw.Header().Add(\"Interx_hash\", response.Hash)\n\t\tw.WriteHeader(statusCode)\n\n\t\tjson.NewEncoder(w).Encode(response.Response)\n\t} else {\n\t\tw.WriteHeader(statusCode)\n\n\t\tif response.Error == nil {\n\t\t\tresponse.Error = \"service not available\"\n\t\t}\n\t\tjson.NewEncoder(w).Encode(response.Error)\n\t}\n}", "func (a *APITest) Intercept(interceptor Intercept) *APITest {\n\ta.request.interceptor = interceptor\n\treturn a\n}", "func (h *Handler) prepResponse(w http.ResponseWriter) {\n\tw.Header().Add(varyHeader, originHeader)\n}", "func (p *Proxy) onResponse(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {\n\tfor _, h := range mubeng.HopHeaders {\n\t\tresp.Header.Del(h)\n\t}\n\n\treturn resp\n}", "func (c *UrlReplaceHandler) Intercept(pipeline Pipeline, middlewareIndex int, req *http.Request) (*http.Response, error) {\n\treqOption, ok := req.Context().Value(urlReplaceOptionKey).(urlReplaceOptionsInt)\n\tif !ok {\n\t\treqOption = &c.options\n\t}\n\n\tobsOptions := GetObservabilityOptionsFromRequest(req)\n\tctx := req.Context()\n\tvar span trace.Span\n\tif obsOptions != nil {\n\t\tctx, span = otel.GetTracerProvider().Tracer(obsOptions.GetTracerInstrumentationName()).Start(ctx, \"UrlReplaceHandler_Intercept\")\n\t\tspan.SetAttributes(attribute.Bool(\"com.microsoft.kiota.handler.url_replacer.enable\", true))\n\t\tdefer span.End()\n\t\treq = req.WithContext(ctx)\n\t}\n\n\tif !reqOption.IsEnabled() || len(reqOption.GetReplacementPairs()) == 0 {\n\t\treturn pipeline.Next(req, middlewareIndex)\n\t}\n\n\treq.URL.Path = ReplacePathTokens(req.URL.Path, reqOption.GetReplacementPairs())\n\n\tif span != nil {\n\t\tspan.SetAttributes(attribute.String(\"http.request_url\", req.RequestURI))\n\t}\n\n\treturn pipeline.Next(req, middlewareIndex)\n}", "func NewWriterInterceptor(w http.ResponseWriter, req *http.Request, fn ResModifierFunc) *WriterInterceptor {\n\tres := &http.Response{\n\t\tRequest: req,\n\t\tStatusCode: 200,\n\t\tStatus: \"200 OK\",\n\t\tProto: \"HTTP/1.1\",\n\t\tProtoMajor: 1,\n\t\tProtoMinor: 1,\n\t\tHeader: make(http.Header),\n\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte{})),\n\t}\n\treturn &WriterInterceptor{mutex: &sync.Mutex{}, writer: w, modifier: fn, response: res}\n}", "func (f *genericFilter) OnResponse(_ context.Context, result protocol.Result, _ protocol.Invoker,\n\t_ protocol.Invocation) protocol.Result {\n\treturn result\n}", "func InterceptWithRespModifier(method string, modifier SafeLoggingModifier) InterceptOption {\n\treturn func(cfg *interceptConfig) {\n\t\tcfg.respModifiers[method] = modifier\n\t}\n}", "func (tunnel *TunnelHandler) OnResponse(filters ...Filter) *RespFilterGroup {\n\treturn &RespFilterGroup{ctx: tunnel.Ctx, filters: filters}\n}", "func (this Interceptor) Intercept(url string, exec rack.Middleware) error {\n\tif this[url] != nil {\n\t\treturn PreExistingInterceptorError{url}\n\t}\n\tthis[url] = exec\n\treturn nil\n}", "func NewResponseModifier(req *http.Request, res *http.Response) *ResponseModifier {\n\treturn &ResponseModifier{Request: req, Response: res, Header: res.Header}\n}", "func Response(fn ResModifierFunc) func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.Method == \"OPTIONS\" || r.Method == \"HEAD\" {\n\t\t\t\th.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twriter := NewWriterInterceptor(w, r, fn)\n\t\t\tdefer h.ServeHTTP(writer, r)\n\n\t\t\tnotifier, ok := w.(http.CloseNotifier)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnotify := notifier.CloseNotify()\n\t\t\tgo func() {\n\t\t\t\t<-notify\n\t\t\t\twriter.Close()\n\t\t\t}()\n\t\t})\n\t}\n}", "func interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\n\tif err := auth(ctx); err != nil {\n\t\tfmt.Println(\"111\")\n\t\treturn nil, err\n\t}\n\t//继续处理请求\n\treturn handler(ctx, req)\n\n}", "func Interceptor(opts ...Option) gin.HandlerFunc {\n\tset := newOptionSet(opts...)\n\n\treturn func(ctx *gin.Context) {\n\t\tctx.Set(rkgininter.RpcEntryNameKey, set.EntryName)\n\n\t\trequestId := rkcommon.GenerateRequestId()\n\t\tctx.Header(rkginctx.RequestIdKey, requestId)\n\n\t\tevent := rkginctx.GetEvent(ctx)\n\t\tevent.SetRequestId(requestId)\n\t\tevent.SetEventId(requestId)\n\n\t\tctx.Header(set.AppNameKey, rkentry.GlobalAppCtx.GetAppInfoEntry().AppName)\n\t\tctx.Header(set.AppVersionKey, rkentry.GlobalAppCtx.GetAppInfoEntry().Version)\n\n\t\tnow := time.Now()\n\t\tctx.Header(set.AppUnixTimeKey, now.Format(time.RFC3339Nano))\n\t\tctx.Header(set.ReceivedTimeKey, now.Format(time.RFC3339Nano))\n\n\t\tctx.Next()\n\t}\n}", "func (m RequestInterceptor) ServeHandler(h http.Handler) http.Handler {\n\tif m.Intercept == nil {\n\t\treturn h\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tm.Intercept(r.Header)\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func ResponseModifier(responseModifier func(*http.Response) error) optSetter {\n\treturn func(f *Forwarder) error {\n\t\tf.httpForwarder.modifyResponse = responseModifier\n\t\treturn nil\n\t}\n}", "func (proxy *ProxyHttpServer) OnResponse(conds ...RespCondition) *ProxyConds {\n\treturn &ProxyConds{proxy, make([]ReqCondition, 0), conds}\n}", "func (r *Response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {\n\treturn r.ResponseWriter.(http.Hijacker).Hijack()\n}", "func (r *tee) Response(filters.FilterContext) {}", "func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tr.rendered = true\n\thijacker, ok := r.ResponseWriter.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"the ResponseWriter doesn't support the Hijacker interface\")\n\t}\n\treturn hijacker.Hijack()\n}", "func NewCustomResponseWriter(resp http.ResponseWriter, catchBody bool) *CustomResponseWriter {\n\treturn &CustomResponseWriter{\n\t\tResponseWriter: resp,\n\t\tcatchBody: catchBody,\n\t}\n}", "func cacheResponse(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tc.Response().Writer = cache.NewWriter(c.Response().Writer, c.Request())\n\t\treturn next(c)\n\t}\n}", "func Response(request *events.APIGatewayProxyRequest) events.APIGatewayProxyResponse {\n\tcorsHeaders := map[string]string{\n\t\t\"Access-Control-Allow-Credentials\": \"true\",\n\t\t\"Access-Control-Allow-Headers\": \"Content-Type\",\n\t\t\"Access-Control-Allow-Origin\": \"\",\n\t}\n\torigin := request.Headers[\"origin\"]\n\tsetOrigin(corsHeaders, origin)\n\treturn events.APIGatewayProxyResponse{\n\t\tHeaders: corsHeaders,\n\t\tMultiValueHeaders: map[string][]string{},\n\t\tStatusCode: http.StatusInternalServerError,\n\t}\n}", "func IdentityResponseModifier(r *http.Response) error {\n\tif r.Request.Method == http.MethodDelete {\n\t\t// regex, may be /v1/tokens/self where value after 'v' could be any positive integer\n\t\ttokenSelfPathRegex := \"^/v\\\\d+/tokens/self$\"\n\t\tmatched, err := regexp.MatchString(tokenSelfPathRegex, r.Request.URL.Path)\n\t\tif err != nil {\n\t\t\tlog.Event(r.Request.Context(), \"failed to run regex on request path\", log.Error(err), log.ERROR)\n\t\t}\n\t\tif matched {\n\t\t\t// Attempt to delete cookies even if the response upstream was a fail\n\t\t\tdeleteAuthCookies(r)\n\t\t}\n\t} else if r.StatusCode >= http.StatusOK && r.StatusCode < http.StatusMultipleChoices {\n\t\tsetAuthCookies(r)\n\t}\n\n\treturn nil\n}", "func (c *ClientWithResponses) CreateanewInterceptionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader) (*CreateanewInterceptionResponse, error) {\n\trsp, err := c.CreateanewInterceptionWithBody(ctx, contentType, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseCreateanewInterceptionResponse(rsp)\n}", "func MockExtendResponse(t *testing.T) {\n\tth.Mux.HandleFunc(shareEndpoint+\"/\"+shareID+\"/action\", func(w http.ResponseWriter, r *http.Request) {\n\t\tth.TestMethod(t, r, \"POST\")\n\t\tth.TestHeader(t, r, \"X-Auth-Token\", fake.TokenID)\n\t\tth.TestHeader(t, r, \"Content-Type\", \"application/json\")\n\t\tth.TestHeader(t, r, \"Accept\", \"application/json\")\n\t\tth.TestJSONRequest(t, r, extendRequest)\n\t\tw.Header().Add(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusAccepted)\n\t})\n}", "func AugmentWithResponse(baseCtx context.Context, responseCode int) context.Context {\n\tctx, _ := tag.New(\n\t\tbaseCtx,\n\t\ttag.Upsert(ResponseCodeKey, strconv.Itoa(responseCode)),\n\t\ttag.Upsert(ResponseCodeClassKey, responseCodeClass(responseCode)))\n\treturn ctx\n}", "func InterceptRequest(f func(http.Header)) *RequestInterceptor {\n\treturn &RequestInterceptor{Intercept: f}\n}", "func setupResponse(writer *http.ResponseWriter, request *http.Request) {\n\t(*writer).Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t(*writer).Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t(*writer).Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n}", "func wrapErdaStyleResponse(proxyConfig types.ProxyConfig, resp *http.Response) (wErr error) {\n\tif resp.Header.Get(\"X-NEED-USER-INFO\") != \"true\" {\n\t\tlogrus.Info(\"resp doesn't have need user info header, skip inject user info\")\n\t\tresp.Header.Set(\"Content-Type\", \"application/json\")\n\t\treturn\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(content))\n\t\t\twErr = fmt.Errorf(\"err: %v, responseBody: %s\", r, string(content))\n\t\t}\n\t\tresp.Header.Set(\"Content-Type\", \"application/json\")\n\t}()\n\n\t// construct erda style response\n\tvar erdaResp response\n\tif err := jsi.Unmarshal(content, &erdaResp); err != nil {\n\t\tpanic(err)\n\t}\n\trenderResponse, ok := erdaResp.Data.(map[string]interface{})\n\tif !ok {\n\t\tlogrus.Infof(\"data in response is not map[string]interface{}, skip inject user info\")\n\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(content))\n\t\treturn nil\n\t}\n\tprotocol, ok := renderResponse[\"protocol\"]\n\tif !ok {\n\t\tlogrus.Infof(\"protocol is nil in response, skip inject user info\")\n\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(content))\n\t\treturn nil\n\t}\n\tobj, ok := protocol.(map[string]interface{})\n\tif !ok {\n\t\tlogrus.Infof(\"protocol in response is not map[string]interface{}, skip inject user info\")\n\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(content))\n\t\treturn nil\n\t}\n\tglobalState, ok := obj[\"state\"]\n\tif !ok {\n\t\tlogrus.Infof(\"globalState is nil in response, skip inject user info\")\n\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(content))\n\t\treturn nil\n\t}\n\tobj, ok = globalState.(map[string]interface{})\n\tif !ok {\n\t\tlogrus.Infof(\"globalState is response is not map[string]interface{}, skip inject user info\")\n\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(content))\n\t\treturn nil\n\t}\n\n\tuserIDsValue, ok := obj[cptype.GlobalInnerKeyUserIDs.String()]\n\tif !ok {\n\t\tlogrus.Infof(\"userIDsValue is nil, skip inject user info\")\n\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(content))\n\t\treturn nil\n\t}\n\n\tvar userIDs []string\n\tif err := cputil.ObjJSONTransfer(userIDsValue, &userIDs); err != nil {\n\t\tpanic(err)\n\t}\n\tuserIDs = strutil.DedupSlice(userIDs, true)\n\t// inject to response body\n\terdaResp.UserIDs = userIDs\n\n\t// update response body\n\tnewErdaBody, err := jsi.Marshal(erdaResp)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tresp.Body = ioutil.NopCloser(bytes.NewReader(newErdaBody))\n\tresp.Header.Set(\"Content-Length\", fmt.Sprint(len(newErdaBody)))\n\n\treturn nil\n}", "func (w *WriterInterceptor) Write(b []byte) (int, error) {\n\tlength := w.response.Header.Get(\"Content-Length\")\n\tif length == \"\" || length == \"0\" {\n\t\tw.buf = b\n\t\treturn w.DoWrite()\n\t}\n\n\tw.response.ContentLength += int64(len(b))\n\tw.buf = append(w.buf, b...)\n\n\t// If not EOF\n\tif cl, _ := strconv.Atoi(length); w.response.ContentLength != int64(cl) {\n\t\treturn len(b), nil\n\t}\n\n\tw.response.Body = ioutil.NopCloser(bytes.NewReader(w.buf))\n\tresm := NewResponseModifier(w.response.Request, w.response)\n\tw.modifier(resm)\n\treturn w.DoWrite()\n}", "func WrapResponseWriter(w http.ResponseWriter) (http.ResponseWriter, *Response) {\n\trw := responseWriter{\n\t\tResponseWriter: w,\n\t\tresp: Response{\n\t\t\tHeaders: w.Header(),\n\t\t},\n\t}\n\n\th, _ := w.(http.Hijacker)\n\tp, _ := w.(http.Pusher)\n\trf, _ := w.(io.ReaderFrom)\n\n\tswitch {\n\tcase h != nil && p != nil:\n\t\trwhp := responseWriterHijackerPusher{\n\t\t\tresponseWriter: rw,\n\t\t\tHijacker: h,\n\t\t\tPusher: p,\n\t\t}\n\t\tif rf != nil {\n\t\t\trwhprf := responseWriterHijackerPusherReaderFrom{rwhp, rf}\n\t\t\treturn &rwhprf, &rwhprf.resp\n\t\t}\n\t\treturn &rwhp, &rwhp.resp\n\tcase h != nil:\n\t\trwh := responseWriterHijacker{\n\t\t\tresponseWriter: rw,\n\t\t\tHijacker: h,\n\t\t}\n\t\tif rf != nil {\n\t\t\trwhrf := responseWriterHijackerReaderFrom{rwh, rf}\n\t\t\treturn &rwhrf, &rwhrf.resp\n\t\t}\n\t\treturn &rwh, &rwh.resp\n\tcase p != nil:\n\t\trwp := responseWriterPusher{\n\t\t\tresponseWriter: rw,\n\t\t\tPusher: p,\n\t\t}\n\t\tif rf != nil {\n\t\t\trwprf := responseWriterPusherReaderFrom{rwp, rf}\n\t\t\treturn &rwprf, &rwprf.resp\n\t\t}\n\t\treturn &rwp, &rwp.resp\n\tdefault:\n\t\tif rf != nil {\n\t\t\trwrf := responseWriterReaderFrom{rw, rf}\n\t\t\treturn &rwrf, &rwrf.resp\n\t\t}\n\t\treturn &rw, &rw.resp\n\t}\n}", "func ResponseWriter(customResponse model.CustomResponse, transform string, cc *model.CustomContext) error {\n\tvar statusCode int\n\tstatusCode = customResponse.StatusCode\n\n\tresponseBody := customResponse.Body\n\tresponseHeader := customResponse.Header\n\n\tif customResponse.Error != nil {\n\t\tlog.Error(\"response error : \", customResponse.Error.Error())\n\t\tresponseBody[\"error\"] = customResponse.Error.Error()\n\t}\n\n\tSetHeaderResponse(responseHeader, cc)\n\tif statusCode == 0 {\n\t\tlog.Warn(\"Status Code is not defined, set Status code to 4000\")\n\t\tstatusCode = 400\n\t}\n\n\tswitch strings.ToLower(transform) {\n\tcase strings.ToLower(\"ToJson\"):\n\t\treturn cc.JSON(statusCode, responseBody)\n\tcase strings.ToLower(\"ToXml\"):\n\n\t\tresByte, err := service.ToXml(responseBody)\n\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\tres := make(map[string]interface{})\n\t\t\tres[\"message\"] = err.Error()\n\t\t\treturn cc.XML(500, res)\n\t\t}\n\t\treturn cc.XMLBlob(statusCode, resByte)\n\tdefault:\n\t\treturn cc.JSON(statusCode, responseBody)\n\t}\n}", "func (r *Router) AppendInterceptor(i func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {\n\tif i == nil {\n\t\treturn\n\t}\n\tr.interceptors = append(r.interceptors, i)\n}", "func NewLogInterceptor(request configs.WsMessage) *LogInterceptor {\n\t// TODO: determine if we're only getting stub responses and if we don't have to pick things out that we care about\n\t// This is a stub response used by the writer to kick out messages to the UI\n\tresponse := configs.WsMessage{\n\t\tType: configs.UI,\n\t\tComponent: configs.Log,\n\t\tSessionID: request.SessionID,\n\t}\n\n\treturn &LogInterceptor{\n\t\tresponse: response,\n\t}\n}", "func LogResponse(logger log.Logger) autorest.RespondDecorator {\n\treturn func(r autorest.Responder) autorest.Responder {\n\t\treturn autorest.ResponderFunc(func(resp *http.Response) error {\n\t\t\tif resp != nil {\n\t\t\t\tprovider, resource := parseServiceURL(resp.Request.URL.Path)\n\t\t\t\tapiRequestCounter.WithLabelValues(provider, resource, strconv.Itoa(resp.StatusCode)).Inc()\n\n\t\t\t\tif logger.GetLogLevel() == log.DebugLevel {\n\t\t\t\t\tif start, ok := resp.Request.Context().Value(timeKey).(time.Time); ok {\n\t\t\t\t\t\tlogger.\n\t\t\t\t\t\t\tWith(\"path\", resp.Request.URL.Path).\n\t\t\t\t\t\t\tWith(\"status\", resp.StatusCode).\n\t\t\t\t\t\t\tWith(\"time\", time.Since(start)).\n\t\t\t\t\t\t\tDebug(\"request\")\n\t\t\t\t\t}\n\n\t\t\t\t\tif dump, e := httputil.DumpResponse(resp, false); e == nil {\n\t\t\t\t\t\tlogger.Debug(string(dump))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn r.Respond(resp)\n\t\t})\n\t}\n}", "func (r *response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn r.ResponseWriter.(http.Hijacker).Hijack()\n}", "func newResponse(r *http.Response) *Response {\n\treturn &Response{Response: r}\n}", "func (chain HandlerInterceptorChain) InjectHttpHandler(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// short circuit\n\t\tif len(chain.interceptors) == 0 {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\t// record where to reverse\n\t\tvar it = -1\n\t\tdefer func() {\n\t\t\tdefer func() {\n\t\t\t\terr := recover()\n\t\t\t\t// no filter\n\t\t\t\tif it == -1 {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tfor i := it; i >= 0; i-- {\n\t\t\t\t\tchain.interceptors[i].AfterCompletion(w, r, err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tfor i := it; i >= 0; i-- {\n\t\t\t\tchain.interceptors[i].PostHandle(w, r)\n\t\t\t}\n\t\t}()\n\n\t\tfor i, filter := range chain.interceptors {\n\t\t\terr := filter.PreHandle(w, r)\n\t\t\tif err != nil {\n\t\t\t\t// assumes that this interceptor has already dealt with the response itself\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// the execution chain should proceed with the next interceptor or the handler itself\n\t\t\tit = i\n\t\t}\n\n\t\tfor i := range chain.interceptors {\n\t\t\tnext = chain.interceptors[len(chain.interceptors)-1-i].WrapHandle(next)\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n\n}", "func normalResponse(w http.ResponseWriter, r *http.Request){\n\trespStr := `<html>\n<head><title> My Custom Response </title> </head>\n<body> <h1> Testing the response headers ...... </h1></body>\n</html>`\nw.Write([]byte(respStr))\n}", "func forwardResponse(w http.ResponseWriter, response *http.Response) error {\n\tw.Header().Del(\"Server\") // remove Server: Caddy, append via instead\n\tw.Header().Add(\"Via\", strconv.Itoa(response.ProtoMajor)+\".\"+strconv.Itoa(response.ProtoMinor)+\" caddy\")\n\n\tfor header, values := range response.Header {\n\t\tfor _, val := range values {\n\t\t\tw.Header().Add(header, val)\n\t\t}\n\t}\n\tremoveHopByHop(w.Header())\n\tw.WriteHeader(response.StatusCode)\n\tbuf := bufferPool.Get().([]byte)\n\tbuf = buf[0:cap(buf)]\n\t_, err := io.CopyBuffer(w, response.Body, buf)\n\tbufferPool.Put(buf)\n\treturn err\n}", "func (ser *ProxyServe) logResponse(res *http.Response, ctx *goproxy.ProxyCtx) {\n\tif ctx.UserData == nil {\n\t\tlog.Println(\"err,userdata not reqid,log res skip\")\n\t\treturn\n\t}\n\treqCtx := ctx.UserData.(*requestCtx)\n\tif reqCtx.Docid < 1 {\n\t\treturn\n\t}\n\tdata := kvType{}\n\tdata[\"session_id\"] = ctx.Session\n\tdata[\"now\"] = time.Now().Unix()\n\tdata[\"header\"] = map[string][]string(res.Header)\n\tdata[\"status\"] = res.StatusCode\n\tdata[\"content_length\"] = res.ContentLength\n\n\tres_dump, dump_err := httputil.DumpResponse(res, false)\n\tif dump_err != nil {\n\t\tlog.Println(\"dump res err\", dump_err)\n\t\tres_dump = []byte(\"dump res failed\")\n\t}\n\tdata[\"dump\"] = base64.StdEncoding.EncodeToString(res_dump)\n\t// data[\"cookies\"]=res.Cookies()\n\n\tbody := []byte(\"pproxy skip\")\n\tif res.ContentLength <= ser.MaxResSaveLength {\n\t\tbuf := forgetRead(&res.Body)\n\t\tif res.Header.Get(Content_Encoding) == \"gzip\" {\n\t\t\tbody = []byte(gzipDocode(buf))\n\t\t} else {\n\t\t\tbody = buf.Bytes()\n\t\t}\n\t}\n\tdata[\"body\"] = base64.StdEncoding.EncodeToString(body)\n\n\terr := ser.mydb.ResponseTable.InsertRecovery(reqCtx.Docid, data)\n\n\tlog.Println(\"save_res\", ctx.Session, \"docid=\", reqCtx.Docid, \"body_len=\", len(data[\"body\"].(string)), err)\n}", "func (self *Proxy) AddInterceptor(dir Interceptor) {\n\tself.Interceptors = append(self.Interceptors, dir)\n}", "func NewResponse(ctx iris.Context) Response {\n\treturn Response{ctx: ctx}\n}", "func responseMiddleware() martini.Handler {\n\treturn func(w http.ResponseWriter, enc Encoder, l log.Logger, e *errEncoder, c martini.Context) {\n\t\tc.MapTo(&response{w.(martini.ResponseWriter), enc, l, e}, (*Response)(nil))\n\t}\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := Response{Response: r}\n\n\treturn &response\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := &Response{Response: r}\n\treturn response\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := &Response{Response: r}\n\treturn response\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := &Response{Response: r}\n\treturn response\n}", "func (self *Commands) Intercept(match string, args *InterceptArgs) error {\n\tif args == nil {\n\t\targs = &InterceptArgs{}\n\t}\n\n\tdefaults.SetDefaults(args)\n\n\tif filename := args.File; filename != `` {\n\t\tif file, err := self.browser.GetReaderForPath(filename); err == nil {\n\t\t\tdefer file.Close()\n\n\t\t\tbuf := bytes.NewBuffer(nil)\n\n\t\t\tif _, err := io.Copy(buf, file); err == nil {\n\t\t\t\targs.Body = buf\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else if contents, ok := args.Body.(string); ok {\n\t\targs.Body = bytes.NewBufferString(contents)\n\t} else if reader, ok := args.Body.(io.Reader); ok {\n\t\targs.Body = reader\n\t} else if contents, ok := args.Body.([]byte); ok {\n\t\targs.Body = bytes.NewBuffer(contents)\n\t} else if contents, ok := args.Body.([]uint8); ok {\n\t\targs.Body = bytes.NewBuffer([]byte(contents))\n\t} else {\n\t\treturn fmt.Errorf(\"Must specify a filename or reader\")\n\t}\n\n\treturn self.browser.Tab().AddNetworkIntercept(match, args.WaitForHeaders, func(tab *browser.Tab, pattern *browser.NetworkRequestPattern, event *browser.Event) *browser.NetworkInterceptResponse {\n\t\tresponse := &browser.NetworkInterceptResponse{\n\t\t\tAutoremove: !args.Persistent,\n\t\t}\n\n\t\tif reader, ok := args.Body.(io.Reader); ok {\n\t\t\tlog.Debugf(\"Setting request body override\")\n\t\t\tresponse.Body = reader\n\t\t}\n\n\t\tif status := event.P().Int(`responseStatusCode`); len(args.Statuses) == 0 || sliceutil.Contains(args.Statuses, status) {\n\t\t\tif args.Reject {\n\t\t\t\tresponse.Error = errors.New(`Aborted`)\n\t\t\t}\n\n\t\t\tif method := args.Method; method != `` {\n\t\t\t\tresponse.Method = method\n\t\t\t}\n\n\t\t\tif url := args.URL; url != `` {\n\t\t\t\tresponse.URL = url\n\t\t\t}\n\n\t\t\tif hdr := args.Headers; len(hdr) > 0 {\n\t\t\t\tresponse.Header = make(http.Header)\n\n\t\t\t\tfor k, v := range hdr {\n\t\t\t\t\tresponse.Header.Set(k, stringutil.MustString(v))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif data := args.PostData; len(data) > 0 {\n\t\t\t\tresponse.PostData = data\n\t\t\t}\n\n\t\t\tif origin := event.P().String(`authChallenge.origin`); origin != `` {\n\t\t\t\tif args.Realm == `` || args.Realm == event.P().String(`authChallenge.realm`) {\n\t\t\t\t\tu := args.Username\n\t\t\t\t\tp := args.Password\n\n\t\t\t\t\tif u == `` && p == `` {\n\t\t\t\t\t\tresponse.AuthResponse = `Cancel`\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.AuthResponse = `ProvideCredentials`\n\t\t\t\t\t\tresponse.Username = u\n\t\t\t\t\t\tresponse.Password = p\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn response\n\t})\n}", "func (client *OutputsClient) createOrReplaceHandleResponse(resp *http.Response) (OutputsCreateOrReplaceResponse, error) {\n\tresult := OutputsCreateOrReplaceResponse{RawResponse: resp}\n\tif val := resp.Header.Get(\"ETag\"); val != \"\" {\n\t\tresult.ETag = &val\n\t}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.Output); err != nil {\n\t\treturn OutputsCreateOrReplaceResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func (response *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn response.Writer.(http.Hijacker).Hijack()\n}", "func (t *RpcServ) UnaryInterceptor() grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,\n\t\thandler grpc.UnaryHandler) (resp interface{}, err error) {\n\n\t\t// panic recover\n\t\tdefer func() {\n\t\t\tif e := recover(); e != nil {\n\t\t\t\tt.log.Error(\"Rpc server happen panic.\", \"error\", e, \"rpc_method\", info.FullMethod)\n\t\t\t}\n\t\t}()\n\n\t\t// set request header\n\t\ttype HeaderInterface interface {\n\t\t\tGetHeader() *pb.ReqHeader\n\t\t}\n\t\tif req.(HeaderInterface).GetHeader() == nil {\n\t\t\theader := reflect.ValueOf(req).Elem().FieldByName(\"Header\")\n\t\t\tif header.IsValid() && header.IsNil() && header.CanSet() {\n\t\t\t\theader.Set(reflect.ValueOf(t.defReqHeader()))\n\t\t\t}\n\t\t}\n\t\tif req.(HeaderInterface).GetHeader().GetLogId() == \"\" {\n\t\t\treq.(HeaderInterface).GetHeader().LogId = utils.GenLogId()\n\t\t}\n\t\treqHeader := req.(HeaderInterface).GetHeader()\n\n\t\t// set request context\n\t\treqCtx, _ := t.createReqCtx(ctx, reqHeader)\n\t\tctx = sctx.WithReqCtx(ctx, reqCtx)\n\n\t\t// output access log\n\t\tlogFields := make([]interface{}, 0)\n\t\tlogFields = append(logFields, \"from\", reqHeader.GetSelfName(),\n\t\t\t\"client_ip\", reqCtx.GetClientIp(), \"rpc_method\", info.FullMethod)\n\t\treqCtx.GetLog().Trace(\"access request\", logFields...)\n\n\t\t// handle request\n\t\t// 根据err自动设置响应错误码,err需要是定义的标准err,否则会响应为未知错误\n\t\tstdErr := ecom.ErrSuccess\n\t\trespRes, err := handler(ctx, req)\n\t\tif err != nil {\n\t\t\tstdErr = ecom.CastError(err)\n\t\t}\n\t\t// 根据错误统一设置header,对外统一响应err=nil,通过Header.ErrCode判断\n\t\trespHeader := &pb.RespHeader{\n\t\t\tLogId: reqHeader.GetLogId(),\n\t\t\tErrCode: int64(stdErr.Code),\n\t\t\tErrMsg: stdErr.Msg,\n\t\t\tTraceId: t.genTraceId(),\n\t\t}\n\t\t// 通过反射设置header到response\n\t\theader := reflect.ValueOf(respRes).Elem().FieldByName(\"Header\")\n\t\tif header.IsValid() && header.IsNil() && header.CanSet() {\n\t\t\theader.Set(reflect.ValueOf(respHeader))\n\t\t}\n\n\t\t// output ending log\n\t\t// 可以通过log库提供的SetInfoField方法附加输出到ending log\n\t\tlogFields = append(logFields, \"status\", stdErr.Status, \"err_code\", stdErr.Code,\n\t\t\t\"err_msg\", stdErr.Msg, \"cost_time\", reqCtx.GetTimer().Print())\n\t\treqCtx.GetLog().Info(\"request done\", logFields...)\n\n\t\treturn respRes, nil\n\t}\n}", "func RegisterInterceptor(newRI RequestInterceptor) (restore func()) {\n\toldRI := registeredInterceptor\n\tregisteredInterceptor = newRI\n\treturn func() {\n\t\tregisteredInterceptor = oldRI\n\t}\n}", "func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\thj, ok := r.ResponseWriter.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"webserver doesn't support hijacking\")\n\t}\n\treturn hj.Hijack()\n}", "func (client *OutputsClient) createOrReplaceHandleResponse(resp *http.Response) (OutputsClientCreateOrReplaceResponse, error) {\n\tresult := OutputsClientCreateOrReplaceResponse{}\n\tif val := resp.Header.Get(\"ETag\"); val != \"\" {\n\t\tresult.ETag = &val\n\t}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.Output); err != nil {\n\t\treturn OutputsClientCreateOrReplaceResponse{}, err\n\t}\n\treturn result, nil\n}", "func (c *CustomContext) injectRequestID(prev zerolog.Logger) zerolog.Logger {\n\tid := c.Response().Header().Get(echo.HeaderXRequestID)\n\treturn prev.With().Str(\"requestId\", id).Logger()\n}", "func (hs *HTTPSpanner) Decorate(appName string, next http.Handler) http.Handler {\n\tif hs == nil {\n\t\t// allow DI of nil values to shut off money trace\n\t\treturn next\n\t}\n\n\treturn http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {\n\t\tif span, err := hs.SD(request); err == nil {\n\t\t\tspan.AppName, span.Name = appName, \"ServeHTTP\"\n\t\t\ttracker := hs.Start(request.Context(), span)\n\n\t\t\tctx := context.WithValue(request.Context(), contextKeyTracker, tracker)\n\n\t\t\ts := simpleResponseWriter{\n\t\t\t\tcode: http.StatusOK,\n\t\t\t\tResponseWriter: response,\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(s, request.WithContext(ctx))\n\n\t\t\t//TODO: application and not library code should finish the above tracker\n\t\t\t//such that information on it could be forwarded\n\t\t\t//once confirmed, delete the below\n\n\t\t\t// tracker.Finish(Result{\n\t\t\t// \tName: \"ServeHTTP\",\n\t\t\t// \tAppName: appName,\n\t\t\t// \tCode: s.code,\n\t\t\t// \tSuccess: s.code < 400,\n\t\t\t// })\n\n\t\t} else {\n\t\t\tnext.ServeHTTP(response, request)\n\t\t}\n\t})\n}", "func (client HTTPSuccessClient) Patch200Responder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func AddResponse(jc *jenkins.Client, method string, urlPath string, resp Response) {\n\tkey := fmt.Sprintf(keyFmt, strings.ToUpper(method), urlPath)\n\tjc.HTTPClient.Transport.(RequestMocker).RequestMap[key] = resp\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := &Response{Response: r}\n\tresponse.populatePageValues()\n\treturn response\n}", "func NewResponseCapture(w http.ResponseWriter) *ResponseCapture {\n\treturn &ResponseCapture{\n\t\tResponseWriter: w,\n\t\twroteHeader: false,\n\t\tbody: new(bytes.Buffer),\n\t}\n}", "func Wrap(w http.ResponseWriter) JResponseWriter {\n\tif w, ok := w.(JResponseWriter); ok {\n\t\treturn w\n\t}\n\n\tif w.Header().Get(\"Content-Type\") == \"\" {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t}\n\n\treturn &Response{rw: w, fields: make(map[string]interface{})}\n}", "func CreateResponse(w *gin.Context, payload interface{}) {\n\tw.JSON(200, payload)\n}", "func (h *middlewareHarness) interceptStream(methodURI string,\n\texpectedRequest proto.Message, responseReplacement proto.Message,\n\treadOnly bool) {\n\n\t// Read intercept message and make sure it's for an RPC stream auth.\n\tauthIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\n\t// Make sure the custom condition is populated correctly (if we're using\n\t// a macaroon with a custom condition).\n\tif !readOnly {\n\t\trequire.Equal(\n\t\t\th.t, \"itest-value\", authIntercept.CustomCaveatCondition,\n\t\t)\n\t}\n\n\tauth := authIntercept.GetStreamAuth()\n\trequire.NotNil(h.t, auth)\n\n\t// This is just the authentication, so we can only look at the URI.\n\trequire.Equal(h.t, methodURI, auth.MethodFullUri)\n\n\t// We need to accept the auth.\n\th.sendAccept(authIntercept.MsgId, nil)\n\n\t// Read intercept message and make sure it's for an RPC request.\n\treqIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\treq := reqIntercept.GetRequest()\n\trequire.NotNil(h.t, req)\n\n\t// We know the request we're going to send so make sure we get the right\n\t// type and content from the interceptor.\n\trequire.Equal(h.t, methodURI, req.MethodFullUri)\n\tassertInterceptedType(h.t, expectedRequest, req)\n\n\t// We need to accept the request.\n\th.sendAccept(reqIntercept.MsgId, nil)\n\n\t// Now read the intercept message for the response.\n\trespIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\tres := respIntercept.GetResponse()\n\trequire.NotNil(h.t, res)\n\n\t// We expect the request ID to be the same for the auth intercept,\n\t// request intercept and the response intercept messages. But the\n\t// message IDs must be different/unique.\n\trequire.Equal(h.t, authIntercept.RequestId, respIntercept.RequestId)\n\trequire.Equal(h.t, reqIntercept.RequestId, respIntercept.RequestId)\n\trequire.NotEqual(h.t, authIntercept.MsgId, reqIntercept.MsgId)\n\trequire.NotEqual(h.t, authIntercept.MsgId, respIntercept.MsgId)\n\trequire.NotEqual(h.t, reqIntercept.MsgId, respIntercept.MsgId)\n\n\t// We need to accept the response as well.\n\th.sendAccept(respIntercept.MsgId, responseReplacement)\n\n\th.responsesChan <- res\n}", "func ResponseHeaders(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t// Timings\n\t\tt := timings.Tracker{}\n\t\tt.Start()\n\n\t\t// Make a new PluggableResponseWriter if we need to\n\t\tDebugOut.Printf(\"ResponseHeaders Pluggable ResponseWriter...\\n\")\n\t\trw, _ := prw.NewPluggableResponseWriterIfNot(w)\n\t\tdefer rw.Flush()\n\n\t\t// NOTE: we do this early in the event a Flush() is called during\n\t\t// the pre-response-end phase\n\t\trmHeaders := make([]string, 0)\n\t\taddHeaders := make(map[string]string)\n\t\tfor _, header := range Conf.GetStringSlice(ConfigHeaders) {\n\t\t\tif strings.Contains(header, \" \") {\n\t\t\t\t// Set it\n\t\t\t\thparts := strings.SplitN(header, \" \", 2)\n\t\t\t\thvalue := hparts[1]\n\t\t\t\tif strings.Contains(hvalue, \"%%\") {\n\t\t\t\t\thvalue = MacroDictionary.Replacer(hvalue)\n\t\t\t\t}\n\t\t\t\taddHeaders[hparts[0]] = hvalue\n\t\t\t} else {\n\t\t\t\t// Queue it for removal\n\t\t\t\trmHeaders = append(rmHeaders, header)\n\t\t\t}\n\t\t}\n\n\t\t// Pass along the headers to remove or add to PRW (flush-safe)\n\t\trw.SetHeadersToRemove(rmHeaders)\n\t\trw.SetHeadersToAdd(addHeaders)\n\n\t\tTimingOut.Printf(\"ResponseHeaders handler took %s\\n\", t.Since().String())\n\t\tnext.ServeHTTP(rw, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (c *IRacing) AfterResponse(f AfterFunc) {\n\tc.AfterFuncs = append(c.AfterFuncs, f)\n}", "func ResponseAddHeader(key, value string) ResponseModifier {\n\treturn func(resp *http.Response, err error) (*http.Response, error) {\n\t\tif resp != nil {\n\t\t\tif resp.Header == nil {\n\t\t\t\tresp.Header = make(http.Header)\n\t\t\t}\n\t\t\tresp.Header.Add(key, value)\n\t\t}\n\t\treturn resp, err\n\t}\n}", "func setResponseCacheControlHeader(rw http.ResponseWriter, maxAge int) {\n\tcacheControl := \"\"\n\tif maxAge >= 0 {\n\t\tcacheControl = fmt.Sprintf(\"public, max-age=%d\", maxAge)\n\t} else {\n\t\tcacheControl = \"must-revalidate, no-cache, no-store\"\n\t}\n\n\trw.Header().Set(\"Cache-Control\", cacheControl)\n}", "func Response(ctx *gin.Context, httpStatus int, code int, msg string, data interface{}) {\n\tctx.JSON(httpStatus, &Body{Code: code, Msg: msg, Data: data})\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := &Response{Response: r}\n\tresponse.populatePageValues()\n\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err == nil && data != nil {\n\t\tjson.Unmarshal(data, response)\n\t}\n\n\treturn response\n}", "func (o *CreateACLAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\t// response header Reload-ID\n\n\treloadID := o.ReloadID\n\tif reloadID != \"\" {\n\t\trw.Header().Set(\"Reload-ID\", reloadID)\n\t}\n\n\trw.WriteHeader(202)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func InjectTrace(ctx context.Context, incomingReq *restful.Request,\n\toutgoingReq *http.Request) (*http.Request, opentracing.Span, context.Context) {\n\tspan, newCtx := StartSpanFromContext(ctx, \"outgoing request\")\n\tif span != nil {\n\t\text.HTTPUrl.Set(span, outgoingReq.Host+outgoingReq.RequestURI)\n\t\text.HTTPMethod.Set(span, outgoingReq.Method)\n\t\t_ = span.Tracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(outgoingReq.Header))\n\n\t\tfor _, header := range forwardHeaders {\n\t\t\tif value := incomingReq.Request.Header.Get(header); value != \"\" {\n\t\t\t\toutgoingReq.Header.Set(header, value)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn outgoingReq, nil, nil\n\t}\n\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range outgoingReq.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\n\t\tlogrus.Debug(\"outgoing header : \", header)\n\t}\n\n\tif abTraceID := incomingReq.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\toutgoingReq.Header.Set(event.TraceIDKey, abTraceID)\n\t}\n\n\treturn outgoingReq, span, newCtx\n}", "func NewResponseWrapper(responseWriter http.ResponseWriter) *ResponseWrapper {\n\treturn &ResponseWrapper{\n\t\tResponseWriter: responseWriter,\n\t}\n}", "func NewResponse(pt *influx.Point, tr *Tracer) Response {\r\n\treturn Response{\r\n\t\tPoint: pt,\r\n\t\tTracer: tr,\r\n\t}\r\n}", "func (r Response) UseProxy(code string, payload Payload, header ...ResponseHeader) {\n\tr.Response(code, http.UseProxy, payload, header...)\n}", "func (l *Lambda) ResponseHeaderSet(header, value string) {\n\tl.w.Header().Set(header, value)\n}", "func Response(c *gin.Context, status int, body interface{}) {\n\taccType := c.GetHeader(\"Accept\")\n\tif accType == \"application/xml\" {\n\t\tc.XML(status, body)\n\t\treturn\n\t}\n\tc.JSON(status, body)\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := &Response{Response: r}\n\tresponse.Rate = parseRate(r)\n\treturn response\n}", "func InjectHeader(h http.Header) InterceptorFn {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn RoundTripperFn(func(req *http.Request) (*http.Response, error) {\n\t\t\tfor k, v := range h {\n\t\t\t\tfor _, vv := range v {\n\t\t\t\t\treq.Header.Add(k, vv)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn rt.RoundTrip(req)\n\t\t})\n\t}\n}", "func (h *middlewareHarness) interceptUnary(methodURI string,\n\texpectedRequest proto.Message, responseReplacement proto.Message,\n\treadOnly bool) {\n\n\t// Read intercept message and make sure it's for an RPC request.\n\treqIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\n\t// Make sure the custom condition is populated correctly (if we're using\n\t// a macaroon with a custom condition).\n\tif !readOnly {\n\t\trequire.Equal(\n\t\t\th.t, \"itest-value\", reqIntercept.CustomCaveatCondition,\n\t\t)\n\t}\n\n\treq := reqIntercept.GetRequest()\n\trequire.NotNil(h.t, req)\n\n\t// We know the request we're going to send so make sure we get the right\n\t// type and content from the interceptor.\n\trequire.Equal(h.t, methodURI, req.MethodFullUri)\n\tassertInterceptedType(h.t, expectedRequest, req)\n\n\t// We need to accept the request.\n\th.sendAccept(reqIntercept.MsgId, nil)\n\n\t// Now read the intercept message for the response.\n\trespIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\tres := respIntercept.GetResponse()\n\trequire.NotNil(h.t, res)\n\n\t// We expect the request ID to be the same for the request intercept\n\t// and the response intercept messages. But the message IDs must be\n\t// different/unique.\n\trequire.Equal(h.t, reqIntercept.RequestId, respIntercept.RequestId)\n\trequire.NotEqual(h.t, reqIntercept.MsgId, respIntercept.MsgId)\n\n\t// We need to accept the response as well.\n\th.sendAccept(respIntercept.MsgId, responseReplacement)\n\n\th.responsesChan <- res\n}", "func InjectLoggerInterceptor(rootLogger *zerolog.Logger) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\t\tctx = rootLogger.With().Timestamp().Logger().Hook(sourceLocationHook).WithContext(ctx)\n\n\t\tmd, ok := metadata.FromIncomingContext(ctx)\n\t\tif !ok {\n\t\t\treturn handler(ctx, req)\n\t\t}\n\t\tvalues := md.Get(\"x-cloud-trace-context\")\n\t\tif len(values) != 1 {\n\t\t\treturn handler(ctx, req)\n\t\t}\n\n\t\ttraceID, _ := traceContextFromHeader(values[0])\n\t\tif traceID == \"\" {\n\t\t\treturn handler(ctx, req)\n\t\t}\n\t\ttrace := fmt.Sprintf(\"projects/%s/traces/%s\", projectID, traceID)\n\n\t\tlog.Ctx(ctx).UpdateContext(func(c zerolog.Context) zerolog.Context {\n\t\t\treturn c.Str(\"logging.googleapis.com/trace\", trace)\n\t\t})\n\n\t\treturn handler(ctx, req)\n\t}\n}", "func (h *Handler) buildResponse(w http.ResponseWriter, r *http.Request, origin string, method string, headers string) {\n\tw.Header().Set(allowOriginHeader, origin)\n\tw.Header().Set(allowMethodsHeader, method)\n\tw.Header().Set(allowHeadersHeader, headers)\n}", "func (s *Plugin) MockResponse(ctx context.Context, mock *v1alpha1.MockAPI_Response, request *interact.Request, response *interact.Response) (abort bool, err error) {\n\tsimple := mock.GetSimple()\n\tif simple == nil {\n\t\treturn false, nil\n\t}\n\tc := core.NewContext(request)\n\n\t// Render Code\n\tresponse.Code = simple.GetCode()\n\t// Render Headers\n\tresponse.Header = map[string]string{}\n\tfor key, val := range simple.GetHeader() {\n\t\tresponse.Header[key] = core.Render(c, val)\n\t}\n\t// Render Trailers\n\tresponse.Trailer = map[string]string{}\n\tfor key, val := range simple.GetTrailer() {\n\t\tresponse.Trailer[key] = val\n\t}\n\t// Render Body\n\tdata, err := fasttemplate.ExecuteFuncStringWithErr(simple.GetBody(), \"{{\", \"}}\", func(w io.Writer, tag string) (int, error) {\n\t\treturn w.Write([]byte(core.Render(c, strings.TrimSpace(tag))))\n\t})\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tresponse.Body = interact.NewBytesMessage([]byte(data))\n\treturn false, nil\n}", "func ResponseSetHeader(key, value string) ResponseModifier {\n\treturn func(resp *http.Response, err error) (*http.Response, error) {\n\t\tif resp != nil {\n\t\t\tif resp.Header == nil {\n\t\t\t\tresp.Header = make(http.Header)\n\t\t\t}\n\t\t\tresp.Header.Set(key, value)\n\t\t}\n\t\treturn resp, err\n\t}\n}", "func newResponse(data map[string]string) (*AMIResponse, error) {\n\tr, found := data[\"Response\"]\n\tif !found {\n\t\treturn nil, errors.New(\"Not Response\")\n\t}\n\tresponse := &AMIResponse{ID: data[\"ActionID\"], Status: r, Params: make(map[string]string)}\n\tfor k, v := range data {\n\t\tif k == \"Response\" {\n\t\t\tcontinue\n\t\t}\n\t\tresponse.Params[k] = v\n\t}\n\treturn response, nil\n}", "func New() *Interceptor {\n\treturn &Interceptor{}\n}", "func ParseResponse(mapWrapper *cmap.ConcurrentMap, command model.Command, err error, customResponse *model.CustomResponse) model.CustomResponse {\n\n\tresultWrapper := model.Wrapper{\n\t\tConfigure: model.Configure{\n\t\t\tResponse: command,\n\t\t},\n\t\tResponse: cmap.New(),\n\t}\n\n\tresultWrapper.Response.Set(\"statusCode\", 0)\n\tresultWrapper.Response.Set(\"header\", make(map[string]interface{}))\n\tresultWrapper.Response.Set(\"body\", make(map[string]interface{}))\n\n\t//* now we will set the response body based from configurex.json if there is $configure value in configureBased.\n\n\ttmpHeader := make(map[string]interface{})\n\ttmpBody := make(map[string]interface{})\n\n\tstatusCode := 400\n\tif customResponse != nil {\n\t\tif customResponse.Header != nil {\n\t\t\ttmpHeader = customResponse.Header\n\t\t}\n\t\tif customResponse.Body != nil {\n\t\t\ttmpBody = customResponse.Body\n\t\t}\n\n\t\tif customResponse.StatusCode > 0 {\n\t\t\tstatusCode = customResponse.StatusCode\n\n\t\t} else {\n\t\t\tlog.Warn(\"status code is not defined, set status code to 400\")\n\t\t\t// default\n\t\t\tstatusCode = 400\n\n\t\t}\n\t}\n\n\t// if status code is specified in configure, then set status code based on configure\n\tif command.StatusCode > 0 {\n\t\tstatusCode = command.StatusCode\n\t}\n\n\t//*header\n\ttmpHeader = service.AddToWrapper(resultWrapper.Configure.Response.Adds.Header, \"--\", tmpHeader, mapWrapper, 0)\n\t//*modify header\n\ttmpHeader = service.ModifyWrapper(resultWrapper.Configure.Response.Modifies.Header, \"--\", tmpHeader, mapWrapper, 0)\n\t//*Deletion Header\n\ttmpHeader = service.DeletionHeaderOrQuery(resultWrapper.Configure.Response.Deletes.Header, tmpHeader)\n\n\t//*add\n\ttmpBody = service.AddToWrapper(resultWrapper.Configure.Response.Adds.Body, \"--\", tmpBody, mapWrapper, 0)\n\t//*modify\n\ttmpBody = service.ModifyWrapper(resultWrapper.Configure.Response.Modifies.Body, \"--\", tmpBody, mapWrapper, 0)\n\t//* delete\n\ttmpBody = service.DeletionBody(resultWrapper.Configure.Response.Deletes, tmpBody)\n\n\t//*In case user want to log final response\n\tif len(resultWrapper.Configure.Response.LogAfterModify) > 0 {\n\t\tlogValue := make(map[string]interface{}) // v\n\t\tfor key, val := range resultWrapper.Configure.Response.LogAfterModify {\n\t\t\tlogValue[key] = service.GetFromHalfReferenceValue(val, resultWrapper.Response, 0)\n\t\t}\n\t\t//logValue := service.GetFromHalfReferenceValue(resultWrapper.Configure.Response.LogAfterModify, resultWrapper.Response, 0)\n\t\tutil.DoLoggingJson(logValue, \"after\", \"final response\", false)\n\t}\n\n\tresponse := model.CustomResponse{\n\t\tStatusCode: statusCode,\n\t\tHeader: tmpHeader,\n\t\tBody: tmpBody,\n\t\tError: err,\n\t}\n\n\treturn response\n}", "func (b *BaseHandler) Response() http.ResponseWriter {\n\treturn b.getResponse()\n}", "func (w *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tw.hijacked = true\n\tconn := newNodeConn(w.Value, w.reqReader)\n\tbrw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))\n\treturn conn, brw, nil\n\n}", "func (client *ContainerClient) renameHandleResponse(resp *http.Response) (ContainerClientRenameResponse, error) {\n\tresult := ContainerClientRenameResponse{}\n\tif val := resp.Header.Get(\"x-ms-client-request-id\"); val != \"\" {\n\t\tresult.ClientRequestID = &val\n\t}\n\tif val := resp.Header.Get(\"x-ms-request-id\"); val != \"\" {\n\t\tresult.RequestID = &val\n\t}\n\tif val := resp.Header.Get(\"x-ms-version\"); val != \"\" {\n\t\tresult.Version = &val\n\t}\n\tif val := resp.Header.Get(\"Date\"); val != \"\" {\n\t\tdate, err := time.Parse(time.RFC1123, val)\n\t\tif err != nil {\n\t\t\treturn ContainerClientRenameResponse{}, err\n\t\t}\n\t\tresult.Date = &date\n\t}\n\treturn result, nil\n}", "func NewProxy(director *upstream.Director) elton.Handler {\n\treturn func(c *elton.Context) (err error) {\n\t\t// 如果请求是从缓存读取Cacheable ,则直接跳过\n\t\tstatus, ok := c.Get(df.Status).(int)\n\t\tif ok && status == cache.Cacheable {\n\t\t\treturn c.Next()\n\t\t}\n\t\toriginalNext := c.Next\n\t\t// 由于proxy中间件会调用next,因此直接覆盖,\n\t\t// 避免导致先执行了后续的中间件\n\t\tc.Next = func() error {\n\t\t\treturn nil\n\t\t}\n\n\t\tvar ifModifiedSince, ifNoneMatch, acceptEncoding string\n\t\treqHeader := c.Request.Header\n\t\t// proxy时为了避免304的出现,因此调用时临时删除header\n\t\t// 如果是 pass 则无需删除,其它的需要删除(因为此时无法确认数据是否可缓存)\n\t\tif status != cache.Pass &&\n\t\t\tstatus != cache.HitForPass {\n\t\t\tacceptEncoding = reqHeader.Get(elton.HeaderAcceptEncoding)\n\t\t\tifModifiedSince = reqHeader.Get(elton.HeaderIfModifiedSince)\n\t\t\tifNoneMatch = reqHeader.Get(elton.HeaderIfNoneMatch)\n\t\t\tif ifModifiedSince != \"\" {\n\t\t\t\treqHeader.Del(elton.HeaderIfModifiedSince)\n\t\t\t}\n\t\t\tif ifNoneMatch != \"\" {\n\t\t\t\treqHeader.Del(elton.HeaderIfNoneMatch)\n\t\t\t}\n\n\t\t\tif strings.Contains(acceptEncoding, df.GZIP) {\n\t\t\t\treqHeader.Set(elton.HeaderAcceptEncoding, df.GZIP)\n\t\t\t} else {\n\t\t\t\treqHeader.Del(elton.HeaderAcceptEncoding)\n\t\t\t}\n\t\t}\n\n\t\terr = director.Proxy(c)\n\n\t\t// 将原有的请求头恢复\n\t\tif acceptEncoding != \"\" {\n\t\t\treqHeader.Set(elton.HeaderAcceptEncoding, acceptEncoding)\n\t\t}\n\t\tif ifModifiedSince != \"\" {\n\t\t\treqHeader.Set(elton.HeaderIfModifiedSince, ifModifiedSince)\n\t\t}\n\t\tif ifNoneMatch != \"\" {\n\t\t\treqHeader.Set(elton.HeaderIfNoneMatch, ifNoneMatch)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, key := range clearHeaders {\n\t\t\t// 清除header\n\t\t\tc.SetHeader(key, \"\")\n\t\t}\n\t\treturn originalNext()\n\t}\n}", "func ParseReplacechangeaspecificInterceptionResponse(rsp *http.Response) (*ReplacechangeaspecificInterceptionResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &ReplacechangeaspecificInterceptionResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Interceptions\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func (resp *response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif resp.size < 0 {\n\t\tresp.size = 0\n\t}\n\treturn resp.ResponseWriter.(http.Hijacker).Hijack()\n}", "func Interceptor(opts ...Option) gin.HandlerFunc {\n\tset := newOptionSet(opts...)\n\n\treturn func(ctx *gin.Context) {\n\t\tctx.Set(rkgininter.RpcEntryNameKey, set.EntryName)\n\n\t\t// start timer\n\t\tstartTime := time.Now()\n\n\t\tctx.Next()\n\n\t\t// end timer\n\t\telapsed := time.Now().Sub(startTime)\n\n\t\t// ignoring /rk/v1/assets, /rk/v1/tv and /sw/ path while logging since these are internal APIs.\n\t\tif rkgininter.ShouldLog(ctx) {\n\t\t\tif durationMetrics := GetServerDurationMetrics(ctx); durationMetrics != nil {\n\t\t\t\tdurationMetrics.Observe(float64(elapsed.Nanoseconds()))\n\t\t\t}\n\t\t\tif len(ctx.Errors) > 0 {\n\t\t\t\tif errorMetrics := GetServerErrorMetrics(ctx); errorMetrics != nil {\n\t\t\t\t\terrorMetrics.Inc()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif resCodeMetrics := GetServerResCodeMetrics(ctx); resCodeMetrics != nil {\n\t\t\t\tresCodeMetrics.Inc()\n\t\t\t}\n\t\t}\n\t}\n}", "func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) (err error) {\n\tresp := response.(*common.XmidtResponse)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(common.HeaderWPATID, ctx.Value(common.ContextKeyRequestTID).(string))\n\tcommon.ForwardHeadersByPrefix(\"\", resp.ForwardedHeaders, w.Header())\n\n\tw.WriteHeader(resp.Code)\n\t_, err = w.Write(resp.Body)\n\treturn\n}", "func newResponse(r *http.Response) *Response {\n\tresp := &Response{\n\t\tResponse: r,\n\t}\n\tif v := r.Header.Get(headerXRemaining); v != \"\" {\n\t\tresp.Remaining, _ = strconv.Atoi(v)\n\t}\n\tif v := r.Header.Get(headerXReset); v != \"\" {\n\t\tresp.Reset, _ = strconv.Atoi(v)\n\t}\n\tif v := r.Header.Get(headerXTotal); v != \"\" {\n\t\tresp.Total, _ = strconv.Atoi(v)\n\t}\n\treturn resp\n}", "func OpenTracingServerInterceptor(parentSpan opentracing.Span) grpc.UnaryServerInterceptor {\n\ttracingInterceptor := otgrpc.OpenTracingServerInterceptor(\n\t\t// Use the globally installed tracer\n\t\topentracing.GlobalTracer(),\n\t\t// Log full payloads along with trace spans\n\t\totgrpc.LogPayloads(),\n\t)\n\tif parentSpan == nil {\n\t\treturn tracingInterceptor\n\t}\n\tspanContext := parentSpan.Context()\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,\n\t\thandler grpc.UnaryHandler) (interface{}, error) {\n\n\t\tmd, ok := metadata.FromIncomingContext(ctx)\n\t\tif !ok {\n\t\t\tmd = metadata.New(nil)\n\t\t}\n\t\tcarrier := metadataReaderWriter{md}\n\t\t_, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, carrier)\n\t\tif err == opentracing.ErrSpanContextNotFound {\n\t\t\tcontract.IgnoreError(opentracing.GlobalTracer().Inject(spanContext, opentracing.HTTPHeaders, carrier))\n\t\t}\n\t\treturn tracingInterceptor(ctx, req, info, handler)\n\t}\n\n}" ]
[ "0.6732688", "0.61742854", "0.61518264", "0.60882735", "0.6087335", "0.59464914", "0.5909216", "0.5903693", "0.58017325", "0.5780744", "0.57799304", "0.574046", "0.57401216", "0.5722633", "0.5645109", "0.5630329", "0.54868275", "0.5467772", "0.54632527", "0.5380859", "0.5380016", "0.5376029", "0.53739005", "0.5347959", "0.53407854", "0.53378135", "0.5337724", "0.5333694", "0.53126955", "0.5309879", "0.5301915", "0.53014714", "0.53010863", "0.52993715", "0.5290106", "0.5281495", "0.5279741", "0.5275336", "0.5275136", "0.5246023", "0.5232054", "0.52292246", "0.52244276", "0.5219074", "0.51814765", "0.51762336", "0.51758564", "0.5163028", "0.5157606", "0.5157606", "0.5157606", "0.51489687", "0.5148895", "0.514823", "0.5138011", "0.5137947", "0.5135983", "0.51347286", "0.5122549", "0.5119092", "0.5099077", "0.50942904", "0.5086763", "0.50784504", "0.50556225", "0.50551254", "0.5053525", "0.5048079", "0.50454354", "0.50289613", "0.5019875", "0.50192106", "0.501689", "0.50116783", "0.49937773", "0.49925822", "0.49909148", "0.49831825", "0.49785182", "0.49755907", "0.4975267", "0.4971469", "0.4971013", "0.4969855", "0.49681672", "0.49681222", "0.4963014", "0.495058", "0.4949417", "0.49489748", "0.49416336", "0.4938296", "0.49287018", "0.4927918", "0.49258873", "0.49226683", "0.4919164", "0.4908692", "0.4902933", "0.49003053" ]
0.79600096
0